text
stringlengths
54
60.6k
<commit_before>// // Created by Vadim N. on 16/03/2016. // // #include "benchutils.h" #include <Inference> using namespace ymir; using namespace std; int main(int argc, char* argv[]) { // if (argc < 2) { // std::cout << "Please re-run the script with the data folder path supplied." << std::endl; // return 1; // } // std::chrono::system_clock::time_point tp1, tp2; // std::vector< std::pair<std::string, size_t> > timepoints; // std::vector<prob_t> logLvec; // std::string temp_str; // time_t vj_single_parse, vdj_single_parse, // vj_single_prob, vj_single_meta, // vj_single_infer, vdj_single_prob, // vdj_single_meta, vdj_single_infer; // time_t vj_good_parse, vdj_good_parse, // vj_good_prob, vj_good_meta, // vj_good_infer, vdj_good_prob, // vdj_good_meta, vdj_good_infer; std::string BENCH_DATA_FOLDER = argv[1]; std::cout << "Data folder:\t[" << BENCH_DATA_FOLDER << "]" << endl; // // TCR alpha chain repertoire - VJ recombination // VDJRecombinationGenes vj_single_genes("Vgene", BENCH_DATA_FOLDER + "trav.txt", "Jgene", BENCH_DATA_FOLDER + "traj.txt"); VDJRecombinationGenes vj_single_genes2(vj_single_genes); VDJRecombinationGenes vj_single_genes3 = vj_single_genes; vj_single_genes2 = vj_single_genes; // string input_alpha_file = "alpha.250k.txt"; // string input_beta_file = "beta.250k.txt"; // CDR3NucParser parser; // Cloneset cloneset_vj; // YMIR_BENCHMARK("Parsing VJ", // parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file, // &cloneset_vj, // vj_single_genes, // NUCLEOTIDE, // VJ_RECOMB, // AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE), // VDJAlignerParameters(2))) // // // // TCR beta chain repertoire - VDJ recombination // // // // VDJRecombinationGenes vdj_single_genes("Vgene", // // BENCH_DATA_FOLDER + "trbv.txt", // // "Jgene", // // BENCH_DATA_FOLDER + "trbj.txt", // // "Dgene", // // BENCH_DATA_FOLDER + "trbd.txt"); // // // // Cloneset cloneset_vdj; // // YMIR_BENCHMARK("Parsing VDJ", // // parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file, // // &cloneset_vdj, // // vdj_single_genes, // // NUCLEOTIDE, // // VDJ_RECOMB, // // AlignmentColumnOptions() // // .setV(AlignmentColumnOptions::USE_PROVIDED) // // .setD(AlignmentColumnOptions::OVERWRITE) // // .setJ(AlignmentColumnOptions::USE_PROVIDED), // // VDJAlignerParameters(3))) // // // // VJ MAAG // // // ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY); // // // // VDJ MAAG // // // // ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY); // // // // Inference // // // vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000}; // vec_sample = { 100000 }; // vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; //, 2000, 5000, 10000}; // // vec_block = {2000, 5000, 10000}; // vec_block = { std::stoi(argv[2]) }; // vector<double> vec_alpha = {.5, .6, .7, .8, .9}; // vec_alpha = { std::stof(argv[3]) }; // vector<double> vec_beta = {.1, .5, 1, 3}; // vec_beta = { std::stof(argv[4]) }; // vector<double> vec_K = {1, 2, 3}; // vec_K = { std::stod(argv[5]) }; // ErrorMode error_mode = COMPUTE_ERRORS; // // int niter, sample, block; // // double alpha; // // niter = 10; // // int sample = 10000; // // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, niter, sample, error_mode) // // RUN_EM_INFERENCE(string("vdj"), cloneset_vdj, vdj_single_model, niter, sample, error_mode) // // for(auto val_sample: vec_sample) { // // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_sample, error_mode) // // } // // ModelParameterVector new_param_vec = vj_single_model.event_probabilities(); // // new_param_vec.fill(1); // // new_param_vec.normaliseEventFamilies(); // // vj_single_model.updateModelParameterVector(new_param_vec); // // // // auto rep_nonc = cloneset_vj.noncoding().sample(2500); // // auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true); // // vector<prob_t> prob_vec(maag_rep.size(), 0); // // // // vector<bool> good_clonotypes(maag_rep.size(), true); // // for (size_t i = 0; i < maag_rep.size(); ++i) { // // if (rep_nonc[i].is_good()) { // // prob_vec[i] = maag_rep[i].fullProbability(); // // if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) { // // good_clonotypes[i] = false; // // } // // } else { // // good_clonotypes[i] = false; // // } // // } // for(auto val_sample: vec_sample) { // for(auto val_block: vec_block) { // for (auto val_alpha: vec_alpha) { // for (auto val_beta: vec_beta) { // for (auto val_K: vec_K) { // RUN_SG_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode) // } // } // } // } // } } <commit_msg>debug<commit_after>// // Created by Vadim N. on 16/03/2016. // // #include "benchutils.h" #include <Inference> using namespace ymir; using namespace std; int main(int argc, char* argv[]) { // if (argc < 2) { // std::cout << "Please re-run the script with the data folder path supplied." << std::endl; // return 1; // } // std::chrono::system_clock::time_point tp1, tp2; // std::vector< std::pair<std::string, size_t> > timepoints; // std::vector<prob_t> logLvec; // std::string temp_str; // time_t vj_single_parse, vdj_single_parse, // vj_single_prob, vj_single_meta, // vj_single_infer, vdj_single_prob, // vdj_single_meta, vdj_single_infer; // time_t vj_good_parse, vdj_good_parse, // vj_good_prob, vj_good_meta, // vj_good_infer, vdj_good_prob, // vdj_good_meta, vdj_good_infer; // std::string BENCH_DATA_FOLDER = argv[1]; // std::cout << "Data folder:\t[" << BENCH_DATA_FOLDER << "]" << endl; // // TCR alpha chain repertoire - VJ recombination // VDJRecombinationGenes vj_single_genes("Vgene", "/home/vadim/ymir/benchmark/data/trav.txt", "Jgene", "/home/vadim/ymir/benchmark/data/traj.txt"); VDJRecombinationGenes vj_single_genes2(vj_single_genes); VDJRecombinationGenes vj_single_genes3 = vj_single_genes; vj_single_genes2 = vj_single_genes; // string input_alpha_file = "alpha.250k.txt"; // string input_beta_file = "beta.250k.txt"; // CDR3NucParser parser; // Cloneset cloneset_vj; // YMIR_BENCHMARK("Parsing VJ", // parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file, // &cloneset_vj, // vj_single_genes, // NUCLEOTIDE, // VJ_RECOMB, // AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::OVERWRITE), // VDJAlignerParameters(2))) // // // // TCR beta chain repertoire - VDJ recombination // // // // VDJRecombinationGenes vdj_single_genes("Vgene", // // BENCH_DATA_FOLDER + "trbv.txt", // // "Jgene", // // BENCH_DATA_FOLDER + "trbj.txt", // // "Dgene", // // BENCH_DATA_FOLDER + "trbd.txt"); // // // // Cloneset cloneset_vdj; // // YMIR_BENCHMARK("Parsing VDJ", // // parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file, // // &cloneset_vdj, // // vdj_single_genes, // // NUCLEOTIDE, // // VDJ_RECOMB, // // AlignmentColumnOptions() // // .setV(AlignmentColumnOptions::USE_PROVIDED) // // .setD(AlignmentColumnOptions::OVERWRITE) // // .setJ(AlignmentColumnOptions::USE_PROVIDED), // // VDJAlignerParameters(3))) // // // // VJ MAAG // // // ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + "../../models/hTRA", EMPTY); // // // // VDJ MAAG // // // // ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + "../../models/hTRB", EMPTY); // // // // Inference // // // vector<int> vec_sample = {10000, 25000, 50000, 100000, 150000}; // vec_sample = { 100000 }; // vector<int> vec_block = {500, 1000, 2000, 5000, 10000}; //, 2000, 5000, 10000}; // // vec_block = {2000, 5000, 10000}; // vec_block = { std::stoi(argv[2]) }; // vector<double> vec_alpha = {.5, .6, .7, .8, .9}; // vec_alpha = { std::stof(argv[3]) }; // vector<double> vec_beta = {.1, .5, 1, 3}; // vec_beta = { std::stof(argv[4]) }; // vector<double> vec_K = {1, 2, 3}; // vec_K = { std::stod(argv[5]) }; // ErrorMode error_mode = COMPUTE_ERRORS; // // int niter, sample, block; // // double alpha; // // niter = 10; // // int sample = 10000; // // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, niter, sample, error_mode) // // RUN_EM_INFERENCE(string("vdj"), cloneset_vdj, vdj_single_model, niter, sample, error_mode) // // for(auto val_sample: vec_sample) { // // RUN_EM_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_sample, error_mode) // // } // // ModelParameterVector new_param_vec = vj_single_model.event_probabilities(); // // new_param_vec.fill(1); // // new_param_vec.normaliseEventFamilies(); // // vj_single_model.updateModelParameterVector(new_param_vec); // // // // auto rep_nonc = cloneset_vj.noncoding().sample(2500); // // auto maag_rep = vj_single_model.buildGraphs(rep_nonc, SAVE_METADATA, error_mode, NUCLEOTIDE, true); // // vector<prob_t> prob_vec(maag_rep.size(), 0); // // // // vector<bool> good_clonotypes(maag_rep.size(), true); // // for (size_t i = 0; i < maag_rep.size(); ++i) { // // if (rep_nonc[i].is_good()) { // // prob_vec[i] = maag_rep[i].fullProbability(); // // if (std::isnan(prob_vec[i]) || prob_vec[i] == 0) { // // good_clonotypes[i] = false; // // } // // } else { // // good_clonotypes[i] = false; // // } // // } // for(auto val_sample: vec_sample) { // for(auto val_block: vec_block) { // for (auto val_alpha: vec_alpha) { // for (auto val_beta: vec_beta) { // for (auto val_K: vec_K) { // RUN_SG_INFERENCE(string("vj"), cloneset_vj, vj_single_model, 40, val_block, val_alpha, val_beta, val_K, val_sample, error_mode) // } // } // } // } // } } <|endoftext|>
<commit_before><commit_msg>Update CloseIdleSockets to close out FLIP connections as well as HTTP connections. This is used for benchmarking.<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #include "loadbalancer_haproxy.h" #include <cerrno> #include <fstream> #include <boost/assign/list_of.hpp> #include "base/logging.h" #include "agent.h" #include "init/agent_param.h" #include "loadbalancer_properties.h" using namespace std; using boost::assign::map_list_of; LoadbalancerHaproxy::LoadbalancerHaproxy(Agent *agent) : protocol_default_("tcp"), balance_default_("roundrobin"), agent_(agent) { protocol_map_ = map_list_of ("TCP", "tcp") ("HTTP", "http") ("HTTPS", "tcp"); balance_map_ = map_list_of ("ROUND_ROBIN", "roundrobin") ("LEAST_CONNECTIONS", "leastconn") ("SOURCE_IP", "source"); } const string &LoadbalancerHaproxy::ProtocolMap(const string &proto) const { map<string, string>::const_iterator loc = protocol_map_.find(proto); if (loc == protocol_map_.end()) { return protocol_default_; } return loc->second; } const string &LoadbalancerHaproxy::BalanceMap(const string &proto) const { map<string, string>::const_iterator loc = balance_map_.find(proto); if (loc == balance_map_.end()) { return balance_default_; } return loc->second; } /* * global * daemon * user nobody * group nogroup * log /dev/log local0 * log /dev/log local1 notice * stats socket <path> mode 0666 level user */ void LoadbalancerHaproxy::GenerateGlobal( ostream *out, const LoadbalancerProperties &props) const { *out << "global" << endl; *out << string(4, ' ') << "daemon" << endl; *out << string(4, ' ') << "user nobody" << endl; *out << string(4, ' ') << "group nogroup" << endl; *out << endl; } void LoadbalancerHaproxy::GenerateDefaults( ostream *out, const LoadbalancerProperties &props) const { *out << "defaults" << endl; *out << string(4, ' ') << "log global" << endl; *out << string(4, ' ') << "retries 3" << endl; *out << string(4, ' ') << "option redispatch" << endl; *out << string(4, ' ') << "timeout connect 5000" << endl; *out << string(4, ' ') << "timeout client 50000" << endl; *out << string(4, ' ') << "timeout server 50000" << endl; *out << endl; } void LoadbalancerHaproxy::GenerateListen( ostream *out, const LoadbalancerProperties &props) const { *out << "listen contrail-config-stats :5937" << endl; *out << string(4, ' ') << "mode http" << endl; *out << string(4, ' ') << "stats enable" << endl; *out << string(4, ' ') << "stats uri /" << endl; *out << string(4, ' ') << "stats auth haproxy:contrail123" << endl; *out << endl; } /* * frontend vip_id * bind address:port * mode [http|tcp] * default_backend pool_id */ void LoadbalancerHaproxy::GenerateFrontend( ostream *out, const boost::uuids::uuid &pool_id, const LoadbalancerProperties &props) const { *out << "frontend " << props.vip_uuid() << endl; const autogen::VirtualIpType &vip = props.vip_properties(); *out << string(4, ' ') << "bind " << vip.address << ":" << vip.protocol_port; if (vip.protocol_port == LB_HAPROXY_SSL_PORT) { *out << " ssl crt " << agent_->params()->si_haproxy_ssl_cert_path(); } *out << endl; *out << string(4, ' ') << "mode " << ProtocolMap(vip.protocol) << endl; *out << string(4, ' ') << "default_backend " << pool_id << endl; if (vip.connection_limit >= 0) { *out << string(4, ' ') << "maxconn " << vip.connection_limit << endl; } *out << endl; } /* * backend <pool_id> * mode <protocol> * balance <lb_method> * server <id> <address>:<port> weight <weight> */ void LoadbalancerHaproxy::GenerateBackend( ostream *out, const boost::uuids::uuid &pool_id, const LoadbalancerProperties &props) const { const autogen::LoadbalancerPoolType &pool = props.pool_properties(); *out << "backend " << pool_id << endl; *out << string(4, ' ') << "mode " << ProtocolMap(pool.protocol) << endl; *out << string(4, ' ') << "balance " << BalanceMap(pool.loadbalancer_method) << endl; int timeout = 0, max_retries = 0; if (props.healthmonitors().size()) { const autogen::LoadbalancerHealthmonitorType &hm = props.healthmonitors().begin()->second; timeout = hm.timeout * 1000; //In milliseconds max_retries = hm.max_retries; if (!hm.url_path.empty()) { *out << string(4, ' ') << "option httpchk "; if (!hm.http_method.empty()) { *out << hm.http_method; } *out << " " << hm.url_path << endl; } if (!hm.expected_codes.empty()) { *out << string(4, ' ') << "http-check expect status " << hm.expected_codes << endl; } } for (LoadbalancerProperties::MemberMap::const_iterator iter = props.members().begin(); iter != props.members().end(); ++iter) { const autogen::LoadbalancerMemberType &member = iter->second; *out << string(4, ' ') << "server " << iter->first << " " << member.address << ":" << member.protocol_port << " weight " << member.weight; if (timeout) { *out << " check inter " << timeout << " rise 1 fall " << max_retries; } *out << endl; } } void LoadbalancerHaproxy::GenerateConfig( const string &filename, const boost::uuids::uuid &pool_id, const LoadbalancerProperties &props) const { ofstream fs(filename.c_str()); if (fs.fail()) { LOG(ERROR, "File create " << filename << ": " << strerror(errno)); } GenerateGlobal(&fs, props); GenerateDefaults(&fs, props); GenerateListen(&fs, props); GenerateFrontend(&fs, pool_id, props); GenerateBackend(&fs, pool_id, props); fs.close(); } <commit_msg>Bug:#1380771 Adding the load balancer session persistence parameters fro Service Instance's Virtual ip. The session persistense type and name are written to haproxy configuration file in the backend section<commit_after>/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ #include "loadbalancer_haproxy.h" #include <cerrno> #include <fstream> #include <boost/assign/list_of.hpp> #include "base/logging.h" #include "agent.h" #include "init/agent_param.h" #include "loadbalancer_properties.h" using namespace std; using boost::assign::map_list_of; LoadbalancerHaproxy::LoadbalancerHaproxy(Agent *agent) : protocol_default_("tcp"), balance_default_("roundrobin"), agent_(agent) { protocol_map_ = map_list_of ("TCP", "tcp") ("HTTP", "http") ("HTTPS", "tcp"); balance_map_ = map_list_of ("ROUND_ROBIN", "roundrobin") ("LEAST_CONNECTIONS", "leastconn") ("SOURCE_IP", "source"); } const string &LoadbalancerHaproxy::ProtocolMap(const string &proto) const { map<string, string>::const_iterator loc = protocol_map_.find(proto); if (loc == protocol_map_.end()) { return protocol_default_; } return loc->second; } const string &LoadbalancerHaproxy::BalanceMap(const string &proto) const { map<string, string>::const_iterator loc = balance_map_.find(proto); if (loc == balance_map_.end()) { return balance_default_; } return loc->second; } /* * global * daemon * user nobody * group nogroup * log /dev/log local0 * log /dev/log local1 notice * stats socket <path> mode 0666 level user */ void LoadbalancerHaproxy::GenerateGlobal( ostream *out, const LoadbalancerProperties &props) const { *out << "global" << endl; *out << string(4, ' ') << "daemon" << endl; *out << string(4, ' ') << "user nobody" << endl; *out << string(4, ' ') << "group nogroup" << endl; *out << endl; } void LoadbalancerHaproxy::GenerateDefaults( ostream *out, const LoadbalancerProperties &props) const { *out << "defaults" << endl; *out << string(4, ' ') << "log global" << endl; *out << string(4, ' ') << "retries 3" << endl; *out << string(4, ' ') << "option redispatch" << endl; *out << string(4, ' ') << "timeout connect 5000" << endl; *out << string(4, ' ') << "timeout client 50000" << endl; *out << string(4, ' ') << "timeout server 50000" << endl; *out << endl; } void LoadbalancerHaproxy::GenerateListen( ostream *out, const LoadbalancerProperties &props) const { *out << "listen contrail-config-stats :5937" << endl; *out << string(4, ' ') << "mode http" << endl; *out << string(4, ' ') << "stats enable" << endl; *out << string(4, ' ') << "stats uri /" << endl; *out << string(4, ' ') << "stats auth haproxy:contrail123" << endl; *out << endl; } /* * frontend vip_id * bind address:port * mode [http|tcp] * default_backend pool_id */ void LoadbalancerHaproxy::GenerateFrontend( ostream *out, const boost::uuids::uuid &pool_id, const LoadbalancerProperties &props) const { *out << "frontend " << props.vip_uuid() << endl; const autogen::VirtualIpType &vip = props.vip_properties(); *out << string(4, ' ') << "bind " << vip.address << ":" << vip.protocol_port; if (vip.protocol_port == LB_HAPROXY_SSL_PORT) { *out << " ssl crt " << agent_->params()->si_haproxy_ssl_cert_path(); } *out << endl; *out << string(4, ' ') << "mode " << ProtocolMap(vip.protocol) << endl; *out << string(4, ' ') << "default_backend " << pool_id << endl; if (vip.connection_limit >= 0) { *out << string(4, ' ') << "maxconn " << vip.connection_limit << endl; } *out << endl; } /* * backend <pool_id> * mode <protocol> * balance <lb_method> * server <id> <address>:<port> weight <weight> */ void LoadbalancerHaproxy::GenerateBackend( ostream *out, const boost::uuids::uuid &pool_id, const LoadbalancerProperties &props) const { const autogen::LoadbalancerPoolType &pool = props.pool_properties(); *out << "backend " << pool_id << endl; *out << string(4, ' ') << "mode " << ProtocolMap(pool.protocol) << endl; *out << string(4, ' ') << "balance " << BalanceMap(pool.loadbalancer_method) << endl; int timeout = 0, max_retries = 0; if (props.healthmonitors().size()) { const autogen::LoadbalancerHealthmonitorType &hm = props.healthmonitors().begin()->second; timeout = hm.timeout * 1000; //In milliseconds max_retries = hm.max_retries; if (!hm.url_path.empty()) { *out << string(4, ' ') << "option httpchk "; if (!hm.http_method.empty()) { *out << hm.http_method; } *out << " " << hm.url_path << endl; } if (!hm.expected_codes.empty()) { *out << string(4, ' ') << "http-check expect status " << hm.expected_codes << endl; } } const autogen::VirtualIpType &vip = props.vip_properties(); if (vip.persistence_type == "HTTP_COOKIE") { *out << string(4, ' ') << "cookie SRV insert indirect nocache" << endl; } if (vip.persistence_type == "SOURCE_IP") { *out << string(4, ' ') << "stick-table type ip size 10k" << endl; *out << string(4, ' ') << "stick on src" << endl; } if (vip.persistence_type == "APP_COOKIE" && !vip.persistence_cookie_name.empty()) { *out << string(4, ' ') << "appsession " << vip.persistence_cookie_name << " len 56 timeout 3h" << endl; } for (LoadbalancerProperties::MemberMap::const_iterator iter = props.members().begin(); iter != props.members().end(); ++iter) { const autogen::LoadbalancerMemberType &member = iter->second; *out << string(4, ' ') << "server " << iter->first << " " << member.address << ":" << member.protocol_port << " weight " << member.weight; if (timeout) { *out << " check inter " << timeout << " rise 1 fall " << max_retries; } *out << endl; } } void LoadbalancerHaproxy::GenerateConfig( const string &filename, const boost::uuids::uuid &pool_id, const LoadbalancerProperties &props) const { ofstream fs(filename.c_str()); if (fs.fail()) { LOG(ERROR, "File create " << filename << ": " << strerror(errno)); } GenerateGlobal(&fs, props); GenerateDefaults(&fs, props); GenerateListen(&fs, props); GenerateFrontend(&fs, pool_id, props); GenerateBackend(&fs, pool_id, props); fs.close(); } <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/hid/xinput/xinput_input_driver.h" #include "xenia/hid/hid-private.h" #include <Xinput.h> namespace xe { namespace hid { namespace xinput { XInputInputDriver::XInputInputDriver(InputSystem* input_system) : InputDriver(input_system) { XInputEnable(TRUE); } XInputInputDriver::~XInputInputDriver() { XInputEnable(FALSE); } X_STATUS XInputInputDriver::Setup() { return X_STATUS_SUCCESS; } X_RESULT XInputInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags, X_INPUT_CAPABILITIES* out_caps) { XINPUT_CAPABILITIES native_caps; DWORD result = XInputGetCapabilities(user_index, flags, &native_caps); if (result) { return result; } out_caps->type = native_caps.Type; out_caps->sub_type = native_caps.SubType; out_caps->flags = native_caps.Flags; out_caps->gamepad.buttons = native_caps.Gamepad.wButtons; out_caps->gamepad.left_trigger = native_caps.Gamepad.bLeftTrigger; out_caps->gamepad.right_trigger = native_caps.Gamepad.bRightTrigger; out_caps->gamepad.thumb_lx = native_caps.Gamepad.sThumbLX; out_caps->gamepad.thumb_ly = native_caps.Gamepad.sThumbLY; out_caps->gamepad.thumb_rx = native_caps.Gamepad.sThumbRX; out_caps->gamepad.thumb_ry = native_caps.Gamepad.sThumbRY; out_caps->vibration.left_motor_speed = native_caps.Vibration.wLeftMotorSpeed; out_caps->vibration.right_motor_speed = native_caps.Vibration.wRightMotorSpeed; return result; } X_RESULT XInputInputDriver::GetState(uint32_t user_index, X_INPUT_STATE* out_state) { XINPUT_STATE native_state; DWORD result = XInputGetState(user_index, &native_state); if (result) { return result; } out_state->packet_number = native_state.dwPacketNumber; out_state->gamepad.buttons = native_state.Gamepad.wButtons; out_state->gamepad.left_trigger = native_state.Gamepad.bLeftTrigger; out_state->gamepad.right_trigger = native_state.Gamepad.bRightTrigger; out_state->gamepad.thumb_lx = native_state.Gamepad.sThumbLX; out_state->gamepad.thumb_ly = native_state.Gamepad.sThumbLY; out_state->gamepad.thumb_rx = native_state.Gamepad.sThumbRX; out_state->gamepad.thumb_ry = native_state.Gamepad.sThumbRY; return result; } X_RESULT XInputInputDriver::SetState(uint32_t user_index, X_INPUT_VIBRATION* vibration) { XINPUT_VIBRATION native_vibration; native_vibration.wLeftMotorSpeed = vibration->left_motor_speed; native_vibration.wRightMotorSpeed = vibration->right_motor_speed; DWORD result = XInputSetState(user_index, &native_vibration); return result; } X_RESULT XInputInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags, X_INPUT_KEYSTROKE* out_keystroke) { // We may want to filter flags/user_index before sending to native. // flags is reserved on desktop. XINPUT_KEYSTROKE native_keystroke; DWORD result = XInputGetKeystroke(user_index, flags, &native_keystroke); if (result == ERROR_SUCCESS) { out_keystroke->virtual_key = native_keystroke.VirtualKey; out_keystroke->unicode = native_keystroke.Unicode; out_keystroke->flags = native_keystroke.Flags; out_keystroke->user_index = native_keystroke.UserIndex; out_keystroke->hid_code = native_keystroke.HidCode; } // X_ERROR_EMPTY if no new keys // X_ERROR_DEVICE_NOT_CONNECTED if no device // X_ERROR_SUCCESS if key return result; } } // namespace xinput } // namespace hid } // namespace xe <commit_msg>Fixed XInputGetKeystroke.<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/hid/xinput/xinput_input_driver.h" #include "xenia/hid/hid-private.h" #include <Xinput.h> namespace xe { namespace hid { namespace xinput { XInputInputDriver::XInputInputDriver(InputSystem* input_system) : InputDriver(input_system) { XInputEnable(TRUE); } XInputInputDriver::~XInputInputDriver() { XInputEnable(FALSE); } X_STATUS XInputInputDriver::Setup() { return X_STATUS_SUCCESS; } X_RESULT XInputInputDriver::GetCapabilities(uint32_t user_index, uint32_t flags, X_INPUT_CAPABILITIES* out_caps) { XINPUT_CAPABILITIES native_caps; DWORD result = XInputGetCapabilities(user_index, flags, &native_caps); if (result) { return result; } out_caps->type = native_caps.Type; out_caps->sub_type = native_caps.SubType; out_caps->flags = native_caps.Flags; out_caps->gamepad.buttons = native_caps.Gamepad.wButtons; out_caps->gamepad.left_trigger = native_caps.Gamepad.bLeftTrigger; out_caps->gamepad.right_trigger = native_caps.Gamepad.bRightTrigger; out_caps->gamepad.thumb_lx = native_caps.Gamepad.sThumbLX; out_caps->gamepad.thumb_ly = native_caps.Gamepad.sThumbLY; out_caps->gamepad.thumb_rx = native_caps.Gamepad.sThumbRX; out_caps->gamepad.thumb_ry = native_caps.Gamepad.sThumbRY; out_caps->vibration.left_motor_speed = native_caps.Vibration.wLeftMotorSpeed; out_caps->vibration.right_motor_speed = native_caps.Vibration.wRightMotorSpeed; return result; } X_RESULT XInputInputDriver::GetState(uint32_t user_index, X_INPUT_STATE* out_state) { XINPUT_STATE native_state; DWORD result = XInputGetState(user_index, &native_state); if (result) { return result; } out_state->packet_number = native_state.dwPacketNumber; out_state->gamepad.buttons = native_state.Gamepad.wButtons; out_state->gamepad.left_trigger = native_state.Gamepad.bLeftTrigger; out_state->gamepad.right_trigger = native_state.Gamepad.bRightTrigger; out_state->gamepad.thumb_lx = native_state.Gamepad.sThumbLX; out_state->gamepad.thumb_ly = native_state.Gamepad.sThumbLY; out_state->gamepad.thumb_rx = native_state.Gamepad.sThumbRX; out_state->gamepad.thumb_ry = native_state.Gamepad.sThumbRY; return result; } X_RESULT XInputInputDriver::SetState(uint32_t user_index, X_INPUT_VIBRATION* vibration) { XINPUT_VIBRATION native_vibration; native_vibration.wLeftMotorSpeed = vibration->left_motor_speed; native_vibration.wRightMotorSpeed = vibration->right_motor_speed; DWORD result = XInputSetState(user_index, &native_vibration); return result; } X_RESULT XInputInputDriver::GetKeystroke(uint32_t user_index, uint32_t flags, X_INPUT_KEYSTROKE* out_keystroke) { // We may want to filter flags/user_index before sending to native. // flags is reserved on desktop. XINPUT_KEYSTROKE native_keystroke; DWORD result = XInputGetKeystroke(user_index, flags, &native_keystroke); out_keystroke->virtual_key = native_keystroke.VirtualKey; out_keystroke->unicode = native_keystroke.Unicode; out_keystroke->flags = native_keystroke.Flags; out_keystroke->user_index = native_keystroke.UserIndex; out_keystroke->hid_code = native_keystroke.HidCode; // X_ERROR_EMPTY if no new keys // X_ERROR_DEVICE_NOT_CONNECTED if no device // X_ERROR_SUCCESS if key return result; } } // namespace xinput } // namespace hid } // namespace xe <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <memory> #include <string> #include <vector> #include <cctype> namespace workspace { void example_01() { // -> the "how to do it" section { auto i = 42; auto d = 42.5; auto s = "text"; auto v = { 1, 2, 3 }; } { auto b = new char[10]{0}; auto s1 = std::string{"text"}; auto v1 = std::vector<int>{ 1, 2, 3 }; auto p = std::make_shared<int>(42); } { auto upper = [](char const c) { return std::toupper(c); }; } { auto add = [](auto const a, auto const b) { return a + b; }; } } void example_02() { // -> the "how it works" section { auto v = std::vector<int>{ 1, 2, 3 }; auto size2 = v.size(); } { std::map<int, std::string> m; for (std::map<int, std::string>::const_iterator it = m.cbegin(); it != m.cend(); ++it) { /* ... */ } for (auto it = m.cbegin(); it != m.cend(); ++it) { /* ... */ } } { class foo { int x_; public: foo(int const x = 0) : x_{x} {} int& get() { return x_; } }; foo f(42); auto x = f.get(); x = 100; std::cout << f.get() << '\n'; auto& y = f.get(); y = 100; std::cout << f.get() << '\n'; } { using llong = long long; auto l2 = llong{42}; auto l3 = 42LL; } { class foo { static auto func1(int const i) -> int { return 2 * i; } static auto func2(int const i) { return 2 * i; } }; } { class foo { int x_; public: foo(int const x = 0) : x_{ x } {} int& get() { return x_; } static decltype(auto) proxy_get(foo& f) { return f.get(); } }; auto f = foo{ 42 }; decltype(auto) x = foo::proxy_get(f); } { using namespace std::string_literals; auto ladd = [] (auto const a, auto const b) { return a + b; }; auto i = ladd(40, 2); auto s = ladd("forty"s, "two"s); } } void run() { std::cout << "how to do it =>" << std::endl; example_01(); std::cout << std::endl; std::cout << "how it works =>" << std::endl; example_02(); std::cout << std::endl; } } // workspace int main() { workspace::run(); return 0; } <commit_msg>[m_bancila-modern_cpp_progr_cookbook-2_ed][ch 01] slightly rewrite the 1-st example<commit_after>#include <initializer_list> #include <memory> #include <string> #include <vector> #include <cctype> namespace example_01 { // -> the "how to do it..." section template <typename F, typename T> auto apply(F&& f, T value) { return f(value); } void run() { { auto i = 42; auto d = 42.5; auto s = "text"; auto v = { 1, 2, 3 }; } { auto b = new char[10]{ 0 }; auto s1 = std::string{"text"}; auto v1 = std::vector<int>{ 1, 2, 3 }; auto p = std::make_shared<int>(42); } { auto upper = [](char const c) { return std::toupper(c); }; } { auto add = [](auto const a, auto const b) { return a + b; }; } { const auto func = [](const int value) { return value + 1; }; apply(func, 10); } } } // example_01 -> the "how to do it..." section #include <iostream> #include <map> #include <string> #include <vector> namespace example_02 { // -> the "how it works..." section struct { template <typename T, typename U> auto operator()(T const a, U const b) const { return a + b; } } lstruct; void run() { { const auto v = std::vector<int>{ 1, 2, 3 }; int size1 = v.size(); // possible loss of data auto size2 = v.size(); // auto size3 = int{ v.size() }; // error } { std::map<int, std::string> m{}; for (std::map<int, std::string>::const_iterator it = m.cbegin(); it != m.cend(); ++it) { /* ... */} for (auto it = m.cbegin(); it != m.cend(); ++it) { /* ... */ } } { class foo { int x_; public: foo(int const x = 0) : x_{ x } {} int& get() { return x_; } }; foo f{42}; auto x = f.get(); x = 100; std::cout << f.get() << '\n'; auto& y = f.get(); y = 100; std::cout << f.get() << '\n'; } { using llong = long long; auto l2 = llong{42}; auto l3 = 42LL; } { class foo { static auto func1(int const i) -> int { return 2 * i; } static auto func2(int const i) { return 2 * i; } }; } { class foo { int x_; public: foo(int const x = 0) : x_{x} {} int& get() { return x_; } static auto proxy_get(foo& f) { return f.get(); } }; auto f = foo{42}; // auto& x = foo::proxy_get(f); // error } { class foo { int x_; public: foo(int const x = 0) : x_{x} {} int& get() { return x_; } static decltype(auto) proxy_get(foo& f) { return f.get(); } }; auto f = foo{42}; decltype(auto) x = foo::proxy_get(f); } { using namespace std::string_literals; auto ladd = [](auto const a, auto const b) { return a + b; }; auto i = ladd(40, 2); auto s = ladd("forty"s, "two"s); } { using namespace std::string_literals; auto i = lstruct(40, 2); auto s = lstruct("forty"s, "two"s); } } } // example_02 -> the "how it works..." section #include <iostream> int main() { std::cout << "example_01 =>" << std::endl; example_01::run(); std::cout << std::endl; std::cout << "example_02 =>" << std::endl; example_02::run(); std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrRRectEffect.h" #include "gl/GrGLEffect.h" #include "gl/GrGLSL.h" #include "GrTBackendEffectFactory.h" #include "SkPath.h" // This effect only supports circular corner rrects where all corners have the same radius // which must be <= kRadiusMin. static const SkScalar kRadiusMin = 0.5; ////////////////////////////////////////////////////////////////////////////// class GrGLRRectEffect : public GrGLEffect { public: GrGLRRectEffect(const GrBackendEffectFactory&, const GrDrawEffect&); virtual void emitCode(GrGLShaderBuilder* builder, const GrDrawEffect& drawEffect, EffectKey key, const char* outputColor, const char* inputColor, const TransformedCoordsArray&, const TextureSamplerArray&) SK_OVERRIDE; static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&) { return 0; } virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE; private: GrGLUniformManager::UniformHandle fInnerRectUniform; GrGLUniformManager::UniformHandle fRadiusPlusHalfUniform; SkRRect fPrevRRect; typedef GrGLEffect INHERITED; }; GrGLRRectEffect::GrGLRRectEffect(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect) : INHERITED (factory) { fPrevRRect.setEmpty(); } void GrGLRRectEffect::emitCode(GrGLShaderBuilder* builder, const GrDrawEffect& drawEffect, EffectKey key, const char* outputColor, const char* inputColor, const TransformedCoordsArray&, const TextureSamplerArray& samplers) { const char *rectName; const char *radiusPlusHalfName; // The inner rect is the rrect bounds inset by the radius. Its top, left, right, and bottom // edges correspond to components x, y, z, and w, respectively. fInnerRectUniform = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, kVec4f_GrSLType, "innerRect", &rectName); fRadiusPlusHalfUniform = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, kFloat_GrSLType, "radiusPlusHalf", &radiusPlusHalfName); const char* fragmentPos = builder->fragmentPosition(); // At each quarter-circle corner we compute a vector that is the offset of the fragment position // from the circle center. The vector is pinned in x and y to be in the quarter-plane relevant // to that corner. This means that points near the interior near the rrect top edge will have // a vector that points straight up for both the TL left and TR corners. Computing an // alpha from this vector at either the TR or TL corner will give the correct result. Similarly, // fragments near the other three edges will get the correct AA. Fragments in the interior of // the rrect will have a (0,0) vector at all four corners. So long as the radius > 0.5 they will // correctly produce an alpha value of 1 at all four corners. We take the min of all the alphas. // The code below is a simplified version of the above that performs maxs on the vector // components before computing distances and alpha values so that only one distance computation // need be computed to determine the min alpha. builder->fsCodeAppendf("\t\tvec2 dxy0 = %s.xy - %s.xy;\n", rectName, fragmentPos); builder->fsCodeAppendf("\t\tvec2 dxy1 = %s.xy - %s.zw;\n", fragmentPos, rectName); builder->fsCodeAppend("\t\tvec2 dxy = max(max(dxy0, dxy1), 0.0);\n"); builder->fsCodeAppendf("\t\tfloat alpha = clamp(%s - length(dxy), 0.0, 1.0);\n", radiusPlusHalfName); builder->fsCodeAppendf("\t\t%s = %s;\n", outputColor, (GrGLSLExpr4(inputColor) * GrGLSLExpr1("alpha")).c_str()); } void GrGLRRectEffect::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) { const GrRRectEffect& rre = drawEffect.castEffect<GrRRectEffect>(); const SkRRect& rrect = rre.getRRect(); if (rrect != fPrevRRect) { SkASSERT(rrect.isSimpleCircular()); SkRect rect = rrect.getBounds(); SkScalar radius = rrect.getSimpleRadii().fX; SkASSERT(radius >= kRadiusMin); rect.inset(radius, radius); uman.set4f(fInnerRectUniform, rect.fLeft, rect.fTop, rect.fRight, rect.fBottom); uman.set1f(fRadiusPlusHalfUniform, radius + 0.5f); fPrevRRect = rrect; } } ////////////////////////////////////////////////////////////////////////////// GrEffectRef* GrRRectEffect::Create(const SkRRect& rrect) { if (!rrect.isSimpleCircular()) { return NULL; } if (rrect.getSimpleRadii().fX < kRadiusMin) { return NULL; } return CreateEffectRef(AutoEffectUnref(SkNEW_ARGS(GrRRectEffect, (rrect)))); } GrRRectEffect::~GrRRectEffect() {} void GrRRectEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const { *validFlags = 0; } const GrBackendEffectFactory& GrRRectEffect::getFactory() const { return GrTBackendEffectFactory<GrRRectEffect>::getInstance(); } GrRRectEffect::GrRRectEffect(const SkRRect& rrect) : fRRect(rrect) { SkASSERT(rrect.isSimpleCircular()); SkASSERT(rrect.getSimpleRadii().fX >= kRadiusMin); this->setWillReadFragmentPosition(); } bool GrRRectEffect::onIsEqual(const GrEffect& other) const { const GrRRectEffect& rre = CastEffect<GrRRectEffect>(other); return fRRect == rre.fRRect; } ////////////////////////////////////////////////////////////////////////////// GR_DEFINE_EFFECT_TEST(GrRRectEffect); GrEffectRef* GrRRectEffect::TestCreate(SkRandom* random, GrContext*, const GrDrawTargetCaps& caps, GrTexture*[]) { SkScalar w = random->nextRangeScalar(20.f, 1000.f); SkScalar h = random->nextRangeScalar(20.f, 1000.f); SkScalar r = random->nextRangeF(kRadiusMin, 9.f); SkRRect rrect; rrect.setRectXY(SkRect::MakeWH(w, h), r, r); return GrRRectEffect::Create(rrect); } <commit_msg>Add f suffix to 0.5 to fix mac 10.6 warning<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrRRectEffect.h" #include "gl/GrGLEffect.h" #include "gl/GrGLSL.h" #include "GrTBackendEffectFactory.h" #include "SkPath.h" // This effect only supports circular corner rrects where all corners have the same radius // which must be <= kRadiusMin. static const SkScalar kRadiusMin = 0.5f; ////////////////////////////////////////////////////////////////////////////// class GrGLRRectEffect : public GrGLEffect { public: GrGLRRectEffect(const GrBackendEffectFactory&, const GrDrawEffect&); virtual void emitCode(GrGLShaderBuilder* builder, const GrDrawEffect& drawEffect, EffectKey key, const char* outputColor, const char* inputColor, const TransformedCoordsArray&, const TextureSamplerArray&) SK_OVERRIDE; static inline EffectKey GenKey(const GrDrawEffect&, const GrGLCaps&) { return 0; } virtual void setData(const GrGLUniformManager&, const GrDrawEffect&) SK_OVERRIDE; private: GrGLUniformManager::UniformHandle fInnerRectUniform; GrGLUniformManager::UniformHandle fRadiusPlusHalfUniform; SkRRect fPrevRRect; typedef GrGLEffect INHERITED; }; GrGLRRectEffect::GrGLRRectEffect(const GrBackendEffectFactory& factory, const GrDrawEffect& drawEffect) : INHERITED (factory) { fPrevRRect.setEmpty(); } void GrGLRRectEffect::emitCode(GrGLShaderBuilder* builder, const GrDrawEffect& drawEffect, EffectKey key, const char* outputColor, const char* inputColor, const TransformedCoordsArray&, const TextureSamplerArray& samplers) { const char *rectName; const char *radiusPlusHalfName; // The inner rect is the rrect bounds inset by the radius. Its top, left, right, and bottom // edges correspond to components x, y, z, and w, respectively. fInnerRectUniform = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, kVec4f_GrSLType, "innerRect", &rectName); fRadiusPlusHalfUniform = builder->addUniform(GrGLShaderBuilder::kFragment_Visibility, kFloat_GrSLType, "radiusPlusHalf", &radiusPlusHalfName); const char* fragmentPos = builder->fragmentPosition(); // At each quarter-circle corner we compute a vector that is the offset of the fragment position // from the circle center. The vector is pinned in x and y to be in the quarter-plane relevant // to that corner. This means that points near the interior near the rrect top edge will have // a vector that points straight up for both the TL left and TR corners. Computing an // alpha from this vector at either the TR or TL corner will give the correct result. Similarly, // fragments near the other three edges will get the correct AA. Fragments in the interior of // the rrect will have a (0,0) vector at all four corners. So long as the radius > 0.5 they will // correctly produce an alpha value of 1 at all four corners. We take the min of all the alphas. // The code below is a simplified version of the above that performs maxs on the vector // components before computing distances and alpha values so that only one distance computation // need be computed to determine the min alpha. builder->fsCodeAppendf("\t\tvec2 dxy0 = %s.xy - %s.xy;\n", rectName, fragmentPos); builder->fsCodeAppendf("\t\tvec2 dxy1 = %s.xy - %s.zw;\n", fragmentPos, rectName); builder->fsCodeAppend("\t\tvec2 dxy = max(max(dxy0, dxy1), 0.0);\n"); builder->fsCodeAppendf("\t\tfloat alpha = clamp(%s - length(dxy), 0.0, 1.0);\n", radiusPlusHalfName); builder->fsCodeAppendf("\t\t%s = %s;\n", outputColor, (GrGLSLExpr4(inputColor) * GrGLSLExpr1("alpha")).c_str()); } void GrGLRRectEffect::setData(const GrGLUniformManager& uman, const GrDrawEffect& drawEffect) { const GrRRectEffect& rre = drawEffect.castEffect<GrRRectEffect>(); const SkRRect& rrect = rre.getRRect(); if (rrect != fPrevRRect) { SkASSERT(rrect.isSimpleCircular()); SkRect rect = rrect.getBounds(); SkScalar radius = rrect.getSimpleRadii().fX; SkASSERT(radius >= kRadiusMin); rect.inset(radius, radius); uman.set4f(fInnerRectUniform, rect.fLeft, rect.fTop, rect.fRight, rect.fBottom); uman.set1f(fRadiusPlusHalfUniform, radius + 0.5f); fPrevRRect = rrect; } } ////////////////////////////////////////////////////////////////////////////// GrEffectRef* GrRRectEffect::Create(const SkRRect& rrect) { if (!rrect.isSimpleCircular()) { return NULL; } if (rrect.getSimpleRadii().fX < kRadiusMin) { return NULL; } return CreateEffectRef(AutoEffectUnref(SkNEW_ARGS(GrRRectEffect, (rrect)))); } GrRRectEffect::~GrRRectEffect() {} void GrRRectEffect::getConstantColorComponents(GrColor* color, uint32_t* validFlags) const { *validFlags = 0; } const GrBackendEffectFactory& GrRRectEffect::getFactory() const { return GrTBackendEffectFactory<GrRRectEffect>::getInstance(); } GrRRectEffect::GrRRectEffect(const SkRRect& rrect) : fRRect(rrect) { SkASSERT(rrect.isSimpleCircular()); SkASSERT(rrect.getSimpleRadii().fX >= kRadiusMin); this->setWillReadFragmentPosition(); } bool GrRRectEffect::onIsEqual(const GrEffect& other) const { const GrRRectEffect& rre = CastEffect<GrRRectEffect>(other); return fRRect == rre.fRRect; } ////////////////////////////////////////////////////////////////////////////// GR_DEFINE_EFFECT_TEST(GrRRectEffect); GrEffectRef* GrRRectEffect::TestCreate(SkRandom* random, GrContext*, const GrDrawTargetCaps& caps, GrTexture*[]) { SkScalar w = random->nextRangeScalar(20.f, 1000.f); SkScalar h = random->nextRangeScalar(20.f, 1000.f); SkScalar r = random->nextRangeF(kRadiusMin, 9.f); SkRRect rrect; rrect.setRectXY(SkRect::MakeWH(w, h), r, r); return GrRRectEffect::Create(rrect); } <|endoftext|>
<commit_before>#include <os> #include <syscalls.hpp> #include <string.h> #include <signal.h> //#include <vga.hpp> char *__env[1] = { 0 }; char **environ = __env; static const int syscall_fd=999; static bool debug_syscalls=true; caddr_t heap_end; //Syscall logger void syswrite(const char* name, const char* str) { static const char* hdr = "\tSYSCALL "; static const char* term = "\n"; write(syscall_fd, (char*) hdr, strlen(hdr)); write(syscall_fd, (char*) name, strlen(name)); write(syscall_fd, (char*) ": ", 2); write(syscall_fd, (char*) str, strlen(str)); write(syscall_fd, (char*) term, strlen(term)); }; void _exit(int status) { printf("EXIT: status == %d\n", status); panic("EXIT: Not implemented"); } int close(int UNUSED(file)){ syswrite("CLOSE","Dummy, returning -1"); return -1; }; #undef errno int errno=0; //Is this right? //Not like in http://wiki.osdev.org/Porting_Newlib int execve(const char* UNUSED(name), char* const* UNUSED(argv), char* const* UNUSED(env)) { syswrite((char*) "EXECVE", "NOT SUPPORTED"); errno = ENOMEM; return -1; }; int fork(){ syswrite("FORK","NOT SUPPORTED"); errno=ENOMEM; return -1; }; int fstat(int UNUSED(file), struct stat *st){ syswrite("FSTAT","Returning OK 0"); st->st_mode = S_IFCHR; return 0; }; int getpid(){ syswrite("GETPID", "RETURNING 1"); return 1; }; int isatty(int UNUSED(file)) { syswrite("ISATTY","RETURNING 1"); return 1; } int link(const char* UNUSED(old), const char* UNUSED(_new)) { syswrite("LINK","CAN'T DO THAT!"); kill(1,9); return -1; }; int unlink(const char* UNUSED(name)){ syswrite((char*)"UNLINK","DUMMY, RETURNING -1"); return -1; }; off_t lseek(int UNUSED(file), off_t UNUSED(ptr), int UNUSED(dir)) { syswrite("LSEEK","RETURNING 0"); return 0; } int open(const char* UNUSED(name), int UNUSED(flags), ...){ syswrite("OPEN","NOT SUPPORTED - RETURNING -1"); return -1; }; int read(int UNUSED(file), void* UNUSED(ptr), size_t UNUSED(len)) { syswrite("READ","CAN'T DO THAT - RETURNING 0"); return 0; } int write(int file, const void* ptr, size_t len) { if (file == syscall_fd and not debug_syscalls) return len; // VGA console output //consoleVGA.write(ptr, len); // serial output for(size_t i = 0; i < len; i++) OS::rswrite( ((char*) ptr)[i] ); return len; } void* sbrk(ptrdiff_t incr) { void* prev_heap_end = heap_end; heap_end += incr; return (caddr_t) prev_heap_end; } int stat(const char* UNUSED(file), struct stat *st){ syswrite((char*)"STAT","DUMMY"); st->st_mode = S_IFCHR; return 0; }; clock_t times(struct tms* UNUSED(buf)) { printf("Syscall: times(tms) returning -1\n"); syswrite((char*)"TIMES","DUMMY, RETURNING -1"); //__asm__("rdtsc"); return -1; }; int wait(int* UNUSED(status)){ syswrite((char*)"UNLINK","DUMMY, RETURNING -1"); return -1; }; int gettimeofday(struct timeval* p, void* UNUSED(z)){ float seconds = OS::uptime(); p->tv_sec = int(seconds); p->tv_usec = (seconds - p->tv_sec) * 1000000; return 5; } int kill(pid_t pid, int sig) { if (pid == 1) { syswrite("KILL", "HALTING"); __asm__("cli; hlt;"); _exit(sig); } return -1; } void panic(const char* why) { printf("\n\t **** PANIC: **** %s\n",why); printf("\tHeap end: %p \n",heap_end); kill(1, 1); } <commit_msg>Added __errno_location<commit_after>#include <os> #include <syscalls.hpp> #include <string.h> #include <signal.h> //#include <vga.hpp> char *__env[1] = { 0 }; char **environ = __env; static const int syscall_fd=999; static bool debug_syscalls=true; caddr_t heap_end; //Syscall logger void syswrite(const char* name, const char* str) { static const char* hdr = "\tSYSCALL "; static const char* term = "\n"; write(syscall_fd, (char*) hdr, strlen(hdr)); write(syscall_fd, (char*) name, strlen(name)); write(syscall_fd, (char*) ": ", 2); write(syscall_fd, (char*) str, strlen(str)); write(syscall_fd, (char*) term, strlen(term)); }; void _exit(int status) { printf("EXIT: status == %d\n", status); panic("EXIT: Not implemented"); } int close(int UNUSED(file)){ syswrite("CLOSE","Dummy, returning -1"); return -1; }; #undef errno int errno=0; //Is this right? //Not like in http://wiki.osdev.org/Porting_Newlib int execve(const char* UNUSED(name), char* const* UNUSED(argv), char* const* UNUSED(env)) { syswrite((char*) "EXECVE", "NOT SUPPORTED"); errno = ENOMEM; return -1; }; int fork(){ syswrite("FORK","NOT SUPPORTED"); errno=ENOMEM; return -1; }; int fstat(int UNUSED(file), struct stat *st){ syswrite("FSTAT","Returning OK 0"); st->st_mode = S_IFCHR; return 0; }; int getpid(){ syswrite("GETPID", "RETURNING 1"); return 1; }; int isatty(int UNUSED(file)) { syswrite("ISATTY","RETURNING 1"); return 1; } int link(const char* UNUSED(old), const char* UNUSED(_new)) { syswrite("LINK","CAN'T DO THAT!"); kill(1,9); return -1; }; int unlink(const char* UNUSED(name)){ syswrite((char*)"UNLINK","DUMMY, RETURNING -1"); return -1; }; off_t lseek(int UNUSED(file), off_t UNUSED(ptr), int UNUSED(dir)) { syswrite("LSEEK","RETURNING 0"); return 0; } int open(const char* UNUSED(name), int UNUSED(flags), ...){ syswrite("OPEN","NOT SUPPORTED - RETURNING -1"); return -1; }; int read(int UNUSED(file), void* UNUSED(ptr), size_t UNUSED(len)) { syswrite("READ","CAN'T DO THAT - RETURNING 0"); return 0; } int write(int file, const void* ptr, size_t len) { if (file == syscall_fd and not debug_syscalls) return len; // VGA console output //consoleVGA.write(ptr, len); // serial output for(size_t i = 0; i < len; i++) OS::rswrite( ((char*) ptr)[i] ); return len; } void* sbrk(ptrdiff_t incr) { void* prev_heap_end = heap_end; heap_end += incr; return (caddr_t) prev_heap_end; } int stat(const char* UNUSED(file), struct stat *st){ syswrite((char*)"STAT","DUMMY"); st->st_mode = S_IFCHR; return 0; }; clock_t times(struct tms* UNUSED(buf)) { printf("Syscall: times(tms) returning -1\n"); syswrite((char*)"TIMES","DUMMY, RETURNING -1"); //__asm__("rdtsc"); return -1; }; int wait(int* UNUSED(status)){ syswrite((char*)"UNLINK","DUMMY, RETURNING -1"); return -1; }; int gettimeofday(struct timeval* p, void* UNUSED(z)){ float seconds = OS::uptime(); p->tv_sec = int(seconds); p->tv_usec = (seconds - p->tv_sec) * 1000000; return 5; } int kill(pid_t pid, int sig) { if (pid == 1) { syswrite("KILL", "HALTING"); __asm__("cli; hlt;"); _exit(sig); } return -1; } void panic(const char* why) { printf("\n\t **** PANIC: **** %s\n",why); printf("\tHeap end: %p \n",heap_end); kill(1, 1); } static int __errno__; extern "C" { int * __errno_location(void){ return &__errno__; } } <|endoftext|>
<commit_before>/* Copyright 2014 CyberTech Labs Ltd. * * 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 "src/cameraLineDetectorSensorWorker.h" #include <QtCore/QDebug> #include <QtCore/QFileInfo> #include <QtCore/QWaitCondition> #include <QtCore/QMutex> #include <unistd.h> #include <fcntl.h> #include <errno.h> using namespace trikControl; CameraLineDetectorSensorWorker::CameraLineDetectorSensorWorker( QString const &roverCvBinary , QString const &inputFile , QString const &outputFile) : mReading(0) , mRoverCvBinary(roverCvBinary) , mOutputFileDescriptor(0) , mInputFile(inputFile) , mOutputFile(outputFile) , mReady(false) { qDebug() << "CameraLineDetectorSensorWorker::CameraLineDetectorSensorWorker"; qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError"); } CameraLineDetectorSensorWorker::~CameraLineDetectorSensorWorker() { deinitialize(); } void CameraLineDetectorSensorWorker::moveChildrenToCorrectThread() { mRoverCvProcess.moveToThread(this->thread()); connect(&mRoverCvProcess, SIGNAL(error(QProcess::ProcessError)) , this, SLOT(onRoverCvError(QProcess::ProcessError)), Qt::QueuedConnection); connect(&mRoverCvProcess, SIGNAL(readyReadStandardError()) , this, SLOT(onRoverCvReadyReadStandardError()), Qt::QueuedConnection); connect(&mRoverCvProcess, SIGNAL(readyReadStandardOutput()) , this, SLOT(onRoverCvReadyReadStandardOutput()), Qt::QueuedConnection); } void CameraLineDetectorSensorWorker::init() { qDebug() << "CameraLineDetectorSensorWorker::init()"; if (!mReady) { initDetector(); } } void CameraLineDetectorSensorWorker::detect() { qDebug() << "CameraLineDetectorSensorWorker::detect()"; if (!mReady) { init(); } mCommandQueue << "detect"; tryToExecute(); } int CameraLineDetectorSensorWorker::read() { return mReading; } void CameraLineDetectorSensorWorker::initDetector() { qDebug() << "initDetector()"; if (!mInputFile.exists() || !mOutputFile.exists()) { startRoverCv(); } else { openFifos(); } } void CameraLineDetectorSensorWorker::onRoverCvError(QProcess::ProcessError error) { qDebug() << "rover-cv error: " << error; mReady = false; deinitialize(); } void CameraLineDetectorSensorWorker::onRoverCvReadyReadStandardOutput() { qDebug() << "onRoverCvReadyReadStandardOutput"; QString const data = mRoverCvProcess.readAllStandardOutput(); QStringList const lines = data.split("\n"); foreach (QString const line, lines) { qDebug() << "From rover-cv:" << line; if (line == "Entering video thread loop") { openFifos(); } } } void CameraLineDetectorSensorWorker::onRoverCvReadyReadStandardError() { QString const data = mRoverCvProcess.readAllStandardError(); QStringList const lines = data.split("\n"); foreach (QString const line, lines) { qDebug() << "From rover-cv standard error:" << line; } } void CameraLineDetectorSensorWorker::readFile() { char data[4000] = {0}; int size = 0; mSocketNotifier->setEnabled(false); if ((size = ::read(mOutputFileDescriptor, data, 4000)) < 0) { qDebug() << mOutputFile.fileName() << ": fifo read failed: " << errno; return; } QString const linesRead(data); QStringList const lines = linesRead.split('\n', QString::SkipEmptyParts); foreach (QString const line, lines) { QStringList const parsedLine = line.split(" ", QString::SkipEmptyParts); qDebug() << "parsed: " << parsedLine; if (parsedLine[0] == "loc:") { int const x = parsedLine[1].toInt(); int const angle = parsedLine[2].toInt(); int const mass = parsedLine[3].toInt(); mReading = x; // These values are not needed in current implementation, but are left here for reference. Q_UNUSED(angle) Q_UNUSED(mass) } if (parsedLine[0] == "hsv:") { int const hue = parsedLine[1].toInt(); int const hueTolerance = parsedLine[2].toInt(); int const saturation = parsedLine[3].toInt(); int const saturationTolerance = parsedLine[4].toInt(); int const value = parsedLine[5].toInt(); int const valueTolerance = parsedLine[6].toInt(); // These values are not needed in current implementation, but are left here for reference too. Q_UNUSED(hue) Q_UNUSED(hueTolerance) Q_UNUSED(saturation) Q_UNUSED(saturationTolerance) Q_UNUSED(value) Q_UNUSED(valueTolerance) mInputStream << QString(line).remove(":") << "\n"; mInputStream.flush(); } } mSocketNotifier->setEnabled(true); } void CameraLineDetectorSensorWorker::startRoverCv() { QFileInfo roverCvBinaryFileInfo(mRoverCvBinary); qDebug() << "Starting rover-cv"; mRoverCvProcess.setWorkingDirectory(roverCvBinaryFileInfo.absolutePath()); mRoverCvProcess.start(roverCvBinaryFileInfo.filePath()); mRoverCvProcess.waitForStarted(); if (mRoverCvProcess.state() != QProcess::Running) { qDebug() << "Cannot launch detector application " << roverCvBinaryFileInfo.filePath() << " in " << roverCvBinaryFileInfo.absolutePath(); return; } qDebug() << "rover-cv started, waiting for it to initialize..."; /// @todo Remove this hack! QProcess does not deliver messages from rover-cv during startup. QMutex mutex; QWaitCondition wait; wait.wait(&mutex, 1000); openFifos(); } void CameraLineDetectorSensorWorker::openFifos() { qDebug() << "opening" << mOutputFile.fileName(); if (!mOutputFileDescriptor) { mOutputFileDescriptor = open(mOutputFile.fileName().toStdString().c_str(), O_SYNC | O_NONBLOCK, O_RDONLY); } if (mOutputFileDescriptor == -1) { qDebug() << "Cannot open sensor output file " << mOutputFile.fileName(); return; } qDebug() << mOutputFileDescriptor; mSocketNotifier.reset(new QSocketNotifier(mOutputFileDescriptor, QSocketNotifier::Read)); connect(mSocketNotifier.data(), SIGNAL(activated(int)), this, SLOT(readFile())); mSocketNotifier->setEnabled(true); qDebug() << "opening" << mInputFile.fileName(); if (!mInputFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Sensor input file" << mInputFile.fileName() << " failed to open"; return; } mInputStream.setDevice(&mInputFile); mReady = true; qDebug() << "initialization completed"; tryToExecute(); } void CameraLineDetectorSensorWorker::tryToExecute() { if (mReady) { foreach (QString const &command, mCommandQueue) { mInputStream << command + "\n"; mInputStream.flush(); } mCommandQueue.clear(); } } void CameraLineDetectorSensorWorker::deinitialize() { disconnect(mSocketNotifier.data(), SIGNAL(activated(int)), this, SLOT(readFifo())); mSocketNotifier->setEnabled(false); if (::close(mOutputFileDescriptor) != 0) { qDebug() << mOutputFile.fileName() << ": fifo close failed: " << errno; } } <commit_msg>fixed restart of the rover-cv<commit_after>/* Copyright 2014 CyberTech Labs Ltd. * * 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 "src/cameraLineDetectorSensorWorker.h" #include <QtCore/QDebug> #include <QtCore/QFileInfo> #include <QtCore/QWaitCondition> #include <QtCore/QMutex> #include <unistd.h> #include <fcntl.h> #include <errno.h> using namespace trikControl; CameraLineDetectorSensorWorker::CameraLineDetectorSensorWorker( QString const &roverCvBinary , QString const &inputFile , QString const &outputFile) : mReading(0) , mRoverCvBinary(roverCvBinary) , mOutputFileDescriptor(0) , mInputFile(inputFile) , mOutputFile(outputFile) , mReady(false) { qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError"); connect(&mRoverCvProcess, SIGNAL(error(QProcess::ProcessError)) , this, SLOT(onRoverCvError(QProcess::ProcessError)), Qt::QueuedConnection); connect(&mRoverCvProcess, SIGNAL(readyReadStandardError()) , this, SLOT(onRoverCvReadyReadStandardError()), Qt::QueuedConnection); connect(&mRoverCvProcess, SIGNAL(readyReadStandardOutput()) , this, SLOT(onRoverCvReadyReadStandardOutput()), Qt::QueuedConnection); } CameraLineDetectorSensorWorker::~CameraLineDetectorSensorWorker() { deinitialize(); } void CameraLineDetectorSensorWorker::moveChildrenToCorrectThread() { mRoverCvProcess.moveToThread(this->thread()); } void CameraLineDetectorSensorWorker::init() { if (!mReady || !mInputFile.exists() || !mOutputFile.exists()) { initDetector(); } } void CameraLineDetectorSensorWorker::detect() { if (!mReady || !mInputFile.exists() || !mOutputFile.exists()) { init(); } mCommandQueue << "detect"; tryToExecute(); } int CameraLineDetectorSensorWorker::read() { return mReading; } void CameraLineDetectorSensorWorker::initDetector() { if (!mInputFile.exists() || !mOutputFile.exists()) { startRoverCv(); } else { openFifos(); } } void CameraLineDetectorSensorWorker::onRoverCvError(QProcess::ProcessError error) { qDebug() << "rover-cv error: " << error; mReady = false; deinitialize(); } void CameraLineDetectorSensorWorker::onRoverCvReadyReadStandardOutput() { QString const data = mRoverCvProcess.readAllStandardOutput(); QStringList const lines = data.split("\n"); foreach (QString const line, lines) { qDebug() << "From rover-cv:" << line; if (line == "Entering video thread loop") { openFifos(); } if (line == "Terminating") { mReady = false; deinitialize(); } } } void CameraLineDetectorSensorWorker::onRoverCvReadyReadStandardError() { QString const data = mRoverCvProcess.readAllStandardError(); QStringList const lines = data.split("\n"); foreach (QString const line, lines) { qDebug() << "From rover-cv standard error:" << line; } } void CameraLineDetectorSensorWorker::readFile() { char data[4000] = {0}; int size = 0; mSocketNotifier->setEnabled(false); if ((size = ::read(mOutputFileDescriptor, data, 4000)) < 0) { qDebug() << mOutputFile.fileName() << ": fifo read failed: " << errno; return; } QString const linesRead(data); QStringList const lines = linesRead.split('\n', QString::SkipEmptyParts); foreach (QString const line, lines) { QStringList const parsedLine = line.split(" ", QString::SkipEmptyParts); qDebug() << "parsed: " << parsedLine; if (parsedLine[0] == "loc:") { int const x = parsedLine[1].toInt(); int const angle = parsedLine[2].toInt(); int const mass = parsedLine[3].toInt(); mReading = x; // These values are not needed in current implementation, but are left here for reference. Q_UNUSED(angle) Q_UNUSED(mass) } if (parsedLine[0] == "hsv:") { int const hue = parsedLine[1].toInt(); int const hueTolerance = parsedLine[2].toInt(); int const saturation = parsedLine[3].toInt(); int const saturationTolerance = parsedLine[4].toInt(); int const value = parsedLine[5].toInt(); int const valueTolerance = parsedLine[6].toInt(); // These values are not needed in current implementation, but are left here for reference too. Q_UNUSED(hue) Q_UNUSED(hueTolerance) Q_UNUSED(saturation) Q_UNUSED(saturationTolerance) Q_UNUSED(value) Q_UNUSED(valueTolerance) mInputStream << QString(line).remove(":") << "\n"; mInputStream.flush(); } } mSocketNotifier->setEnabled(true); } void CameraLineDetectorSensorWorker::startRoverCv() { QFileInfo roverCvBinaryFileInfo(mRoverCvBinary); qDebug() << "Starting rover-cv"; if (mRoverCvProcess.state() == QProcess::Running) { mRoverCvProcess.close(); } mRoverCvProcess.setWorkingDirectory(roverCvBinaryFileInfo.absolutePath()); mRoverCvProcess.start(roverCvBinaryFileInfo.filePath(), QIODevice::ReadOnly | QIODevice::Unbuffered); mRoverCvProcess.waitForStarted(); if (mRoverCvProcess.state() != QProcess::Running) { qDebug() << "Cannot launch detector application " << roverCvBinaryFileInfo.filePath() << " in " << roverCvBinaryFileInfo.absolutePath(); return; } qDebug() << "rover-cv started, waiting for it to initialize..."; /// @todo Remove this hack! QProcess does not deliver messages from rover-cv during startup. QMutex mutex; QWaitCondition wait; wait.wait(&mutex, 1000); openFifos(); } void CameraLineDetectorSensorWorker::openFifos() { qDebug() << "opening" << mOutputFile.fileName(); if (!mOutputFileDescriptor) { mOutputFileDescriptor = open(mOutputFile.fileName().toStdString().c_str(), O_SYNC | O_NONBLOCK, O_RDONLY); } if (mOutputFileDescriptor == -1) { qDebug() << "Cannot open sensor output file " << mOutputFile.fileName(); return; } qDebug() << mOutputFileDescriptor; mSocketNotifier.reset(new QSocketNotifier(mOutputFileDescriptor, QSocketNotifier::Read)); connect(mSocketNotifier.data(), SIGNAL(activated(int)), this, SLOT(readFile())); mSocketNotifier->setEnabled(false); qDebug() << "opening" << mInputFile.fileName(); if (!mInputFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "Sensor input file" << mInputFile.fileName() << " failed to open"; return; } mInputStream.setDevice(&mInputFile); mReady = true; qDebug() << "initialization completed"; tryToExecute(); } void CameraLineDetectorSensorWorker::tryToExecute() { if (mReady) { foreach (QString const &command, mCommandQueue) { mInputStream << command + "\n"; mInputStream.flush(); } mCommandQueue.clear(); } } void CameraLineDetectorSensorWorker::deinitialize() { disconnect(mSocketNotifier.data(), SIGNAL(activated(int)), this, SLOT(readFile())); mSocketNotifier->setEnabled(false); if (::close(mOutputFileDescriptor) != 0) { qDebug() << mOutputFile.fileName() << ": fifo close failed: " << errno; } } <|endoftext|>
<commit_before>// Copyright 2020 The Pigweed Authors // // 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 // // https://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 "pw_kvs/internal/sectors.h" #include "gtest/gtest.h" #include "pw_kvs/fake_flash_memory.h" namespace pw::kvs::internal { namespace { class SectorsTest : public ::testing::Test { protected: SectorsTest() : partition_(&flash_), sectors_(sector_descriptors_, partition_, nullptr) {} FakeFlashMemoryBuffer<128, 16> flash_; FlashPartition partition_; Vector<SectorDescriptor, 32> sector_descriptors_; Sectors sectors_; }; TEST_F(SectorsTest, Reset) { EXPECT_EQ(0u, sectors_.size()); sectors_.Reset(); EXPECT_EQ(partition_.sector_count(), sectors_.size()); EXPECT_EQ(32u, sectors_.max_size()); EXPECT_EQ(sectors_.begin(), sectors_.last_new()); } TEST_F(SectorsTest, LastNew) { sectors_.set_last_new_sector(130); EXPECT_EQ(128u, sectors_.BaseAddress(*sectors_.last_new())); } TEST_F(SectorsTest, AddressInSector) { SectorDescriptor& sector = sectors_.FromAddress(128); EXPECT_FALSE(sectors_.AddressInSector(sector, 127)); for (size_t address = 128; address < 256; ++address) { EXPECT_TRUE(sectors_.AddressInSector(sector, address)); } EXPECT_FALSE(sectors_.AddressInSector(sector, 256)); EXPECT_FALSE(sectors_.AddressInSector(sector, 1025)); } TEST_F(SectorsTest, BaseAddressAndFromAddress) { for (size_t address = 0; address < 128; ++address) { EXPECT_EQ(0u, sectors_.BaseAddress(sectors_.FromAddress(address))); } for (size_t address = 128; address < 256; ++address) { EXPECT_EQ(128u, sectors_.BaseAddress(sectors_.FromAddress(address))); } for (size_t address = 256; address < 384; ++address) { EXPECT_EQ(256u, sectors_.BaseAddress(sectors_.FromAddress(address))); } } TEST_F(SectorsTest, NextWritableAddress_EmptySector) { EXPECT_EQ(0u, sectors_.NextWritableAddress(*sectors_.begin())); } TEST_F(SectorsTest, NextWritableAddress_PartiallyWrittenSector) { sectors_.begin()->RemoveWritableBytes(123); EXPECT_EQ(123u, sectors_.NextWritableAddress(*sectors_.begin())); } // TODO: Add tests for FindSpace, FindSpaceDuringGarbageCollection, and // FindSectorToGarbageCollect. } // namespace } // namespace pw::kvs::internal <commit_msg>pw_kvs: Fix sectors test<commit_after>// Copyright 2020 The Pigweed Authors // // 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 // // https://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 "pw_kvs/internal/sectors.h" #include "gtest/gtest.h" #include "pw_kvs/fake_flash_memory.h" namespace pw::kvs::internal { namespace { class SectorsTest : public ::testing::Test { protected: SectorsTest() : partition_(&flash_), sectors_(sector_descriptors_, partition_, nullptr) { EXPECT_EQ(0u, sectors_.size()); sectors_.Reset(); } FakeFlashMemoryBuffer<128, 16> flash_; FlashPartition partition_; Vector<SectorDescriptor, 32> sector_descriptors_; Sectors sectors_; }; TEST_F(SectorsTest, Reset) { // Reset is done by the fixture. EXPECT_EQ(partition_.sector_count(), sectors_.size()); EXPECT_EQ(32u, sectors_.max_size()); EXPECT_EQ(sectors_.begin(), sectors_.last_new()); } TEST_F(SectorsTest, LastNew) { sectors_.set_last_new_sector(130); EXPECT_EQ(128u, sectors_.BaseAddress(*sectors_.last_new())); } TEST_F(SectorsTest, AddressInSector) { SectorDescriptor& sector = sectors_.FromAddress(128); EXPECT_FALSE(sectors_.AddressInSector(sector, 127)); for (size_t address = 128; address < 256; ++address) { EXPECT_TRUE(sectors_.AddressInSector(sector, address)); } EXPECT_FALSE(sectors_.AddressInSector(sector, 256)); EXPECT_FALSE(sectors_.AddressInSector(sector, 1025)); } TEST_F(SectorsTest, BaseAddressAndFromAddress) { for (size_t address = 0; address < 128; ++address) { EXPECT_EQ(0u, sectors_.BaseAddress(sectors_.FromAddress(address))); } for (size_t address = 128; address < 256; ++address) { EXPECT_EQ(128u, sectors_.BaseAddress(sectors_.FromAddress(address))); } for (size_t address = 256; address < 384; ++address) { EXPECT_EQ(256u, sectors_.BaseAddress(sectors_.FromAddress(address))); } } TEST_F(SectorsTest, NextWritableAddress_EmptySector) { EXPECT_EQ(0u, sectors_.NextWritableAddress(*sectors_.begin())); } TEST_F(SectorsTest, NextWritableAddress_PartiallyWrittenSector) { sectors_.begin()->RemoveWritableBytes(123); EXPECT_EQ(123u, sectors_.NextWritableAddress(*sectors_.begin())); } // TODO: Add tests for FindSpace, FindSpaceDuringGarbageCollection, and // FindSectorToGarbageCollect. } // namespace } // namespace pw::kvs::internal <|endoftext|>
<commit_before>//vbSort.cpp //Copyright (c) 2015 mmYYmmdd #include "stdafx.h" #include <algorithm> #include "VBA_NestFunc.hpp" //比較関数 class compareByVBAfunc { VARIANT* begin; std::shared_ptr<functionExpr> comp; public: compareByVBAfunc(VARIANT* pA, VARIANT* f) : begin(pA), comp(std::make_shared<functionExpr>(f)) { } bool valid() const { return static_cast<bool>(comp); } bool operator ()(__int32 i, __int32 j) const { return comp->eval(begin + i, begin + j)->lVal ? true: false; } }; //1次元昇順 class compFunctor { VARIANT* begin; public: compFunctor(VARIANT* pA) : begin(pA) { } bool operator ()(__int32 i, __int32 j) const { return VARCMP_LT == VarCmp(begin + i, begin + j, LANG_JAPANESE, 0); } }; //2次元昇順 class compDictionaryFunctor { VARIANT* begin; public: compDictionaryFunctor(VARIANT* pA) : begin(pA) { } bool operator ()(__int32 i, __int32 j) const { safearrayRef arr1(begin + i); safearrayRef arr2(begin + j); if ( arr1.getDim() == 1 || arr2.getDim() == 1 ) return false; for ( ULONG k = 0; k < arr1.getSize(1) && k < arr2.getSize(1); ++k ) { if ( VARCMP_LT == VarCmp(&arr1(k), &arr2(k), LANG_JAPANESE, 0) ) return true; if ( VARCMP_LT == VarCmp(&arr2(k), &arr1(k), LANG_JAPANESE, 0) ) return false; } return false; } }; VARIANT __stdcall stdsort(VARIANT* array, __int32 defaultFlag, VARIANT* pComp) { VARIANT ret; ::VariantInit(&ret); safearrayRef arrIn(array); if ( 1 != arrIn.getDim() ) return ret; auto index = std::make_unique<__int32[]>(arrIn.getSize(1)); auto VArray = std::make_unique<VARIANT[]>(arrIn.getSize(1)); for (std::size_t i = 0; i < arrIn.getSize(1); ++i) { index[i] = static_cast<__int32>(i); ::VariantInit(&VArray[i]); ::VariantCopyInd(&VArray[i], &arrIn(i)); } if ( defaultFlag == 1 ) //1次元昇順 { compFunctor functor(VArray.get()); std::sort(index.get(), index.get() + arrIn.getSize(1), functor); } else if ( defaultFlag == 2 ) //2次元昇順 { compDictionaryFunctor functor(VArray.get()); std::sort(index.get(), index.get() + arrIn.getSize(1), functor); } else if ( pComp ) { compareByVBAfunc functor(VArray.get(), pComp); if ( functor.valid() ) std::sort(index.get(), index.get() + arrIn.getSize(1), functor); } //------------------------------------------------------- SAFEARRAYBOUND boundRet = { static_cast<ULONG>(arrIn.getSize(1)), 0}; //要素数、LBound ret.vt = VT_ARRAY | VT_VARIANT; ret.parray = ::SafeArrayCreate(VT_VARIANT, 1, &boundRet); safearrayRef arrOut(&ret); VARIANT elem; ::VariantInit(&elem); elem.vt = VT_I4; for ( std::size_t i = 0; i < arrIn.getSize(1); ++i ) { elem.lVal = static_cast<LONG>(index[i] + arrIn.getOriginalLBound(1)); ::VariantCopy(&arrOut(i), &elem); } return ret; } <commit_msg>リファクタリング : コピーコンストラクタ = default; など<commit_after>//vbSort.cpp //Copyright (c) 2015 mmYYmmdd #include "stdafx.h" #include <algorithm> #include "VBA_NestFunc.hpp" //比較関数 class compareByVBAfunc { VARIANT* begin; std::shared_ptr<functionExpr> comp; public: compareByVBAfunc(VARIANT* pA, VARIANT* f) : begin(pA), comp(std::make_shared<functionExpr>(f)) { } compareByVBAfunc(compareByVBAfunc const&) = default; compareByVBAfunc(compareByVBAfunc&&) = delete; ~compareByVBAfunc() = default; bool valid() const { return static_cast<bool>(comp); } bool operator ()(__int32 i, __int32 j) const { return comp->eval(begin + i, begin + j)->lVal ? true: false; } }; //1次元昇順 class compFunctor { VARIANT* begin; public: explicit compFunctor(VARIANT* pA) : begin(pA) { } compFunctor(compFunctor const&) = default; compFunctor(compFunctor&&) = delete; ~compFunctor() = default; bool operator ()(__int32 i, __int32 j) const { return VARCMP_LT == VarCmp(begin + i, begin + j, LANG_JAPANESE, 0); } }; //2次元昇順 class compDictionaryFunctor { VARIANT* begin; public: explicit compDictionaryFunctor(VARIANT* pA) : begin(pA) { } compDictionaryFunctor(compDictionaryFunctor const&) = default; compDictionaryFunctor(compDictionaryFunctor&&) = delete; ~compDictionaryFunctor() = default; bool operator ()(__int32 i, __int32 j) const { safearrayRef arr1(begin + i); safearrayRef arr2(begin + j); if ( arr1.getDim() == 1 || arr2.getDim() == 1 ) return false; for ( ULONG k = 0; k < arr1.getSize(1) && k < arr2.getSize(1); ++k ) { if ( VARCMP_LT == VarCmp(&arr1(k), &arr2(k), LANG_JAPANESE, 0) ) return true; if ( VARCMP_LT == VarCmp(&arr2(k), &arr1(k), LANG_JAPANESE, 0) ) return false; } return false; } }; VARIANT __stdcall stdsort(VARIANT* array, __int32 defaultFlag, VARIANT* pComp) { VARIANT ret; ::VariantInit(&ret); safearrayRef arrIn(array); if ( 1 != arrIn.getDim() ) return ret; auto index = std::make_unique<__int32[]>(arrIn.getSize(1)); auto VArray = std::make_unique<VARIANT[]>(arrIn.getSize(1)); for (std::size_t i = 0; i < arrIn.getSize(1); ++i) { index[i] = static_cast<__int32>(i); ::VariantInit(&VArray[i]); ::VariantCopyInd(&VArray[i], &arrIn(i)); } if ( defaultFlag == 1 ) //1次元昇順 { compFunctor functor(VArray.get()); std::sort(index.get(), index.get() + arrIn.getSize(1), functor); } else if ( defaultFlag == 2 ) //2次元昇順 { compDictionaryFunctor functor(VArray.get()); std::sort(index.get(), index.get() + arrIn.getSize(1), functor); } else if ( pComp ) { compareByVBAfunc functor(VArray.get(), pComp); if ( functor.valid() ) std::sort(index.get(), index.get() + arrIn.getSize(1), functor); } //------------------------------------------------------- SAFEARRAYBOUND boundRet = { static_cast<ULONG>(arrIn.getSize(1)), 0}; //要素数、LBound ret.vt = VT_ARRAY | VT_VARIANT; ret.parray = ::SafeArrayCreate(VT_VARIANT, 1, &boundRet); safearrayRef arrOut(&ret); VARIANT elem; ::VariantInit(&elem); elem.vt = VT_I4; for ( std::size_t i = 0; i < arrIn.getSize(1); ++i ) { elem.lVal = static_cast<LONG>(index[i] + arrIn.getOriginalLBound(1)); ::VariantCopy(&arrOut(i), &elem); } return ret; } <|endoftext|>
<commit_before>/* symtable.cc * Hash table representing the symbol table. * the symbol table. * UIdaho CS445 120++ Compiler * author: Chris Waltrip <[email protected]> */ #include <iostream> #include <sstream> #include <string> #include "symtable.hh" #include "exception.hh" /* AbstractSymbol::AbstractSymbol(std::string n, TypenameEntry t) : name(n), type(t) { } */ AbstractSymbol::AbstractSymbol(std::string n, std::string t) : name(n), type(t) { } std::string AbstractSymbol::to_string(std::size_t depth) { std::string spaces = std::string(depth, '>'); return(spaces + this->type + " " + this->name); } /* * The only time that SymbolTable's parent will be NULL is the Global Symbol * Table. Given this and the n-ary tree (represented using std::deque), * resolving scope should be relatively simple. */ SymbolTable::SymbolTable(SymbolTable *p) { this->parent = p; } /* * Just a wrapper function for nesting scopes. */ void SymbolTable::add_sub_table(SymbolTable *k) { this->kids.push_back(k); } /* * This hashing method is identical to the Typename Table hash method. */ std::size_t SymbolTable::hash(std::string name) { std::size_t hash = 0; const char* s = name.c_str(); while(*s) { hash = hash * 101 + *s++; } return hash % this->HASHTABLE_SIZE; } bool SymbolTable::insert(std::string n, AbstractSymbol *s) { if(!this->symbol_exists(n)) { std::size_t h = this->hash(n); this->bucket[h].push_back(s); return true; } throw EDuplicateSymbol(); return false; /* Remove after refactor */ } bool SymbolTable::empty() { for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { if(!this->bucket[i].empty()) return false; } return true; } AbstractSymbol* SymbolTable::get_symbol(std::string name) { std::size_t h = this->hash(name); std::deque<AbstractSymbol*> b = this->bucket[h]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) { std::size_t i = it - b.begin(); if(*(b[i]) == name) { return b[i]; } } throw ENoSymbolEntry(); } /* * Tries to get the symbol from the current scope. If get_symbol throws an * ENoSymbolEntry, then the current scope doesn't have the symbol that is * being search for. If the parent symbol table is NULL then we have reached * the global symbol table and the symbol doesn't exist so throw * ENoSymbolEntry again and let the calling function handle the exception. If * the symbol is found, it's returned. */ AbstractSymbol* SymbolTable::get_scoped_symbol(std::string name) { AbstractSymbol *symb; try { symb = this->get_symbol(name); return symb; } catch(ENoSymbolEntry e) { if(this->parent == NULL) { throw ENoSymbolEntry(); } else { /* Will never be NULL because exception is thrown */ return this->parent->get_scoped_symbol(name); } } } /* * Will return true if a symbol is found. If get_symbol throws * an ENoSymbolEntry exception, then the symbol isn't in the symbol * table. This only checks for the existance in the local symbol table. */ bool SymbolTable::symbol_exists(std::string name) { try { this->get_symbol(name); } catch(ENoSymbolEntry e) { return false; } return true; } void SymbolTable::print_table(std::size_t depth) { std::clog << this->to_string(depth) << std::endl; } std::string SymbolTable::to_string(std::size_t depth) { std::stringstream ss; for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { std::deque<AbstractSymbol*> b = this->bucket[i]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) {\ std::size_t index = it - b.begin(); ss << (*(b[i]))->to_string(depth) << std::endl; //ss << (*it)->to_string(depth) << std::endl; } } return ss.str(); } /* Basic Symbol constructor */ BasicSymbol::BasicSymbol(std::string n, std::string t, bool p) : AbstractSymbol(n,t), pointer(p) { } /* Function symbol constructor */ FunctionSymbol::FunctionSymbol(std::string n, std::string t, bool p, bool d) : AbstractSymbol(n,t), pointer(p), def_needed(d) { } std::string FunctionSymbol::to_string(std::size_t depth) { std::stringstream ss; ss << AbstractSymbol::to_string(depth) << std::endl; ss << this->params.to_string(depth+1) << std::endl; ss << this->locals.to_string(depth+1) << std::endl; return ss.str(); }<commit_msg>Fixing segfault when referencing iterator<commit_after>/* symtable.cc * Hash table representing the symbol table. * the symbol table. * UIdaho CS445 120++ Compiler * author: Chris Waltrip <[email protected]> */ #include <iostream> #include <sstream> #include <string> #include "symtable.hh" #include "exception.hh" /* AbstractSymbol::AbstractSymbol(std::string n, TypenameEntry t) : name(n), type(t) { } */ AbstractSymbol::AbstractSymbol(std::string n, std::string t) : name(n), type(t) { } std::string AbstractSymbol::to_string(std::size_t depth) { std::string spaces = std::string(depth, '>'); return(spaces + this->type + " " + this->name); } /* * The only time that SymbolTable's parent will be NULL is the Global Symbol * Table. Given this and the n-ary tree (represented using std::deque), * resolving scope should be relatively simple. */ SymbolTable::SymbolTable(SymbolTable *p) { this->parent = p; } /* * Just a wrapper function for nesting scopes. */ void SymbolTable::add_sub_table(SymbolTable *k) { this->kids.push_back(k); } /* * This hashing method is identical to the Typename Table hash method. */ std::size_t SymbolTable::hash(std::string name) { std::size_t hash = 0; const char* s = name.c_str(); while(*s) { hash = hash * 101 + *s++; } return hash % this->HASHTABLE_SIZE; } bool SymbolTable::insert(std::string n, AbstractSymbol *s) { if(!this->symbol_exists(n)) { std::size_t h = this->hash(n); this->bucket[h].push_back(s); return true; } throw EDuplicateSymbol(); return false; /* Remove after refactor */ } bool SymbolTable::empty() { for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { if(!this->bucket[i].empty()) return false; } return true; } AbstractSymbol* SymbolTable::get_symbol(std::string name) { std::size_t h = this->hash(name); std::deque<AbstractSymbol*> b = this->bucket[h]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) { std::size_t i = it - b.begin(); if(*(b[i]) == name) { return b[i]; } } throw ENoSymbolEntry(); } /* * Tries to get the symbol from the current scope. If get_symbol throws an * ENoSymbolEntry, then the current scope doesn't have the symbol that is * being search for. If the parent symbol table is NULL then we have reached * the global symbol table and the symbol doesn't exist so throw * ENoSymbolEntry again and let the calling function handle the exception. If * the symbol is found, it's returned. */ AbstractSymbol* SymbolTable::get_scoped_symbol(std::string name) { AbstractSymbol *symb; try { symb = this->get_symbol(name); return symb; } catch(ENoSymbolEntry e) { if(this->parent == NULL) { throw ENoSymbolEntry(); } else { /* Will never be NULL because exception is thrown */ return this->parent->get_scoped_symbol(name); } } } /* * Will return true if a symbol is found. If get_symbol throws * an ENoSymbolEntry exception, then the symbol isn't in the symbol * table. This only checks for the existance in the local symbol table. */ bool SymbolTable::symbol_exists(std::string name) { try { this->get_symbol(name); } catch(ENoSymbolEntry e) { return false; } return true; } void SymbolTable::print_table(std::size_t depth) { std::clog << this->to_string(depth) << std::endl; } std::string SymbolTable::to_string(std::size_t depth) { std::stringstream ss; for(std::size_t i = 0; i < this->HASHTABLE_SIZE; ++i) { std::deque<AbstractSymbol*> b = this->bucket[i]; std::deque<AbstractSymbol*>::iterator it; for(it = b.begin(); it != b.end(); ++it) {\ std::size_t index = it - b.begin(); ss << (*(b[i])).to_string(depth) << std::endl; //ss << (*it)->to_string(depth) << std::endl; } } return ss.str(); } /* Basic Symbol constructor */ BasicSymbol::BasicSymbol(std::string n, std::string t, bool p) : AbstractSymbol(n,t), pointer(p) { } /* Function symbol constructor */ FunctionSymbol::FunctionSymbol(std::string n, std::string t, bool p, bool d) : AbstractSymbol(n,t), pointer(p), def_needed(d) { } std::string FunctionSymbol::to_string(std::size_t depth) { std::stringstream ss; ss << AbstractSymbol::to_string(depth) << std::endl; ss << this->params.to_string(depth+1) << std::endl; ss << this->locals.to_string(depth+1) << std::endl; return ss.str(); }<|endoftext|>
<commit_before>#include "google/protobuf/descriptor.h" #include "boost/system/error_code.hpp" #include "vtrc-exception.h" #include "vtrc-errors.pb.h" namespace vtrc { namespace common { namespace gpb = google::protobuf; namespace { const std::string unknown_error("Unknown error"); const std::string &get_internal_error( unsigned code ) { const gpb::EnumValueDescriptor *ev = vtrc_errors::errors_numbers_descriptor( ) ->FindValueByNumber( code ); if( ev ) { return ev->options( ).GetExtension( vtrc_errors::description ); } return unknown_error; } std::string get_error_code_string( unsigned code, unsigned category ) { if( category == vtrc_errors::CATEGORY_INTERNAL ) { return get_internal_error( code ); } else if( category == vtrc_errors::CATEGORY_SYSTEM ) { try { boost::system::error_code ec(code, boost::system::system_category( )); return ec.message( ); } catch( const std::exception &ex ) { return ex.what( ); } } return unknown_error; } std::string get_error_code_string( unsigned code ) { return get_error_code_string(code, vtrc_errors::CATEGORY_INTERNAL); } } exception::exception( unsigned code, unsigned code_category ) :std::runtime_error(get_error_code_string(code, code_category)) ,code_(code) ,category_(code_category) { } exception::exception(unsigned code, unsigned code_category, const std::string &additional) :std::runtime_error(get_error_code_string(code, code_category)) ,code_(code) ,category_(code_category) ,additional_(additional) { } exception::exception( unsigned code ) :std::runtime_error(get_error_code_string(code)) ,code_(code) ,category_(vtrc_errors::CATEGORY_INTERNAL) { } exception::exception( unsigned code, const std::string &additional ) :std::runtime_error(get_error_code_string(code)) ,code_(code) ,category_(vtrc_errors::CATEGORY_INTERNAL) ,additional_(additional) { } exception::~exception( ) throw ( ) { } const char *exception::additional( ) const { return additional_.c_str( ); } unsigned exception::code( ) const { return code_; } unsigned exception::category( ) const { return category_; } }} <commit_msg>exceptions<commit_after>#include "google/protobuf/descriptor.h" #include "boost/system/error_code.hpp" #include "vtrc-exception.h" #include "vtrc-errors.pb.h" namespace vtrc { namespace common { namespace gpb = google::protobuf; namespace { const std::string unknown_error("Unknown error"); const unsigned default_category = vtrc_errors::CATEGORY_INTERNAL; const std::string &get_internal_error( unsigned code ) { const gpb::EnumValueDescriptor *ev = vtrc_errors::errors_numbers_descriptor( ) ->FindValueByNumber( code ); if( ev ) { return ev->options( ).GetExtension( vtrc_errors::description ); } return unknown_error; } std::string get_error_code_string( unsigned code, unsigned category ) { if( category == vtrc_errors::CATEGORY_INTERNAL ) { return get_internal_error( code ); } else if( category == vtrc_errors::CATEGORY_SYSTEM ) { try { boost::system::error_code ec(code, boost::system::system_category( )); return ec.message( ); } catch( const std::exception &ex ) { return ex.what( ); } } return unknown_error; } std::string get_error_code_string( unsigned code ) { return get_error_code_string( code, default_category ); } } exception::exception( unsigned code, unsigned code_category ) :std::runtime_error(get_error_code_string(code, code_category)) ,code_(code) ,category_(code_category) { } exception::exception(unsigned code, unsigned code_category, const std::string &additional) :std::runtime_error(get_error_code_string(code, code_category)) ,code_(code) ,category_(code_category) ,additional_(additional) { } exception::exception( unsigned code ) :std::runtime_error(get_error_code_string(code)) ,code_(code) ,category_(default_category) { } exception::exception( unsigned code, const std::string &additional ) :std::runtime_error(get_error_code_string(code)) ,code_(code) ,category_(default_category) ,additional_(additional) { } exception::~exception( ) throw ( ) { } const char *exception::additional( ) const { return additional_.c_str( ); } unsigned exception::code( ) const { return code_; } unsigned exception::category( ) const { return category_; } }} <|endoftext|>
<commit_before>#include <vector> #include <utility> #include <algorithm> #include <functional> #include <unordered_set> #include "tokenizer.h" #include "shl_exception.h" using std::stack; using std::function; using std::unordered_set; namespace shl { vector<pair<Range, Scope> > Tokenizer::tokenize(const Grammar& grammar, const string& text) { vector<pair<Range, Scope> > tokens; vector<const Pattern*> pattern_stack; tokens.push_back(std::make_pair(Range(0, text.size()), Scope(grammar.name))); tokenize(text, grammar, Match::make_dummy(0,0), pattern_stack, tokens); return tokens; } void for_all_subrules(const vector<Pattern>& root, function<void(const Pattern&)> callback, int max_depth) { if (max_depth <= 0) return; for (const auto& pattern : root) { const Pattern& pat = (pattern.include != nullptr)? *pattern.include : pattern; if (pattern.begin.empty()) { for_all_subrules(root, callback, max_depth - 1); } else { callback(pat); } } } void for_all_subrules(const vector<Pattern>& patterns, function<void(const Pattern&)> callback) { // Define containing pattern to be below // { patterns: [ {}, {} ] } // it have no match/begin but only patterns // There can't be 2 containing patterns as parent and child // so we set the max_depth to be 2 for_all_subrules(patterns, callback, 2); } /** * Find the next lexeme iteratively * * This method find the next lexeme by matching all begin field of the sub-patterns * of current rule, and its own end field, whichever comes first will be seleteced * * When true returned, found will contain the selected next pattern, and match will hold * the results. When false returned, there are 3 scenarios: * 1. end field is matched, found & match contains results * 2. current pattern is toplevel rule, so no end field, found is nullptr * 3. When nothing can be matched(either source text or syntax definition is invalid), * and user specified OPTION_TOLERATE_ERROR, found will be nullptr, otherwise exception * will be thrown */ bool Tokenizer::next_lexeme(const string& text, const Match& begin_lexeme, const Pattern& pattern, const Pattern** found, Match& match) { int pos = begin_lexeme[0].end(); const Pattern* found_pattern = nullptr; Match first_match; bool is_close = false; // first find pattern or end pattern, whichever comes first for_all_subrules(pattern.patterns, [&found_pattern, &first_match, pos, &text](const Pattern& pattern) { const Pattern& sub_pattern = (pattern.include == nullptr)? pattern : *pattern.include; Match tmp = sub_pattern.begin.match(text, pos); if (tmp != Match::NOT_MATCHED) { if( found_pattern == nullptr || tmp[0].position < first_match[0].position) { first_match = std::move(tmp); found_pattern = &sub_pattern; } } }); if (!pattern.end.empty()) { Match tmp = pattern.end.match(text, pos); if (tmp != Match::NOT_MATCHED) { if( found_pattern == nullptr || tmp[0].position < first_match[0].position) { first_match = std::move(tmp); found_pattern = &pattern; is_close = true; } } } if ( found_pattern != nullptr) { *found = found_pattern; match = first_match; return !is_close; } // special handle for toplevel rule if (pattern.end.empty()) { // all rule with begin will has an end, which is enforced by grammar loader // so only toplevel rules can be here *found = nullptr; is_close = true; return false; } // When no lexeme found if (_option & OPTION_TOLERATE_ERROR) { *found = nullptr; return false; } else { throw InvalidSourceException("scope not properly closed"); } } vector<string> get_name(vector<const Pattern*>& stack, const string& name) { vector<string> names; for(auto pattern : stack) { names.push_back(pattern->name); } names.push_back(name); return names; } void Tokenizer::add_scope(vector<pair<Range, Scope> >& tokens, const Range& range, vector<const Pattern*>& stack, const string& name) { if (name.empty()) return; Scope scope(get_name(stack, name)); tokens.push_back(std::make_pair(range, scope)); } inline void append_back(vector<pair<Range, Scope> >& target, const vector<pair<Range, Scope> >& source ) { std::move(source.begin(), source.end(), std::back_inserter(target)); } void Tokenizer::process_capture(vector<pair<Range, Scope> >& tokens, const Match& match, vector<const Pattern*>& stack, const map<int, string>& capture) { for (auto& pair : capture) { unsigned int capture_num = pair.first; const string& name = pair.second; if (match.size() > capture_num) { add_scope(tokens, match[capture_num], stack, name); } else { if ((_option & OPTION_TOLERATE_ERROR) == 0) { throw InvalidSourceException("capture number out of range"); } } } } Match Tokenizer::tokenize(const string& text, const Pattern& pattern, const Match& begin_lexeme, vector<const Pattern*>& stack, vector<pair<Range, Scope> >& tokens) { stack.push_back(&pattern); const Pattern* found_pattern = nullptr; Match last_lexeme, match; last_lexeme = begin_lexeme; while(next_lexeme(text, last_lexeme, pattern, &found_pattern, match)) { if (found_pattern->is_match_rule) { add_scope(tokens, match[0], stack, found_pattern->name); process_capture(tokens, match, stack, found_pattern->captures); last_lexeme = match; } else { vector<pair<Range, Scope> > child_tokens; Match end_match = tokenize(text, *found_pattern, match, stack, child_tokens); Range name_range = Range(match[0].position, end_match[0].end() - match[0].position); add_scope(tokens, name_range, stack, ""); process_capture(tokens, match, stack, found_pattern->begin_captures); Range content_range = Range(match[0].end(), end_match[0].position - match[0].end()); add_scope(tokens, content_range, stack, found_pattern->content_name); append_back(tokens, child_tokens); process_capture(tokens, match, stack, found_pattern->end_captures); last_lexeme = end_match; } } stack.pop_back(); if ( found_pattern == nullptr) { //see comments for next_lexeme return last_lexeme; } else { return match; } } } <commit_msg>bug fix 2<commit_after>#include <vector> #include <utility> #include <algorithm> #include <functional> #include <unordered_set> #include "tokenizer.h" #include "shl_exception.h" using std::stack; using std::function; using std::unordered_set; namespace shl { vector<pair<Range, Scope> > Tokenizer::tokenize(const Grammar& grammar, const string& text) { vector<pair<Range, Scope> > tokens; vector<const Pattern*> pattern_stack; tokens.push_back(std::make_pair(Range(0, text.size()), Scope(grammar.name))); tokenize(text, grammar, Match::make_dummy(0,0), pattern_stack, tokens); return tokens; } void for_all_subrules(const vector<Pattern>& root, function<void(const Pattern&)> callback, int max_depth) { if (max_depth <= 0) return; for (const auto& pattern : root) { const Pattern& pat = (pattern.include != nullptr)? *pattern.include : pattern; if (pat.begin.empty()) { for_all_subrules(pat.patterns, callback, max_depth - 1); } else { callback(pat); } } } void for_all_subrules(const vector<Pattern>& patterns, function<void(const Pattern&)> callback) { // Define containing pattern to be below // { patterns: [ {}, {} ] } // it have no match/begin but only patterns // There can't be 2 containing patterns as parent and child // so we set the max_depth to be 2 for_all_subrules(patterns, callback, 2); } /** * Find the next lexeme iteratively * * This method find the next lexeme by matching all begin field of the sub-patterns * of current rule, and its own end field, whichever comes first will be seleteced * * When true returned, found will contain the selected next pattern, and match will hold * the results. When false returned, there are 3 scenarios: * 1. end field is matched, found & match contains results * 2. current pattern is toplevel rule, so no end field, found is nullptr * 3. When nothing can be matched(either source text or syntax definition is invalid), * and user specified OPTION_TOLERATE_ERROR, found will be nullptr, otherwise exception * will be thrown */ bool Tokenizer::next_lexeme(const string& text, const Match& begin_lexeme, const Pattern& pattern, const Pattern** found, Match& match) { int pos = begin_lexeme[0].end(); const Pattern* found_pattern = nullptr; Match first_match; bool is_close = false; // first find pattern or end pattern, whichever comes first for_all_subrules(pattern.patterns, [&found_pattern, &first_match, pos, &text](const Pattern& sub_pattern) { Match tmp = sub_pattern.begin.match(text, pos); if (tmp != Match::NOT_MATCHED) { if( found_pattern == nullptr || tmp[0].position < first_match[0].position) { first_match = std::move(tmp); found_pattern = &sub_pattern; } } }); if (!pattern.end.empty()) { Match tmp = pattern.end.match(text, pos); if (tmp != Match::NOT_MATCHED) { if( found_pattern == nullptr || tmp[0].position < first_match[0].position) { first_match = std::move(tmp); found_pattern = &pattern; is_close = true; } } } if ( found_pattern != nullptr) { *found = found_pattern; match = first_match; return !is_close; } // special handle for toplevel rule if (pattern.end.empty()) { // all rule with begin will has an end, which is enforced by grammar loader // so only toplevel rules can be here *found = nullptr; is_close = true; return false; } // When no lexeme found if (_option & OPTION_TOLERATE_ERROR) { *found = nullptr; return false; } else { throw InvalidSourceException("scope not properly closed"); } } vector<string> get_name(vector<const Pattern*>& stack, const string& name) { vector<string> names; for(auto pattern : stack) { names.push_back(pattern->name); } names.push_back(name); return names; } void Tokenizer::add_scope(vector<pair<Range, Scope> >& tokens, const Range& range, vector<const Pattern*>& stack, const string& name) { if (name.empty()) return; Scope scope(get_name(stack, name)); tokens.push_back(std::make_pair(range, scope)); } inline void append_back(vector<pair<Range, Scope> >& target, const vector<pair<Range, Scope> >& source ) { std::move(source.begin(), source.end(), std::back_inserter(target)); } void Tokenizer::process_capture(vector<pair<Range, Scope> >& tokens, const Match& match, vector<const Pattern*>& stack, const map<int, string>& capture) { for (auto& pair : capture) { unsigned int capture_num = pair.first; const string& name = pair.second; if (match.size() > capture_num) { add_scope(tokens, match[capture_num], stack, name); } else { if ((_option & OPTION_TOLERATE_ERROR) == 0) { throw InvalidSourceException("capture number out of range"); } } } } Match Tokenizer::tokenize(const string& text, const Pattern& pattern, const Match& begin_lexeme, vector<const Pattern*>& stack, vector<pair<Range, Scope> >& tokens) { stack.push_back(&pattern); const Pattern* found_pattern = nullptr; Match last_lexeme, match; last_lexeme = begin_lexeme; while(next_lexeme(text, last_lexeme, pattern, &found_pattern, match)) { if (found_pattern->is_match_rule) { add_scope(tokens, match[0], stack, found_pattern->name); process_capture(tokens, match, stack, found_pattern->captures); last_lexeme = match; } else { vector<pair<Range, Scope> > child_tokens; Match end_match = tokenize(text, *found_pattern, match, stack, child_tokens); Range name_range = Range(match[0].position, end_match[0].end() - match[0].position); add_scope(tokens, name_range, stack, found_pattern->name); process_capture(tokens, match, stack, found_pattern->begin_captures); Range content_range = Range(match[0].end(), end_match[0].position - match[0].end()); add_scope(tokens, content_range, stack, found_pattern->content_name); append_back(tokens, child_tokens); process_capture(tokens, match, stack, found_pattern->end_captures); last_lexeme = end_match; } } stack.pop_back(); if ( found_pattern == nullptr) { //see comments for next_lexeme return last_lexeme; } else { return match; } } } <|endoftext|>
<commit_before>#include <cilantro/connected_component_segmentation.hpp> #include <stack> #include <iostream> ConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector<Eigen::Vector3f> &points, const std::vector<Eigen::Vector3f> &normals, const std::vector<Eigen::Vector3f> &colors) : points_(&points), normals_((normals.size() == points.size()) ? &normals : NULL), colors_((colors.size() == points.size()) ? &colors : NULL), kd_tree_(new KDTree(points)), kd_tree_owned_(true) {} ConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector<Eigen::Vector3f> &points, const std::vector<Eigen::Vector3f> &normals, const std::vector<Eigen::Vector3f> &colors, const KDTree &kd_tree) : points_(&points), normals_((normals.size() == points.size()) ? &normals : NULL), colors_((colors.size() == points.size()) ? &colors : NULL), kd_tree_((KDTree*)&kd_tree), kd_tree_owned_(false) {} ConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud) : points_(&cloud.points), normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL), colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL), kd_tree_(new KDTree(cloud.points)), kd_tree_owned_(true) {} ConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud, const KDTree &kd_tree) : points_(&cloud.points), normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL), colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL), kd_tree_((KDTree*)&kd_tree), kd_tree_owned_(false) {} ConnectedComponentSegmentation::~ConnectedComponentSegmentation() { if (kd_tree_owned_) delete kd_tree_; } ConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(std::vector<size_t> seeds_ind, float dist_thresh, float normal_angle_thresh, float color_diff_thresh, size_t min_segment_size, size_t max_segment_size) { dist_thresh_ = dist_thresh; normal_angle_thresh_ = normal_angle_thresh; color_diff_thresh_ = color_diff_thresh; min_segment_size_ = min_segment_size; max_segment_size_ = max_segment_size; std::vector<bool> has_been_assigned(points_->size(), 0); std::vector<size_t> neighbors; std::vector<float> distances; component_indices_.clear(); for (size_t i = 0; i < seeds_ind.size(); i++) { if (has_been_assigned[seeds_ind[i]]) continue; std::vector<size_t> curr_cc_ind; std::vector<bool> is_in_stack(points_->size(), 0); std::stack<size_t> seeds_stack; seeds_stack.push(seeds_ind[i]); is_in_stack[seeds_ind[i]] = 1; while (!seeds_stack.empty()) { size_t curr_seed = seeds_stack.top(); seeds_stack.pop(); has_been_assigned[curr_seed] = 1; curr_cc_ind.emplace_back(curr_seed); kd_tree_->radiusSearch((*points_)[curr_seed], dist_thresh_, neighbors, distances); for (size_t j = 0; j < neighbors.size(); j++) { if (is_similar_(curr_seed,neighbors[j]) && !is_in_stack[neighbors[j]]) { seeds_stack.push(neighbors[j]); is_in_stack[neighbors[j]] = 1; } } } if (curr_cc_ind.size() >= min_segment_size_ && curr_cc_ind.size() <= max_segment_size_) { component_indices_.emplace_back(curr_cc_ind); } } std::sort(component_indices_.begin(), component_indices_.end(), vector_size_comparator_); label_map_ = std::vector<size_t>(points_->size(), component_indices_.size()); for (size_t i = 0; i < component_indices_.size(); i++) { for (size_t j = 0; j < component_indices_[i].size(); j++) { label_map_[component_indices_[i][j]] = i; } } return *this; } ConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(float dist_thresh, float normal_angle_thresh, float color_diff_thresh, size_t min_segment_size, size_t max_segment_size) { std::vector<size_t> seeds_ind(points_->size()); for (size_t i = 0; i < seeds_ind.size(); i++) { seeds_ind[i] = i; } return segment(seeds_ind, dist_thresh, normal_angle_thresh, color_diff_thresh, min_segment_size, max_segment_size); } <commit_msg>Minor change<commit_after>#include <cilantro/connected_component_segmentation.hpp> #include <stack> #include <iostream> ConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector<Eigen::Vector3f> &points, const std::vector<Eigen::Vector3f> &normals, const std::vector<Eigen::Vector3f> &colors) : points_(&points), normals_((normals.size() == points.size()) ? &normals : NULL), colors_((colors.size() == points.size()) ? &colors : NULL), kd_tree_(new KDTree(points)), kd_tree_owned_(true) {} ConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector<Eigen::Vector3f> &points, const std::vector<Eigen::Vector3f> &normals, const std::vector<Eigen::Vector3f> &colors, const KDTree &kd_tree) : points_(&points), normals_((normals.size() == points.size()) ? &normals : NULL), colors_((colors.size() == points.size()) ? &colors : NULL), kd_tree_((KDTree*)&kd_tree), kd_tree_owned_(false) {} ConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud) : points_(&cloud.points), normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL), colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL), kd_tree_(new KDTree(cloud.points)), kd_tree_owned_(true) {} ConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud, const KDTree &kd_tree) : points_(&cloud.points), normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL), colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL), kd_tree_((KDTree*)&kd_tree), kd_tree_owned_(false) {} ConnectedComponentSegmentation::~ConnectedComponentSegmentation() { if (kd_tree_owned_) delete kd_tree_; } ConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(std::vector<size_t> seeds_ind, float dist_thresh, float normal_angle_thresh, float color_diff_thresh, size_t min_segment_size, size_t max_segment_size) { dist_thresh_ = dist_thresh; normal_angle_thresh_ = normal_angle_thresh; color_diff_thresh_ = color_diff_thresh; min_segment_size_ = min_segment_size; max_segment_size_ = max_segment_size; std::vector<bool> has_been_assigned(points_->size(), false); std::vector<size_t> neighbors; std::vector<float> distances; component_indices_.clear(); for (size_t i = 0; i < seeds_ind.size(); i++) { if (has_been_assigned[seeds_ind[i]]) continue; std::vector<size_t> curr_cc_ind; std::vector<bool> is_in_stack(points_->size(), 0); std::stack<size_t> seeds_stack; seeds_stack.push(seeds_ind[i]); is_in_stack[seeds_ind[i]] = 1; while (!seeds_stack.empty()) { size_t curr_seed = seeds_stack.top(); seeds_stack.pop(); has_been_assigned[curr_seed] = 1; curr_cc_ind.emplace_back(curr_seed); kd_tree_->radiusSearch((*points_)[curr_seed], dist_thresh_, neighbors, distances); for (size_t j = 0; j < neighbors.size(); j++) { if (is_similar_(curr_seed,neighbors[j]) && !is_in_stack[neighbors[j]]) { seeds_stack.push(neighbors[j]); is_in_stack[neighbors[j]] = 1; } } } if (curr_cc_ind.size() >= min_segment_size_ && curr_cc_ind.size() <= max_segment_size_) { component_indices_.emplace_back(curr_cc_ind); } } std::sort(component_indices_.begin(), component_indices_.end(), vector_size_comparator_); label_map_ = std::vector<size_t>(points_->size(), component_indices_.size()); for (size_t i = 0; i < component_indices_.size(); i++) { for (size_t j = 0; j < component_indices_[i].size(); j++) { label_map_[component_indices_[i][j]] = i; } } return *this; } ConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(float dist_thresh, float normal_angle_thresh, float color_diff_thresh, size_t min_segment_size, size_t max_segment_size) { std::vector<size_t> seeds_ind(points_->size()); for (size_t i = 0; i < seeds_ind.size(); i++) { seeds_ind[i] = i; } return segment(seeds_ind, dist_thresh, normal_angle_thresh, color_diff_thresh, min_segment_size, max_segment_size); } <|endoftext|>
<commit_before>// $Id: quadrature_gauss_2D.C,v 1.16 2004-11-30 23:00:21 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library 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 // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "quadrature_gauss.h" #include "quadrature_jacobi.h" void QGauss::init_2D(const ElemType _type) { #if DIM > 1 //----------------------------------------------------------------------- // 2D quadrature rules switch (_type) { //--------------------------------------------- // Quadrilateral quadrature rules case QUAD4: case QUAD8: case QUAD9: { // We compute the 2D quadrature rule as a tensor // product of the 1D quadrature rule. QGauss q1D(1,_order); q1D.init(EDGE2); tensor_product_quad( q1D ); return; } //--------------------------------------------- // Triangle quadrature rules case TRI3: case TRI6: { switch(_order) { case CONSTANT: case FIRST: { // Exact for linears _points.resize(1); _weights.resize(1); _points[0](0) = .33333333333333333333333333333333; _points[0](1) = .33333333333333333333333333333333; _weights[0] = .5; return; } case SECOND: { // Exact for quadratics _points.resize(3); _weights.resize(3); _points[0](0) = .5; _points[0](1) = .5; _points[1](0) = 0.; _points[1](1) = .5; _points[2](0) = .5; _points[2](1) = .0; _weights[0] = 1./6.; _weights[1] = 1./6.; _weights[2] = 1./6.; return; } case THIRD: { // Exact for cubics _points.resize(4); _weights.resize(4); _points[0](0) = .33333333333333333333333333333333; _points[0](1) = .33333333333333333333333333333333; _points[1](0) = .2; _points[1](1) = .6; _points[2](0) = .2; _points[2](1) = .2; _points[3](0) = .6; _points[3](1) = .2; _weights[0] = -27./96.; _weights[1] = 25./96.; _weights[2] = 25./96.; _weights[3] = 25./96.; return; } case FOURTH: case FIFTH: { // Exact for quintics // Taken from "Quadrature on Simplices of Arbitrary // Dimension" by Walkington _points.resize(7); _weights.resize(7); const Real b1 = 2./7. + sqrt(15.)/21.; const Real a1 = 1. - 2.*b1; const Real b2 = 2./7. - sqrt(15.)/21.; const Real a2 = 1. - 2.*b2; _points[0](0) = 1./3.; _points[0](1) = 1./3.; _points[1](0) = a1; _points[1](1) = b1; _points[2](0) = b1; _points[2](1) = a1; _points[3](0) = b1; _points[3](1) = b1; _points[4](0) = a2; _points[4](1) = b2; _points[5](0) = b2; _points[5](1) = a2; _points[6](0) = b2; _points[6](1) = b2; _weights[0] = 9./80.; _weights[1] = 31./480. + sqrt(15.)/2400.; _weights[2] = _weights[1]; _weights[3] = _weights[1]; _weights[4] = 31./480. - sqrt(15.)/2400.; _weights[5] = _weights[4]; _weights[6] = _weights[4]; return; } case SIXTH: case SEVENTH: { // Exact for seventh degree polynomials // Taken from http://www.rpi.edu/~gilade/fem6.ps by // Flaherty _points.resize(12); _weights.resize(12); const Real w1 = 0.050844906370207 / 2; const Real w2 = 0.116786275726379 / 2; const Real w3 = 0.082851075618374 / 2; const Real a1 = 0.873821971016996; const Real a2 = 0.063089014491502; const Real b1 = 0.501426509658179; const Real b2 = 0.249286745170910; const Real c1 = 0.636502499121399; const Real c2 = 0.310352451033785; const Real c3 = 0.053145049844816; _points[0](0) = a1; _points[0](1) = a2; _points[1](0) = a2; _points[1](1) = a1; _points[2](0) = a2; _points[2](1) = a2; _points[3](0) = b1; _points[3](1) = b2; _points[4](0) = b2; _points[4](1) = b1; _points[5](0) = b2; _points[5](1) = b2; _points[6](0) = c1; _points[6](1) = c2; _points[7](0) = c1; _points[7](1) = c3; _points[8](0) = c2; _points[8](1) = c1; _points[9](0) = c2; _points[9](1) = c3; _points[10](0) = c3; _points[10](1) = c1; _points[11](0) = c3; _points[11](1) = c2; _weights[0] = w1; _weights[1] = w1; _weights[2] = w1; _weights[3] = w2; _weights[4] = w2; _weights[5] = w2; _weights[6] = w3; _weights[7] = w3; _weights[8] = w3; _weights[9] = w3; _weights[10] = w3; _weights[11] = w3; return; } case EIGHTH: case NINTH: case TENTH: case ELEVENTH: case TWELFTH: case THIRTEENTH: case FOURTEENTH: case FIFTEENTH: case SIXTEENTH: case SEVENTEENTH: case EIGHTTEENTH: case NINTEENTH: case TWENTIETH: case TWENTYFIRST: case TWENTYSECOND: case TWENTYTHIRD: { // The following quadrature rules are // generated as conical products. These // tend to be non-optimal (use too many // points, cluster points in certain // regions of the domain) but they are // quite easy to automatically generate // using a 1D Gauss rule on [0,1] and a // 1D Jacobi-Gauss rule on [0,1]. // Define the quadrature rules... QGauss gauss1D(1,_order); QJacobi jac1D(1,_order,1,0); // The Gauss rule needs to be scaled to [0,1] std::pair<Real, Real> old_range(-1,1); std::pair<Real, Real> new_range(0,1); gauss1D.scale(old_range, new_range); // Compute the tensor product tensor_product_tri(gauss1D, jac1D); return; } default: { std::cout << "Quadrature rule not supported!" << std::endl; error(); } } } //--------------------------------------------- // Unsupported type default: { std::cerr << "Element type not supported!:" << _type << std::endl; error(); } } error(); return; #endif } <commit_msg><commit_after>// $Id: quadrature_gauss_2D.C,v 1.17 2004-12-01 02:37:02 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library 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 // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local includes #include "quadrature_gauss.h" #include "quadrature_jacobi.h" void QGauss::init_2D(const ElemType _type) { #if DIM > 1 //----------------------------------------------------------------------- // 2D quadrature rules switch (_type) { //--------------------------------------------- // Quadrilateral quadrature rules case QUAD4: case QUAD8: case QUAD9: { // We compute the 2D quadrature rule as a tensor // product of the 1D quadrature rule. QGauss q1D(1,_order); q1D.init(EDGE2); tensor_product_quad( q1D ); return; } //--------------------------------------------- // Triangle quadrature rules case TRI3: case TRI6: { switch(_order) { case CONSTANT: case FIRST: { // Exact for linears _points.resize(1); _weights.resize(1); _points[0](0) = .33333333333333333333333333333333; _points[0](1) = .33333333333333333333333333333333; _weights[0] = .5; return; } case SECOND: { // Exact for quadratics _points.resize(3); _weights.resize(3); _points[0](0) = .5; _points[0](1) = .5; _points[1](0) = 0.; _points[1](1) = .5; _points[2](0) = .5; _points[2](1) = .0; _weights[0] = 1./6.; _weights[1] = 1./6.; _weights[2] = 1./6.; return; } case THIRD: { // Exact for cubics _points.resize(4); _weights.resize(4); _points[0](0) = .33333333333333333333333333333333; _points[0](1) = .33333333333333333333333333333333; _points[1](0) = .2; _points[1](1) = .6; _points[2](0) = .2; _points[2](1) = .2; _points[3](0) = .6; _points[3](1) = .2; _weights[0] = -27./96.; _weights[1] = 25./96.; _weights[2] = 25./96.; _weights[3] = 25./96.; return; } case FOURTH: case FIFTH: { // Exact for quintics // Taken from "Quadrature on Simplices of Arbitrary // Dimension" by Walkington _points.resize(7); _weights.resize(7); const Real b1 = 2./7. + sqrt(15.)/21.; const Real a1 = 1. - 2.*b1; const Real b2 = 2./7. - sqrt(15.)/21.; const Real a2 = 1. - 2.*b2; _points[0](0) = 1./3.; _points[0](1) = 1./3.; _points[1](0) = a1; _points[1](1) = b1; _points[2](0) = b1; _points[2](1) = a1; _points[3](0) = b1; _points[3](1) = b1; _points[4](0) = a2; _points[4](1) = b2; _points[5](0) = b2; _points[5](1) = a2; _points[6](0) = b2; _points[6](1) = b2; _weights[0] = 9./80.; _weights[1] = 31./480. + sqrt(15.)/2400.; _weights[2] = _weights[1]; _weights[3] = _weights[1]; _weights[4] = 31./480. - sqrt(15.)/2400.; _weights[5] = _weights[4]; _weights[6] = _weights[4]; return; } case SIXTH: case SEVENTH: { // Exact for seventh degree polynomials // Taken from http://www.rpi.edu/~gilade/fem6.ps by // Flaherty _points.resize(12); _weights.resize(12); const Real w1 = 0.050844906370207 / 2.0; const Real w2 = 0.116786275726379 / 2.0; const Real w3 = 0.082851075618374 / 2.0; const Real a1 = 0.873821971016996; const Real a2 = 0.063089014491502; const Real b1 = 0.501426509658179; const Real b2 = 0.249286745170910; const Real c1 = 0.636502499121399; const Real c2 = 0.310352451033785; const Real c3 = 0.053145049844816; _points[0](0) = a1; _points[0](1) = a2; _points[1](0) = a2; _points[1](1) = a1; _points[2](0) = a2; _points[2](1) = a2; _points[3](0) = b1; _points[3](1) = b2; _points[4](0) = b2; _points[4](1) = b1; _points[5](0) = b2; _points[5](1) = b2; _points[6](0) = c1; _points[6](1) = c2; _points[7](0) = c1; _points[7](1) = c3; _points[8](0) = c2; _points[8](1) = c1; _points[9](0) = c2; _points[9](1) = c3; _points[10](0) = c3; _points[10](1) = c1; _points[11](0) = c3; _points[11](1) = c2; _weights[0] = w1; _weights[1] = w1; _weights[2] = w1; _weights[3] = w2; _weights[4] = w2; _weights[5] = w2; _weights[6] = w3; _weights[7] = w3; _weights[8] = w3; _weights[9] = w3; _weights[10] = w3; _weights[11] = w3; return; } case EIGHTH: case NINTH: case TENTH: case ELEVENTH: case TWELFTH: case THIRTEENTH: case FOURTEENTH: case FIFTEENTH: case SIXTEENTH: case SEVENTEENTH: case EIGHTTEENTH: case NINTEENTH: case TWENTIETH: case TWENTYFIRST: case TWENTYSECOND: case TWENTYTHIRD: { // The following quadrature rules are // generated as conical products. These // tend to be non-optimal (use too many // points, cluster points in certain // regions of the domain) but they are // quite easy to automatically generate // using a 1D Gauss rule on [0,1] and a // 1D Jacobi-Gauss rule on [0,1]. // Define the quadrature rules... QGauss gauss1D(1,_order); QJacobi jac1D(1,_order,1,0); // The Gauss rule needs to be scaled to [0,1] std::pair<Real, Real> old_range(-1,1); std::pair<Real, Real> new_range(0,1); gauss1D.scale(old_range, new_range); // Compute the tensor product tensor_product_tri(gauss1D, jac1D); return; } default: { std::cout << "Quadrature rule not supported!" << std::endl; error(); } } } //--------------------------------------------- // Unsupported type default: { std::cerr << "Element type not supported!:" << _type << std::endl; error(); } } error(); return; #endif } <|endoftext|>
<commit_before>// Copyright 2008 Henry de Valence // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library. If not, see <http://www.gnu.org/licenses/>. //Mine #include "worldclock.h" //Qt #include <QtGui/QPainter> //KDE #include <KDebug> #include <KDialog> #include <KConfigGroup> //Plasma #include <plasma/theme.h> #include <plasma/dataengine.h> //Marble #include <marble/MarbleMap.h> #include <marble/SunLocator.h> #include <marble/ClipPainter.h> WorldClock::WorldClock(QObject *parent, const QVariantList &args) : Plasma::Applet(parent, args), m_configDialog(0), m_map(0), m_sun(0) { setHasConfigurationInterface(true); setDrawStandardBackground(true); //The applet needs a 2:1 ratio //so that the map fits properly resize(QSize(400, 200)); } void WorldClock::init() { KConfigGroup cg = config(); m_map = new MarbleMap( ); m_map->setProjection( Equirectangular ); m_map->setSize(geometry().size().width(), geometry().size().height()); //The radius of the map using this projection //will always be 1/4 of the desired width. m_map->setRadius( (geometry().size().width() / 4 ) ); //offset so that the date line isn't //right on the edge of the map //or user choice m_map->centerOn( cg.readEntry("rotation", -20), 0 ); //Set how we want the map to look m_map->setMapTheme( "earth/bluemarble/bluemarble.dgml" ); // &c. m_map->setShowCompass( false ); m_map->setShowScaleBar( false ); m_map->setShowGrid( false ); m_map->setShowPlaces( false ); m_map->setShowCities( true ); m_map->setShowOtherPlaces( false ); m_map->setShowRelief( true ); m_map->setShowIceLayer( true ); //Radius*4 = width m_map->setRadius( 100 ); //Set up the Sun to draw night/day shadow m_sun = m_map->sunLocator(); m_sun->setShow(true); m_sun->setCitylights(true); if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) == Qt::Checked) m_sun->setCentered(true); m_sun->update(); m_map->updateSun(); //We need to zoom the map every time we change size connect(this, SIGNAL(geometryChanged()), this, SLOT(resizeMap())); } WorldClock::~WorldClock() { delete m_configDialog; } //We want to redraw the map every 10 mins //so that the night/day shade is current. //10 mins is 1/144th of a rotation. void WorldClock::connectToEngine() { Plasma::DataEngine* timeEngine = dataEngine("time"); //update every 5 mins timeEngine->connectSource("Local", this, 30000, Plasma::AlignToMinute); } void WorldClock::resizeMap() { m_map->setSize(geometry().size().width(), geometry().size().height()); //The radius of the map using this projection //will always be 1/4 of the desired width. m_map->setRadius( (geometry().size().width() / 4 ) ); update(); } void WorldClock::dataUpdated(const QString &name, const Plasma::DataEngine::Data &data) { m_sun->update(); m_map->updateSun(); update(); } void WorldClock::paintInterface(QPainter *p, const QStyleOptionGraphicsItem *option, const QRect &contentsRect) { kDebug() << contentsRect; QRect rect = contentsRect; //By creating a pixmap and then painting that //we avoid an issue where the map is offset //from the border of the plasmoid and it looks ugly QPixmap pixmap( rect.size() ); ClipPainter cp( &pixmap , false ); m_map->paint(cp, rect); p->drawPixmap( 0, 0, pixmap ); } void WorldClock::showConfigurationInterface() { if(m_configDialog == 0) { m_configDialog = new KDialog; ui.setupUi(m_configDialog->mainWidget()); m_configDialog->setPlainCaption(i18n("Worldclock Applet Configuration")); m_configDialog->setButtons(KDialog::Ok | KDialog::Apply | KDialog::Cancel); KConfigGroup cg = config(); ui.rotationLatLonEdit->setValue(cg.readEntry("rotation", -20)); if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) == Qt::Checked) ui.centerSunCheckBox->setChecked(true); connect(m_configDialog, SIGNAL(okClicked()), this, SLOT(configAccepted())); connect(m_configDialog, SIGNAL(applyClicked()), this, SLOT(configAccepted())); } m_configDialog->show(); } void WorldClock::configAccepted() { KConfigGroup cg = config(); if( ui.centerSunCheckBox->checkState() != cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) ) { switch(ui.centerSunCheckBox->checkState()) { case Qt::Checked : m_sun->setCentered(true); break; default : m_sun->setCentered(false); break; } m_sun->update(); m_map->updateSun(); update(); } if( ui.rotationLatLonEdit->value() != cg.readEntry("rotation", -20) ) { m_map->centerOn(ui.rotationLatLonEdit->value(), 0); update(); } cg.writeEntry("centersun", static_cast<int>(ui.centerSunCheckBox->checkState())); cg.writeEntry("rotation", ui.rotationLatLonEdit->value()); } #include "worldclock.moc" <commit_msg>Now uses GeoPainter instead of ClipPainter<commit_after>// Copyright 2008 Henry de Valence // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library. If not, see <http://www.gnu.org/licenses/>. //Mine #include "worldclock.h" //Qt #include <QtGui/QPainter> //KDE #include <KDebug> #include <KDialog> #include <KConfigGroup> //Plasma #include <plasma/theme.h> #include <plasma/dataengine.h> //Marble #include "../lib/MarbleMap.h" #include "../lib/SunLocator.h" #include "../lib/ViewParams.h" #include "../lib/GeoPainter.h" WorldClock::WorldClock(QObject *parent, const QVariantList &args) : Plasma::Applet(parent, args), m_configDialog(0), m_map(0), m_sun(0) { setHasConfigurationInterface(true); //The applet needs a 2:1 ratio //so that the map fits properly resize(QSize(400, 200)); } void WorldClock::init() { KConfigGroup cg = config(); m_map = new MarbleMap( ); m_map->setProjection( Equirectangular ); m_map->setSize(geometry().size().width(), geometry().size().height()); //The radius of the map using this projection //will always be 1/4 of the desired width. m_map->setRadius( (geometry().size().width() / 4 ) ); //offset so that the date line isn't //right on the edge of the map //or user choice m_map->centerOn( cg.readEntry("rotation", -20), 0 ); //Set how we want the map to look m_map->setMapTheme( "earth/bluemarble/bluemarble.dgml" ); // &c. m_map->setShowCompass( false ); m_map->setShowScaleBar( false ); m_map->setShowGrid( false ); m_map->setShowPlaces( false ); m_map->setShowCities( true ); m_map->setShowOtherPlaces( false ); m_map->setShowRelief( true ); m_map->setShowIceLayer( true ); //Radius*4 = width m_map->setRadius( 100 ); //Set up the Sun to draw night/day shadow m_sun = m_map->sunLocator(); m_sun->setShow(true); m_sun->setCitylights(true); if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) == Qt::Checked) m_sun->setCentered(true); m_sun->update(); m_map->updateSun(); //We need to zoom the map every time we change size connect(this, SIGNAL(geometryChanged()), this, SLOT(resizeMap())); } WorldClock::~WorldClock() { delete m_configDialog; } //We want to redraw the map every 10 mins //so that the night/day shade is current. //10 mins is 1/144th of a rotation. void WorldClock::connectToEngine() { Plasma::DataEngine* timeEngine = dataEngine("time"); //update every 5 mins timeEngine->connectSource("Local", this, 30000, Plasma::AlignToMinute); } void WorldClock::resizeMap() { m_map->setSize(geometry().size().width(), geometry().size().height()); //The radius of the map using this projection //will always be 1/4 of the desired width. m_map->setRadius( (geometry().size().width() / 4 ) ); update(); } void WorldClock::dataUpdated(const QString &name, const Plasma::DataEngine::Data &data) { m_sun->update(); m_map->updateSun(); update(); } void WorldClock::paintInterface(QPainter *p, const QStyleOptionGraphicsItem *option, const QRect &contentsRect) { kDebug() << contentsRect; QRect rect = contentsRect; //By creating a pixmap and then painting that //we avoid an issue where the map is offset //from the border of the plasmoid and it looks ugly QPixmap pixmap( rect.size() ); GeoPainter gp( &pixmap, m_map->viewParams()->viewport(), false ); m_map->paint(gp, rect); p->drawPixmap( 0, 0, pixmap ); } void WorldClock::showConfigurationInterface() { if(m_configDialog == 0) { m_configDialog = new KDialog; ui.setupUi(m_configDialog->mainWidget()); m_configDialog->setPlainCaption(i18n("Worldclock Applet Configuration")); m_configDialog->setButtons(KDialog::Ok | KDialog::Apply | KDialog::Cancel); KConfigGroup cg = config(); ui.rotationLatLonEdit->setValue(cg.readEntry("rotation", -20)); if(cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) == Qt::Checked) ui.centerSunCheckBox->setChecked(true); connect(m_configDialog, SIGNAL(okClicked()), this, SLOT(configAccepted())); connect(m_configDialog, SIGNAL(applyClicked()), this, SLOT(configAccepted())); } m_configDialog->show(); } void WorldClock::configAccepted() { KConfigGroup cg = config(); if( ui.centerSunCheckBox->checkState() != cg.readEntry("centersun", static_cast<int>(Qt::Unchecked)) ) { switch(ui.centerSunCheckBox->checkState()) { case Qt::Checked : m_sun->setCentered(true); break; default : m_sun->setCentered(false); break; } m_sun->update(); m_map->updateSun(); update(); } if( ui.rotationLatLonEdit->value() != cg.readEntry("rotation", -20) ) { m_map->centerOn(ui.rotationLatLonEdit->value(), 0); update(); } cg.writeEntry("centersun", static_cast<int>(ui.centerSunCheckBox->checkState())); cg.writeEntry("rotation", ui.rotationLatLonEdit->value()); } #include "worldclock.moc" <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: splargs.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SPLARGS_HXX #define _SPLARGS_HXX #include <i18npool/lang.h> #include <tools/solar.h> #include <tools/gen.hxx> #include <limits.h> // USHRT_MAX #include <tools/string.hxx> class SwTxtNode; class SwIndex; class SpellCheck; class Font; #include <com/sun/star/linguistic2/XSpellAlternatives.hpp> #include <com/sun/star/linguistic2/XSpellChecker1.hpp> #include <com/sun/star/linguistic2/XHyphenatedWord.hpp> /************************************************************************* * struct SwArgsBase *************************************************************************/ struct SwArgsBase // used for text conversion (Hangul/Hanja, ...) { SwTxtNode *pStartNode; SwIndex *pStartIdx; SwTxtNode *pEndNode; SwIndex *pEndIdx; SwArgsBase( SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : pStartNode( pStart ), pStartIdx( &rStart ), pEndNode( pEnd ), pEndIdx( &rEnd ) {} void SetStart(SwTxtNode* pStart, SwIndex& rStart ) { pStartNode = pStart; pStartIdx = &rStart ; } void SetEnd( SwTxtNode* pEnd, SwIndex& rEnd ) { pEndNode = pEnd; pEndIdx = &rEnd ; } }; /************************************************************************* * struct SwConversionArgs * used for text conversion (Hangul/Hanja, Simplified/Traditional Chinese, ...) *************************************************************************/ struct SwConversionArgs : SwArgsBase { rtl::OUString aConvText; // convertible text found LanguageType nConvSrcLang; // (source) language to look for LanguageType nConvTextLang; // language of aConvText (if the latter one was found) // used for chinese translation LanguageType nConvTargetLang; // target language of text to be changed const Font *pTargetFont; // target font of text to be changed // explicitly enables or disables application of the above two sal_Bool bAllowImplicitChangesForNotConvertibleText; SwConversionArgs( LanguageType nLang, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), nConvSrcLang( nLang ), nConvTextLang( LANGUAGE_NONE ), nConvTargetLang( LANGUAGE_NONE ), pTargetFont( NULL ), bAllowImplicitChangesForNotConvertibleText( sal_False ) {} }; /************************************************************************* * struct SwSpellArgs *************************************************************************/ struct SwSpellArgs : SwArgsBase { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpeller; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > xSpellAlt; SwSpellArgs(::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &rxSplChk, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), xSpeller( rxSplChk ) {} }; /************************************************************************* * class SwInterHyphInfo *************************************************************************/ // Parameter-Klasse fuer Hyphenate // docedt.cxx: SwDoc::Hyphenate() // txtedt.cxx: SwTxtNode::Hyphenate() // txthyph.cxx: SwTxtFrm::Hyphenate() class SwInterHyphInfo { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > xHyphWord; const Point aCrsrPos; sal_Bool bAuto : 1; sal_Bool bNoLang : 1; sal_Bool bCheck : 1; public: xub_StrLen nStart; xub_StrLen nLen; xub_StrLen nWordStart; xub_StrLen nWordLen; xub_StrLen nHyphPos; sal_uInt16 nMinTrail; inline SwInterHyphInfo( const Point &rCrsrPos, const sal_uInt16 nStartPos = 0, const sal_uInt16 nLength = USHRT_MAX ) : aCrsrPos( rCrsrPos ), bAuto(sal_False), bNoLang(sal_False), bCheck(sal_False), nStart(nStartPos), nLen(nLength), nWordStart(0), nWordLen(0), nHyphPos(0), nMinTrail(0) { } inline xub_StrLen GetEnd() const { return STRING_LEN == nLen ? nLen : nStart + nLen; } inline const Point *GetCrsrPos() const { return aCrsrPos.X() || aCrsrPos.Y() ? &aCrsrPos : 0; } inline sal_Bool IsCheck() const { return bCheck; } inline void SetCheck( const sal_Bool bNew ) { bCheck = bNew; } inline void SetNoLang( const sal_Bool bNew ) { bNoLang = bNew; } inline void SetHyphWord(const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > &rxHW) { xHyphWord = rxHW; } inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > GetHyphWord() { return xHyphWord; } }; #endif <commit_msg>INTEGRATION: CWS tl55 (1.7.50); FILE MERGED 2008/06/26 14:19:58 os 1.7.50.1: i85999 interactive grammar checking<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: splargs.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SPLARGS_HXX #define _SPLARGS_HXX #include <i18npool/lang.h> #include <tools/solar.h> #include <tools/gen.hxx> #include <limits.h> // USHRT_MAX #include <tools/string.hxx> class SwTxtNode; class SwIndex; class SpellCheck; class Font; #include <com/sun/star/linguistic2/XSpellAlternatives.hpp> #include <com/sun/star/linguistic2/XSpellChecker1.hpp> #include <com/sun/star/linguistic2/XHyphenatedWord.hpp> /************************************************************************* * struct SwArgsBase *************************************************************************/ struct SwArgsBase // used for text conversion (Hangul/Hanja, ...) { SwTxtNode *pStartNode; SwIndex *pStartIdx; SwTxtNode *pEndNode; SwIndex *pEndIdx; SwArgsBase( SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : pStartNode( pStart ), pStartIdx( &rStart ), pEndNode( pEnd ), pEndIdx( &rEnd ) {} void SetStart(SwTxtNode* pStart, SwIndex& rStart ) { pStartNode = pStart; pStartIdx = &rStart ; } void SetEnd( SwTxtNode* pEnd, SwIndex& rEnd ) { pEndNode = pEnd; pEndIdx = &rEnd ; } }; /************************************************************************* * struct SwConversionArgs * used for text conversion (Hangul/Hanja, Simplified/Traditional Chinese, ...) *************************************************************************/ struct SwConversionArgs : SwArgsBase { rtl::OUString aConvText; // convertible text found LanguageType nConvSrcLang; // (source) language to look for LanguageType nConvTextLang; // language of aConvText (if the latter one was found) // used for chinese translation LanguageType nConvTargetLang; // target language of text to be changed const Font *pTargetFont; // target font of text to be changed // explicitly enables or disables application of the above two sal_Bool bAllowImplicitChangesForNotConvertibleText; SwConversionArgs( LanguageType nLang, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), nConvSrcLang( nLang ), nConvTextLang( LANGUAGE_NONE ), nConvTargetLang( LANGUAGE_NONE ), pTargetFont( NULL ), bAllowImplicitChangesForNotConvertibleText( sal_False ) {} }; /************************************************************************* * struct SwSpellArgs *************************************************************************/ struct SwSpellArgs : SwArgsBase { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpeller; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > xSpellAlt; bool bIsGrammarCheck; SwSpellArgs(::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &rxSplChk, SwTxtNode* pStart, SwIndex& rStart, SwTxtNode* pEnd, SwIndex& rEnd, bool bGrammar ) : SwArgsBase( pStart, rStart, pEnd, rEnd ), xSpeller( rxSplChk ), bIsGrammarCheck( bGrammar ) {} }; /************************************************************************* * class SwInterHyphInfo *************************************************************************/ // Parameter-Klasse fuer Hyphenate // docedt.cxx: SwDoc::Hyphenate() // txtedt.cxx: SwTxtNode::Hyphenate() // txthyph.cxx: SwTxtFrm::Hyphenate() class SwInterHyphInfo { ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > xHyphWord; const Point aCrsrPos; sal_Bool bAuto : 1; sal_Bool bNoLang : 1; sal_Bool bCheck : 1; public: xub_StrLen nStart; xub_StrLen nLen; xub_StrLen nWordStart; xub_StrLen nWordLen; xub_StrLen nHyphPos; sal_uInt16 nMinTrail; inline SwInterHyphInfo( const Point &rCrsrPos, const sal_uInt16 nStartPos = 0, const sal_uInt16 nLength = USHRT_MAX ) : aCrsrPos( rCrsrPos ), bAuto(sal_False), bNoLang(sal_False), bCheck(sal_False), nStart(nStartPos), nLen(nLength), nWordStart(0), nWordLen(0), nHyphPos(0), nMinTrail(0) { } inline xub_StrLen GetEnd() const { return STRING_LEN == nLen ? nLen : nStart + nLen; } inline const Point *GetCrsrPos() const { return aCrsrPos.X() || aCrsrPos.Y() ? &aCrsrPos : 0; } inline sal_Bool IsCheck() const { return bCheck; } inline void SetCheck( const sal_Bool bNew ) { bCheck = bNew; } inline void SetNoLang( const sal_Bool bNew ) { bNoLang = bNew; } inline void SetHyphWord(const ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > &rxHW) { xHyphWord = rxHW; } inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > GetHyphWord() { return xHyphWord; } }; #endif <|endoftext|>
<commit_before>/* Copyright (c) 2013-2015 Jeffrey Pfau * * 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/. */ #include "Display.h" #include "DisplayGL.h" #include "DisplayQt.h" using namespace QGBA; #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) Display::Driver Display::s_driver = Display::Driver::OPENGL; #else Display::Driver Display::s_driver = Display::Driver::QT; #endif Display* Display::create(QWidget* parent) { #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) QSurfaceFormat format; format.setSwapInterval(1); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); #endif switch (s_driver) { #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) case Driver::OPENGL: format.setVersion(3, 2); format.setProfile(QSurfaceFormat::CoreProfile); return new DisplayGL(format, parent); #endif #ifdef BUILD_GL case Driver::OPENGL1: format.setVersion(1, 4); return new DisplayGL(format, parent); #endif case Driver::QT: return new DisplayQt(parent); default: #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) return new DisplayGL(format, parent); #else return new DisplayQt(parent); #endif } } Display::Display(QWidget* parent) : QWidget(parent) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); connect(&m_mouseTimer, &QTimer::timeout, this, &Display::hideCursor); m_mouseTimer.setSingleShot(true); m_mouseTimer.setInterval(MOUSE_DISAPPEAR_TIMER); setMouseTracking(true); } void Display::resizeEvent(QResizeEvent*) { m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio()); } void Display::lockAspectRatio(bool lock) { m_lockAspectRatio = lock; m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio()); } void Display::lockIntegerScaling(bool lock) { m_lockIntegerScaling = lock; } void Display::interframeBlending(bool lock) { m_interframeBlending = lock; } void Display::showOSDMessages(bool enable) { m_showOSD = enable; } void Display::filter(bool filter) { m_filter = filter; } void Display::showMessage(const QString& message) { m_messagePainter.showMessage(message); if (!isDrawing()) { forceDraw(); } } void Display::mouseMoveEvent(QMouseEvent*) { emit showCursor(); m_mouseTimer.stop(); m_mouseTimer.start(); } <commit_msg>Qt: Try GLES 3.0 if using GLES<commit_after>/* Copyright (c) 2013-2015 Jeffrey Pfau * * 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/. */ #include "Display.h" #include "DisplayGL.h" #include "DisplayQt.h" using namespace QGBA; #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) Display::Driver Display::s_driver = Display::Driver::OPENGL; #else Display::Driver Display::s_driver = Display::Driver::QT; #endif Display* Display::create(QWidget* parent) { #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) QSurfaceFormat format; format.setSwapInterval(1); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); #endif switch (s_driver) { #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) case Driver::OPENGL: if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES) { format.setVersion(3, 0); } else { format.setVersion(3, 2); } format.setProfile(QSurfaceFormat::CoreProfile); return new DisplayGL(format, parent); #endif #ifdef BUILD_GL case Driver::OPENGL1: format.setVersion(1, 4); return new DisplayGL(format, parent); #endif case Driver::QT: return new DisplayQt(parent); default: #if defined(BUILD_GL) || defined(BUILD_GLES2) || defined(USE_EPOXY) return new DisplayGL(format, parent); #else return new DisplayQt(parent); #endif } } Display::Display(QWidget* parent) : QWidget(parent) { setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); connect(&m_mouseTimer, &QTimer::timeout, this, &Display::hideCursor); m_mouseTimer.setSingleShot(true); m_mouseTimer.setInterval(MOUSE_DISAPPEAR_TIMER); setMouseTracking(true); } void Display::resizeEvent(QResizeEvent*) { m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio()); } void Display::lockAspectRatio(bool lock) { m_lockAspectRatio = lock; m_messagePainter.resize(size(), m_lockAspectRatio, devicePixelRatio()); } void Display::lockIntegerScaling(bool lock) { m_lockIntegerScaling = lock; } void Display::interframeBlending(bool lock) { m_interframeBlending = lock; } void Display::showOSDMessages(bool enable) { m_showOSD = enable; } void Display::filter(bool filter) { m_filter = filter; } void Display::showMessage(const QString& message) { m_messagePainter.showMessage(message); if (!isDrawing()) { forceDraw(); } } void Display::mouseMoveEvent(QMouseEvent*) { emit showCursor(); m_mouseTimer.stop(); m_mouseTimer.start(); } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ // Command line was: qdbusxml2cpp -c MApplicationIfProxy -p mapplicationifproxy.h:mapplicationifproxy.cpp com.nokia.MApplicationIf.xml #include "mapplicationifproxy.h" MApplicationIfProxy::MApplicationIfProxy(const QString &service, QObject *parent) : QDBusAbstractInterface(service, "/org/maemo/m", "com.nokia.MApplicationIf", QDBusConnection::sessionBus(), parent) { } MApplicationIfProxy::~MApplicationIfProxy() { } QDBusPendingReply<> MApplicationIfProxy::close() { return asyncCall(QLatin1String("close")); } QDBusPendingReply<> MApplicationIfProxy::exit() { return asyncCall(QLatin1String("exit")); } QDBusPendingReply<> MApplicationIfProxy::launch() { return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), QList<QVariant>()); } QDBusPendingReply<> MApplicationIfProxy::launch(const QStringList &parameters) { QList<QVariant> argumentList; argumentList << qVariantFromValue(parameters); return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), argumentList); } <commit_msg>Fixes: NB#143963 - some duiapplicationservice if methods should not cause application to launch<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ // Command line was: qdbusxml2cpp -c MApplicationIfProxy -p mapplicationifproxy.h:mapplicationifproxy.cpp com.nokia.MApplicationIf.xml #include "mapplicationifproxy.h" MApplicationIfProxy::MApplicationIfProxy(const QString &service, QObject *parent) : QDBusAbstractInterface(service, "/org/maemo/m", "com.nokia.MApplicationIf", QDBusConnection::sessionBus(), parent) { } MApplicationIfProxy::~MApplicationIfProxy() { } QDBusPendingReply<> MApplicationIfProxy::close() { return asyncCall(QLatin1String("close")); } QDBusPendingReply<> MApplicationIfProxy::exit() { // here we only do the dbus call, when the interface is valid, // i.e. there is a program listening "on the other side" of the // dbus connection. if ( isValid() ) { return asyncCall(QLatin1String("exit")); } else { return QDBusPendingReply<>(); } } QDBusPendingReply<> MApplicationIfProxy::launch() { return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), QList<QVariant>()); } QDBusPendingReply<> MApplicationIfProxy::launch(const QStringList &parameters) { QList<QVariant> argumentList; argumentList << qVariantFromValue(parameters); return callWithArgumentList(QDBus::BlockWithGui, QLatin1String("launch"), argumentList); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: simpleioerrorrequest.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kso $ $Date: 2001-06-19 09:18:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_UCB_INTERACTIVEAUGMENTEDIOEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp> #endif #ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX #include <ucbhelper/simpleioerrorrequest.hxx> #endif using namespace com::sun::star; using namespace ucbhelper; //========================================================================= SimpleIOErrorRequest::SimpleIOErrorRequest( const ucb::IOErrorCode eError, const uno::Sequence< uno::Any > & rArgs, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) { // Fill request... ucb::InteractiveAugmentedIOException aRequest; aRequest.Message = rMessage; aRequest.Context = xContext; aRequest.Classification = task::InteractionClassification_ERROR; aRequest.Code = eError; aRequest.Arguments = rArgs; setRequest( uno::makeAny( aRequest ) ); // Fill continuations... uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations( 1 ); aContinuations[ 0 ] = new InteractionAbort( this ); setContinuations( aContinuations ); } <commit_msg>INTEGRATION: CWS ooo19126 (1.6.170); FILE MERGED 2005/09/05 13:14:03 rt 1.6.170.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: simpleioerrorrequest.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-09 16:42:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_UCB_INTERACTIVEAUGMENTEDIOEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp> #endif #ifndef _UCBHELPER_SIMPLEIOERRORREQUEST_HXX #include <ucbhelper/simpleioerrorrequest.hxx> #endif using namespace com::sun::star; using namespace ucbhelper; //========================================================================= SimpleIOErrorRequest::SimpleIOErrorRequest( const ucb::IOErrorCode eError, const uno::Sequence< uno::Any > & rArgs, const rtl::OUString & rMessage, const uno::Reference< ucb::XCommandProcessor > & xContext ) { // Fill request... ucb::InteractiveAugmentedIOException aRequest; aRequest.Message = rMessage; aRequest.Context = xContext; aRequest.Classification = task::InteractionClassification_ERROR; aRequest.Code = eError; aRequest.Arguments = rArgs; setRequest( uno::makeAny( aRequest ) ); // Fill continuations... uno::Sequence< uno::Reference< task::XInteractionContinuation > > aContinuations( 1 ); aContinuations[ 0 ] = new InteractionAbort( this ); setContinuations( aContinuations ); } <|endoftext|>
<commit_before>#include "idt.hpp" #include <kernel/events.hpp> #include <kernel/syscalls.hpp> #include <kprint> #include <info> #define RING0_CODE_SEG 0x8 extern "C" { extern void unused_interrupt_handler(); extern void modern_interrupt_handler(); extern void spurious_intr(); extern void cpu_enable_panicking(); } #define IRQ_LINES Events::NUM_EVENTS #define INTR_LINES (IRQ_BASE + IRQ_LINES) namespace x86 { typedef void (*intr_handler_t)(); typedef void (*except_handler_t)(); struct x86_IDT { IDTDescr entry[INTR_LINES] __attribute__((aligned(16))); intr_handler_t get_handler(uint8_t vec); void set_handler(uint8_t, intr_handler_t); void set_exception_handler(uint8_t, except_handler_t); void init(); }; static std::array<x86_IDT, SMP_MAX_CORES> idt; void idt_initialize_for_cpu(int cpu) { idt.at(cpu).init(); } // A union to be able to extract the lower and upper part of an address union addr_union { uintptr_t whole; struct { uint16_t lo16; uint16_t hi16; #ifdef ARCH_x86_64 uint32_t top32; #endif }; }; static void set_intr_entry( IDTDescr* idt_entry, intr_handler_t func, uint8_t ist, uint16_t segment_sel, char attributes) { addr_union addr; addr.whole = (uintptr_t) func; idt_entry->offset_1 = addr.lo16; idt_entry->offset_2 = addr.hi16; #ifdef ARCH_x86_64 idt_entry->offset_3 = addr.top32; #endif idt_entry->selector = segment_sel; idt_entry->type_attr = attributes; #ifdef ARCH_x86_64 idt_entry->ist = ist; idt_entry->zero2 = 0; #else (void) ist; idt_entry->zero = 0; #endif } intr_handler_t x86_IDT::get_handler(uint8_t vec) { addr_union addr; addr.lo16 = entry[vec].offset_1; addr.hi16 = entry[vec].offset_2; #ifdef ARCH_x86_64 addr.top32 = entry[vec].offset_3; #endif return (intr_handler_t) addr.whole; } void x86_IDT::set_handler(uint8_t vec, intr_handler_t func) { set_intr_entry(&entry[vec], func, 1, RING0_CODE_SEG, 0x8e); } void x86_IDT::set_exception_handler(uint8_t vec, except_handler_t func) { set_intr_entry(&entry[vec], (intr_handler_t) func, 2, RING0_CODE_SEG, 0x8e); } extern "C" { void __cpu_except_0(); void __cpu_except_1(); void __cpu_except_2(); void __cpu_except_3(); void __cpu_except_4(); void __cpu_except_5(); void __cpu_except_6(); void __cpu_except_7(); void __cpu_except_8(); void __cpu_except_9(); void __cpu_except_10(); void __cpu_except_11(); void __cpu_except_12(); void __cpu_except_13(); void __cpu_except_14(); void __cpu_except_15(); void __cpu_except_16(); void __cpu_except_17(); void __cpu_except_18(); void __cpu_except_19(); void __cpu_except_20(); void __cpu_except_30(); } void x86_IDT::init() { // make sure its all zeroes memset(&PER_CPU(idt).entry, 0, sizeof(x86_IDT::entry)); set_exception_handler(0, __cpu_except_0); set_exception_handler(1, __cpu_except_1); set_exception_handler(2, __cpu_except_2); set_exception_handler(3, __cpu_except_3); set_exception_handler(4, __cpu_except_4); set_exception_handler(5, __cpu_except_5); set_exception_handler(6, __cpu_except_6); set_exception_handler(7, __cpu_except_7); set_exception_handler(8, __cpu_except_8); set_exception_handler(9, __cpu_except_9); set_exception_handler(10, __cpu_except_10); set_exception_handler(11, __cpu_except_11); set_exception_handler(12, __cpu_except_12); set_exception_handler(13, __cpu_except_13); set_exception_handler(14, __cpu_except_14); set_exception_handler(15, __cpu_except_15); set_exception_handler(16, __cpu_except_16); set_exception_handler(17, __cpu_except_17); set_exception_handler(18, __cpu_except_18); set_exception_handler(19, __cpu_except_19); set_exception_handler(20, __cpu_except_20); set_exception_handler(30, __cpu_except_30); for (size_t i = 32; i < INTR_LINES - 2; i++) { set_handler(i, unused_interrupt_handler); } // spurious interrupt handler set_handler(INTR_LINES - 1, spurious_intr); // Load IDT IDTR idt_reg; idt_reg.limit = INTR_LINES * sizeof(IDTDescr) - 1; idt_reg.base = (uintptr_t) &entry[0]; asm volatile ("lidt %0" : : "m"(idt_reg)); } } // x86 void __arch_subscribe_irq(uint8_t irq) { assert(irq < IRQ_LINES); PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, modern_interrupt_handler); } void __arch_install_irq(uint8_t irq, x86::intr_handler_t handler) { assert(irq < IRQ_LINES); PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, handler); } void __arch_unsubscribe_irq(uint8_t irq) { assert(irq < IRQ_LINES); PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, unused_interrupt_handler); } /// CPU EXCEPTIONS /// #define PAGE_FAULT 14 static const char* exception_names[] = { "Divide-by-zero Error", "Debug", "Non-maskable Interrupt", "Breakpoint", "Overflow", "Bound Range Exceeded", "Invalid Opcode", "Device Not Available", "Double Fault", "Reserved", "Invalid TSS", "Segment Not Present", "Stack-Segment Fault", "General Protection Fault", "Page Fault", "Reserved", "x87 Floating-point Exception", "Alignment Check", "Machine Check", "SIMD Floating-point Exception", "Virtualization Exception", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Security Exception", "Reserved" }; void __cpu_dump_regs(uintptr_t* regs) { #if defined(ARCH_x86_64) # define RIP_REG 16 // AMD64 CPU registers struct desc_table_t { uint16_t limit; uintptr_t location; } __attribute__((packed)) gdt, idt; asm ("sgdtq %0" : : "m" (* &gdt)); asm ("sidtq %0" : : "m" (* &idt)); fprintf(stderr, "\n"); printf(" RAX: %016lx R 8: %016lx\n", regs[0], regs[5]); printf(" RBX: %016lx R 9: %016lx\n", regs[1], regs[6]); printf(" RCX: %016lx R10: %016lx\n", regs[2], regs[7]); printf(" RDX: %016lx R11: %016lx\n", regs[3], regs[8]); fprintf(stderr, "\n"); printf(" RBP: %016lx R12: %016lx\n", regs[4], regs[9]); printf(" RSP: %016lx R13: %016lx\n", regs[13], regs[10]); printf(" RSI: %016lx R14: %016lx\n", regs[14], regs[11]); printf(" RDI: %016lx R15: %016lx\n", regs[15], regs[12]); printf(" RIP: %016lx FLA: %016lx\n", regs[16], regs[17]); fprintf(stderr, "\n"); printf(" CR0: %016lx CR4: %016lx\n", regs[18], regs[22]); printf(" CR1: %016lx CR8: %016lx\n", regs[19], regs[23]); printf(" CR2: %016lx GDT: %016lx (%u)\n", regs[20], gdt.location, gdt.limit); printf(" CR3: %016lx IDT: %016lx (%u)\n", regs[21], idt.location, idt.limit); #elif defined(ARCH_i686) # define RIP_REG 8 // i386 CPU registers fprintf(stderr, "\n"); printf(" EAX: %08x EBP: %08x\n", regs[0], regs[4]); printf(" EBX: %08x ESP: %08x\n", regs[1], regs[5]); printf(" ECX: %08x ESI: %08x\n", regs[2], regs[6]); printf(" EDX: %08x EDI: %08x\n", regs[3], regs[7]); fprintf(stderr, "\n"); printf(" EIP: %08x EFL: %08x\n", regs[8], regs[9]); #else #error "Unknown architecture" #endif fprintf(stderr, "\n"); } extern "C" void double_fault(const char*); void __page_fault(uintptr_t* regs, uint32_t code) { const char* reason = "Protection violation"; if (not(code & 1)) reason = "Page not present"; kprintf("%s, trying to access 0x%lx\n", reason, regs[20]); if (code & 2) kprintf("Page write failed.\n"); else kprintf("Page read failed.\n"); if (code & 4) kprintf("Privileged page access from user space.\n"); if (code & 8) kprintf("Found bit set in reserved field.\n"); if (code & 16) kprintf("Instruction fetch. XD\n"); if (code & 32) kprintf("Protection key violation.\n"); if (code & 0x8000) kprintf("SGX access violation.\n"); } extern "C" __attribute__((noreturn optnone, weak)) void __cpu_exception(uintptr_t* regs, int error, uint32_t code) { cpu_enable_panicking(); SMP::global_lock(); kprintf("\n>>>> !!! CPU %u EXCEPTION !!! <<<<\n", SMP::cpu_id()); kprintf("%s (%d) EIP %p CODE %#x\n", exception_names[error], error, (void*) regs[RIP_REG], code); if (error == PAGE_FAULT) { __page_fault(regs, code); } __cpu_dump_regs(regs); SMP::global_unlock(); // error message: char buffer[64]; snprintf(buffer, sizeof(buffer), "%s (%d)", exception_names[error], error); // normal CPU exception if (error != 0x8) { // call panic, which will decide what to do next panic(buffer); } else { // handle double faults differently double_fault(buffer); } __builtin_unreachable(); } <commit_msg>x86: Remove optnone from IDT/__cpu_exception<commit_after>#include "idt.hpp" #include <kernel/events.hpp> #include <kernel/syscalls.hpp> #include <kprint> #include <info> #define RING0_CODE_SEG 0x8 extern "C" { extern void unused_interrupt_handler(); extern void modern_interrupt_handler(); extern void spurious_intr(); extern void cpu_enable_panicking(); } #define IRQ_LINES Events::NUM_EVENTS #define INTR_LINES (IRQ_BASE + IRQ_LINES) namespace x86 { typedef void (*intr_handler_t)(); typedef void (*except_handler_t)(); struct x86_IDT { IDTDescr entry[INTR_LINES] __attribute__((aligned(16))); intr_handler_t get_handler(uint8_t vec); void set_handler(uint8_t, intr_handler_t); void set_exception_handler(uint8_t, except_handler_t); void init(); }; static std::array<x86_IDT, SMP_MAX_CORES> idt; void idt_initialize_for_cpu(int cpu) { idt.at(cpu).init(); } // A union to be able to extract the lower and upper part of an address union addr_union { uintptr_t whole; struct { uint16_t lo16; uint16_t hi16; #ifdef ARCH_x86_64 uint32_t top32; #endif }; }; static void set_intr_entry( IDTDescr* idt_entry, intr_handler_t func, uint8_t ist, uint16_t segment_sel, char attributes) { addr_union addr; addr.whole = (uintptr_t) func; idt_entry->offset_1 = addr.lo16; idt_entry->offset_2 = addr.hi16; #ifdef ARCH_x86_64 idt_entry->offset_3 = addr.top32; #endif idt_entry->selector = segment_sel; idt_entry->type_attr = attributes; #ifdef ARCH_x86_64 idt_entry->ist = ist; idt_entry->zero2 = 0; #else (void) ist; idt_entry->zero = 0; #endif } intr_handler_t x86_IDT::get_handler(uint8_t vec) { addr_union addr; addr.lo16 = entry[vec].offset_1; addr.hi16 = entry[vec].offset_2; #ifdef ARCH_x86_64 addr.top32 = entry[vec].offset_3; #endif return (intr_handler_t) addr.whole; } void x86_IDT::set_handler(uint8_t vec, intr_handler_t func) { set_intr_entry(&entry[vec], func, 1, RING0_CODE_SEG, 0x8e); } void x86_IDT::set_exception_handler(uint8_t vec, except_handler_t func) { set_intr_entry(&entry[vec], (intr_handler_t) func, 2, RING0_CODE_SEG, 0x8e); } extern "C" { void __cpu_except_0(); void __cpu_except_1(); void __cpu_except_2(); void __cpu_except_3(); void __cpu_except_4(); void __cpu_except_5(); void __cpu_except_6(); void __cpu_except_7(); void __cpu_except_8(); void __cpu_except_9(); void __cpu_except_10(); void __cpu_except_11(); void __cpu_except_12(); void __cpu_except_13(); void __cpu_except_14(); void __cpu_except_15(); void __cpu_except_16(); void __cpu_except_17(); void __cpu_except_18(); void __cpu_except_19(); void __cpu_except_20(); void __cpu_except_30(); } void x86_IDT::init() { // make sure its all zeroes memset(&PER_CPU(idt).entry, 0, sizeof(x86_IDT::entry)); set_exception_handler(0, __cpu_except_0); set_exception_handler(1, __cpu_except_1); set_exception_handler(2, __cpu_except_2); set_exception_handler(3, __cpu_except_3); set_exception_handler(4, __cpu_except_4); set_exception_handler(5, __cpu_except_5); set_exception_handler(6, __cpu_except_6); set_exception_handler(7, __cpu_except_7); set_exception_handler(8, __cpu_except_8); set_exception_handler(9, __cpu_except_9); set_exception_handler(10, __cpu_except_10); set_exception_handler(11, __cpu_except_11); set_exception_handler(12, __cpu_except_12); set_exception_handler(13, __cpu_except_13); set_exception_handler(14, __cpu_except_14); set_exception_handler(15, __cpu_except_15); set_exception_handler(16, __cpu_except_16); set_exception_handler(17, __cpu_except_17); set_exception_handler(18, __cpu_except_18); set_exception_handler(19, __cpu_except_19); set_exception_handler(20, __cpu_except_20); set_exception_handler(30, __cpu_except_30); for (size_t i = 32; i < INTR_LINES - 2; i++) { set_handler(i, unused_interrupt_handler); } // spurious interrupt handler set_handler(INTR_LINES - 1, spurious_intr); // Load IDT IDTR idt_reg; idt_reg.limit = INTR_LINES * sizeof(IDTDescr) - 1; idt_reg.base = (uintptr_t) &entry[0]; asm volatile ("lidt %0" : : "m"(idt_reg)); } } // x86 void __arch_subscribe_irq(uint8_t irq) { assert(irq < IRQ_LINES); PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, modern_interrupt_handler); } void __arch_install_irq(uint8_t irq, x86::intr_handler_t handler) { assert(irq < IRQ_LINES); PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, handler); } void __arch_unsubscribe_irq(uint8_t irq) { assert(irq < IRQ_LINES); PER_CPU(x86::idt).set_handler(IRQ_BASE + irq, unused_interrupt_handler); } /// CPU EXCEPTIONS /// #define PAGE_FAULT 14 static const char* exception_names[] = { "Divide-by-zero Error", "Debug", "Non-maskable Interrupt", "Breakpoint", "Overflow", "Bound Range Exceeded", "Invalid Opcode", "Device Not Available", "Double Fault", "Reserved", "Invalid TSS", "Segment Not Present", "Stack-Segment Fault", "General Protection Fault", "Page Fault", "Reserved", "x87 Floating-point Exception", "Alignment Check", "Machine Check", "SIMD Floating-point Exception", "Virtualization Exception", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Security Exception", "Reserved" }; void __cpu_dump_regs(uintptr_t* regs) { #if defined(ARCH_x86_64) # define RIP_REG 16 // AMD64 CPU registers struct desc_table_t { uint16_t limit; uintptr_t location; } __attribute__((packed)) gdt, idt; asm ("sgdtq %0" : : "m" (* &gdt)); asm ("sidtq %0" : : "m" (* &idt)); fprintf(stderr, "\n"); printf(" RAX: %016lx R 8: %016lx\n", regs[0], regs[5]); printf(" RBX: %016lx R 9: %016lx\n", regs[1], regs[6]); printf(" RCX: %016lx R10: %016lx\n", regs[2], regs[7]); printf(" RDX: %016lx R11: %016lx\n", regs[3], regs[8]); fprintf(stderr, "\n"); printf(" RBP: %016lx R12: %016lx\n", regs[4], regs[9]); printf(" RSP: %016lx R13: %016lx\n", regs[13], regs[10]); printf(" RSI: %016lx R14: %016lx\n", regs[14], regs[11]); printf(" RDI: %016lx R15: %016lx\n", regs[15], regs[12]); printf(" RIP: %016lx FLA: %016lx\n", regs[16], regs[17]); fprintf(stderr, "\n"); printf(" CR0: %016lx CR4: %016lx\n", regs[18], regs[22]); printf(" CR1: %016lx CR8: %016lx\n", regs[19], regs[23]); printf(" CR2: %016lx GDT: %016lx (%u)\n", regs[20], gdt.location, gdt.limit); printf(" CR3: %016lx IDT: %016lx (%u)\n", regs[21], idt.location, idt.limit); #elif defined(ARCH_i686) # define RIP_REG 8 // i386 CPU registers fprintf(stderr, "\n"); printf(" EAX: %08x EBP: %08x\n", regs[0], regs[4]); printf(" EBX: %08x ESP: %08x\n", regs[1], regs[5]); printf(" ECX: %08x ESI: %08x\n", regs[2], regs[6]); printf(" EDX: %08x EDI: %08x\n", regs[3], regs[7]); fprintf(stderr, "\n"); printf(" EIP: %08x EFL: %08x\n", regs[8], regs[9]); #else #error "Unknown architecture" #endif fprintf(stderr, "\n"); } extern "C" void double_fault(const char*); void __page_fault(uintptr_t* regs, uint32_t code) { const char* reason = "Protection violation"; if (not(code & 1)) reason = "Page not present"; kprintf("%s, trying to access 0x%lx\n", reason, regs[20]); if (code & 2) kprintf("Page write failed.\n"); else kprintf("Page read failed.\n"); if (code & 4) kprintf("Privileged page access from user space.\n"); if (code & 8) kprintf("Found bit set in reserved field.\n"); if (code & 16) kprintf("Instruction fetch. XD\n"); if (code & 32) kprintf("Protection key violation.\n"); if (code & 0x8000) kprintf("SGX access violation.\n"); } extern "C" __attribute__((noreturn, weak)) void __cpu_exception(uintptr_t* regs, int error, uint32_t code) { cpu_enable_panicking(); SMP::global_lock(); kprintf("\n>>>> !!! CPU %u EXCEPTION !!! <<<<\n", SMP::cpu_id()); kprintf("%s (%d) EIP %p CODE %#x\n", exception_names[error], error, (void*) regs[RIP_REG], code); if (error == PAGE_FAULT) { __page_fault(regs, code); } __cpu_dump_regs(regs); SMP::global_unlock(); // error message: char buffer[64]; snprintf(buffer, sizeof(buffer), "%s (%d)", exception_names[error], error); // normal CPU exception if (error != 0x8) { // call panic, which will decide what to do next panic(buffer); } else { // handle double faults differently double_fault(buffer); } __builtin_unreachable(); } <|endoftext|>
<commit_before>/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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. */ /** * @file AppEscape_T6.cpp * @brief Contains the definition function main() for the Escape T6 * application. * $Id$ */ // This application #include "Escape_T6Model.h" #include "Escape_T6Controller.h" // This library #include "core/terrain/tgHillyGround.h" #include "core/tgModel.h" #include "core/tgSimViewGraphics.h" #include "core/tgSimulation.h" #include "core/tgWorld.h" // Bullet Physics #include "LinearMath/btVector3.h" // The C++ Standard Library #include <iostream> tgHillyGround *createGround(); tgWorld *createWorld(); tgSimViewGraphics *createGraphicsView(tgWorld *world); tgSimView *createView(tgWorld *world); void simulate(tgSimulation *simulation); /** * Runs a series of episodes. * Each episode tests a given control pattern for a given number of steps. * The fitness function (reward metric) for this experiment is * the maximum distance from the tensegrity's starting point * at any point during the episode * NB: Running episodes and using graphics are mutually exclusive features */ int main(int argc, char** argv) { std::cout << "AppEscape_T6" << std::endl; // First create the world tgWorld *world = createWorld(); // Second create the view //tgSimViewGraphics *view = createGraphicsView(world); // For visual experimenting on one tensegrity tgSimView *view = createView(world); // For running multiple episodes // Third create the simulation tgSimulation *simulation = new tgSimulation(*view); // Fourth create the models with their controllers and add the models to the simulation Escape_T6Model* const model = new Escape_T6Model(); // Fifth create controller and attach it to the model double initialLength = 9; // decimeters Escape_T6Controller* const controller = new Escape_T6Controller(initialLength); model->attach(controller); //Sixth add model (with controller) to simulation simulation->addModel(model); simulate(simulation); //Teardown is handled by delete, so that should be automatic return 0; } tgHillyGround *createGround() { // Determine the angle of the ground in radians. All 0 is flat const double yaw = 0.0; const double pitch = 0.0; const double roll = 0.0; const tgHillyGround::Config groundConfig(btVector3(yaw, pitch, roll)); // the world will delete this return new tgHillyGround(groundConfig); } tgWorld *createWorld() { const tgWorld::Config config(98.1); // gravity, cm/sec^2 Use this to adjust length scale of world. // NB: by changing the setting below from 981 to 98.1, we've // scaled the world length scale to decimeters not cm. tgHillyGround* ground = createGround(); return new tgWorld(config, ground); } /** Use for displaying tensegrities in simulation */ tgSimViewGraphics *createGraphicsView(tgWorld *world) { const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate return new tgSimViewGraphics(*world, timestep_physics, timestep_graphics); } /** Use for trial episodes of many tensegrities in an experiment */ tgSimView *createView(tgWorld *world) { const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate return new tgSimView(*world, timestep_physics, timestep_graphics); } /** Run a series of episodes for nSteps each */ void simulate(tgSimulation *simulation) { int nEpisodes = 10; // Number of episodes ("trial runs") int nSteps = 60000; // Number of steps in each episode for (int i=0; i<nEpisodes; i++) { simulation->run(nSteps); simulation->reset(); } } <commit_msg>Added explicit arguments to tgHillyGround constructor call<commit_after>/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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. */ /** * @file AppEscape_T6.cpp * @brief Contains the definition function main() for the Escape T6 * application. * $Id$ */ // This application #include "Escape_T6Model.h" #include "Escape_T6Controller.h" // This library #include "core/terrain/tgHillyGround.h" #include "core/tgModel.h" #include "core/tgSimViewGraphics.h" #include "core/tgSimulation.h" #include "core/tgWorld.h" // Bullet Physics #include "LinearMath/btVector3.h" // The C++ Standard Library #include <iostream> tgHillyGround *createGround(); tgWorld *createWorld(); tgSimViewGraphics *createGraphicsView(tgWorld *world); tgSimView *createView(tgWorld *world); void simulate(tgSimulation *simulation); /** * Runs a series of episodes. * Each episode tests a given control pattern for a given number of steps. * The fitness function (reward metric) for this experiment is * the maximum distance from the tensegrity's starting point * at any point during the episode * NB: Running episodes and using graphics are mutually exclusive features */ int main(int argc, char** argv) { std::cout << "AppEscape_T6" << std::endl; // First create the world tgWorld *world = createWorld(); // Second create the view tgSimViewGraphics *view = createGraphicsView(world); // For visual experimenting on one tensegrity //tgSimView *view = createView(world); // For running multiple episodes // Third create the simulation tgSimulation *simulation = new tgSimulation(*view); // Fourth create the models with their controllers and add the models to the simulation Escape_T6Model* const model = new Escape_T6Model(); // Fifth create controller and attach it to the model double initialLength = 9; // decimeters Escape_T6Controller* const controller = new Escape_T6Controller(initialLength); model->attach(controller); //Sixth add model (with controller) to simulation simulation->addModel(model); simulate(simulation); //Teardown is handled by delete, so that should be automatic return 0; } tgHillyGround *createGround() { // Determine the angle of the ground in radians. All 0 is flat const double yaw = 0.0; const double pitch = 0.0; const double roll = 0.0; const btVector3 eulerAngles = btVector3(yaw, pitch, roll); // Default: (0.0, 0.0, 0.0) const double friction = 0.5; // Default: 0.5 const double restitution = 0.0; // Default: 0.0 const btVector3 size = btVector3(500.0, 1.5, 500.0); // Default: (500.0, 1.5, 500.0) const btVector3 origin = btVector3(0.0, 0.0, 0.0); // Default: (0.0, 0.0, 0.0) const size_t nx = 50; // Default: 50 const size_t ny = 50; // Default: 50 const double margin = 0.5; // Default: 0.5 const double triangleSize = 5.0; // Default: 5.0 const double waveHeight = 2.0; // Default: 5.0 const double offset = 0.5; // Default: 0.5 const tgHillyGround::Config groundConfig(eulerAngles, friction, restitution, size, origin, nx, ny, margin, triangleSize, waveHeight, offset); // the world will delete this return new tgHillyGround(groundConfig); } tgWorld *createWorld() { const tgWorld::Config config(98.1); // gravity, cm/sec^2 Use this to adjust length scale of world. // NB: by changing the setting below from 981 to 98.1, we've // scaled the world length scale to decimeters not cm. tgHillyGround* ground = createGround(); return new tgWorld(config, ground); } /** Use for displaying tensegrities in simulation */ tgSimViewGraphics *createGraphicsView(tgWorld *world) { const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate return new tgSimViewGraphics(*world, timestep_physics, timestep_graphics); } /** Use for trial episodes of many tensegrities in an experiment */ tgSimView *createView(tgWorld *world) { const double timestep_physics = 1.0 / 60.0 / 10.0; // Seconds const double timestep_graphics = 1.f /60.f; // Seconds, AKA render rate return new tgSimView(*world, timestep_physics, timestep_graphics); } /** Run a series of episodes for nSteps each */ void simulate(tgSimulation *simulation) { int nEpisodes = 10; // Number of episodes ("trial runs") int nSteps = 60000; // Number of steps in each episode for (int i=0; i<nEpisodes; i++) { simulation->run(nSteps); simulation->reset(); } } <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <unistd.h> #include "fnord-base/application.h" #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/random.h" #include "fnord-base/cli/flagparser.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-tsdb/TSDBClient.h" #include <sensord/SensorSampleFeed.h> #include <sensord/SensorPushServlet.h> using namespace fnord; int main(int argc, const char** argv) { Application::init(); Application::logToStderr(); cli::FlagParser flags; flags.defineFlag( "http", cli::FlagParser::T_INTEGER, false, NULL, "8000", "Start the http server on this port", "<port>"); flags.defineFlag( "tsdb", cli::FlagParser::T_STRING, false, NULL, NULL, "tsdb addr", "<host:port>"); flags.defineFlag( "loglevel", cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); thread::EventLoop evloop; thread::ThreadPool tp( std::unique_ptr<ExceptionHandler>( new CatchAndLogExceptionHandler("metricd"))); http::HTTPConnectionPool http(&evloop); tsdb::TSDBClient tsdb( StringUtil::format("http://$0/tsdb", flags.getString("tsdb")), &http); /* set up http server */ http::HTTPRouter http_router; http::HTTPServer http_server(&http_router, &evloop); http_server.listen(flags.getInt("http")); http_server.stats()->exportStats("/metricd/http"); sensord::SensorSampleFeed sensor_feed; metricdb::SensorServlet sensor_servlet(&sensor_feed); http_router.addRouteByPrefixMatch("/sensors", &sensor_servlet); //stats::StatsHTTPServlet stats_servlet; //http_router.addRouteByPrefixMatch("/stats", &stats_servlet); evloop.run(); return 0; } <commit_msg>SensorServlet -> SensorPushServlet<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <unistd.h> #include "fnord-base/application.h" #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/random.h" #include "fnord-base/cli/flagparser.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-tsdb/TSDBClient.h" #include <sensord/SensorSampleFeed.h> #include <sensord/SensorPushServlet.h> using namespace fnord; int main(int argc, const char** argv) { Application::init(); Application::logToStderr(); cli::FlagParser flags; flags.defineFlag( "http", cli::FlagParser::T_INTEGER, false, NULL, "8000", "Start the http server on this port", "<port>"); flags.defineFlag( "tsdb", cli::FlagParser::T_STRING, false, NULL, NULL, "tsdb addr", "<host:port>"); flags.defineFlag( "loglevel", cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); thread::EventLoop evloop; thread::ThreadPool tp( std::unique_ptr<ExceptionHandler>( new CatchAndLogExceptionHandler("metricd"))); http::HTTPConnectionPool http(&evloop); tsdb::TSDBClient tsdb( StringUtil::format("http://$0/tsdb", flags.getString("tsdb")), &http); /* set up http server */ http::HTTPRouter http_router; http::HTTPServer http_server(&http_router, &evloop); http_server.listen(flags.getInt("http")); http_server.stats()->exportStats("/metricd/http"); sensord::SensorSampleFeed sensor_feed; metricdb::SensorPushServlet sensor_servlet(&sensor_feed); http_router.addRouteByPrefixMatch("/sensors", &sensor_servlet); //stats::StatsHTTPServlet stats_servlet; //http_router.addRouteByPrefixMatch("/stats", &stats_servlet); evloop.run(); return 0; } <|endoftext|>
<commit_before>#include "path/ASPC.h" using namespace std; namespace chr { namespace path { array<float, 256> ASPC::randomBase; bool ASPC::randomBaseGenerated = false; ASPC::ASPC(vector<glm::vec2> &&polyline) : polyline(polyline) {} void ASPC::begin() { polyline.clear(); if (!randomBaseGenerated) { srand(1); for (int i = 0; i < randomBase.size(); i++) { randomBase[i] = rand() / float(RAND_MAX); } randomBaseGenerated = true; } randomIndex = 0; } float ASPC::nextRandom() { return randomBase[(randomIndex++) % randomBase.size()]; } void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2) { in[0] = p0; in[1] = p1; in[2] = p2; float pt = 0; auto p = gamma(pt, in.data()); float qt = 1; auto q = gamma(qt, in.data()); sample(pt, p, qt, q); } void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2, const glm::vec2 &p3) { in[0] = p0; in[1] = p1; in[2] = p2; in[3] = p3; float pt = 0; auto p = gamma(pt, in.data()); float qt = 1; auto q = gamma(qt, in.data()); sample(pt, p, qt, q); } void ASPC::sample(float t0, const glm::vec2 &p0, float t1, const glm::vec2 &p1) { float t = 0.45f + 0.1f * nextRandom(); float rt = t0 + t * (t1 - t0); auto r = gamma(rt, in.data()); float cross = (p0.x - r.x) * (p1.y - r.y) - (p1.x - r.x) * (p0.y - r.y); if (cross * cross < samplingTolerance) { polyline.push_back(p0); } else { sample(t0, p0, rt, r); sample(rt, r, t1, p1); } } } } <commit_msg>FIXING INCLUDES FOR EMSCRIPTEN<commit_after>#include "path/ASPC.h" #include <cstdlib> using namespace std; namespace chr { namespace path { array<float, 256> ASPC::randomBase; bool ASPC::randomBaseGenerated = false; ASPC::ASPC(vector<glm::vec2> &&polyline) : polyline(polyline) {} void ASPC::begin() { polyline.clear(); if (!randomBaseGenerated) { srand(1); for (int i = 0; i < randomBase.size(); i++) { randomBase[i] = rand() / float(RAND_MAX); } randomBaseGenerated = true; } randomIndex = 0; } float ASPC::nextRandom() { return randomBase[(randomIndex++) % randomBase.size()]; } void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2) { in[0] = p0; in[1] = p1; in[2] = p2; float pt = 0; auto p = gamma(pt, in.data()); float qt = 1; auto q = gamma(qt, in.data()); sample(pt, p, qt, q); } void ASPC::segment(const glm::vec2 &p0, const glm::vec2 &p1, const glm::vec2 &p2, const glm::vec2 &p3) { in[0] = p0; in[1] = p1; in[2] = p2; in[3] = p3; float pt = 0; auto p = gamma(pt, in.data()); float qt = 1; auto q = gamma(qt, in.data()); sample(pt, p, qt, q); } void ASPC::sample(float t0, const glm::vec2 &p0, float t1, const glm::vec2 &p1) { float t = 0.45f + 0.1f * nextRandom(); float rt = t0 + t * (t1 - t0); auto r = gamma(rt, in.data()); float cross = (p0.x - r.x) * (p1.y - r.y) - (p1.x - r.x) * (p0.y - r.y); if (cross * cross < samplingTolerance) { polyline.push_back(p0); } else { sample(t0, p0, rt, r); sample(rt, r, t1, p1); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gdk/gdkkeysyms.h> #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/accelerators/accelerator.h" #include "ui/gfx/rect.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace views { class AcceleratorHandlerGtkTest : public testing::Test, public WidgetDelegate, public ui::AcceleratorTarget { public: AcceleratorHandlerGtkTest() : kMenuAccelerator(ui::VKEY_MENU, false, false, false), kHomepageAccelerator(ui::VKEY_HOME, false, false, true), content_view_(NULL) { } virtual void SetUp() { window_ = Widget::CreateWindowWithBounds(this, gfx::Rect(0, 0, 500, 500)); window_->Show(); FocusManager* focus_manager = window_->GetFocusManager(); focus_manager->RegisterAccelerator(kMenuAccelerator, this); focus_manager->RegisterAccelerator(kHomepageAccelerator, this); menu_pressed_ = false; home_pressed_ = false; } virtual void TearDown() { window_->Close(); // Flush the message loop to make application verifiers happy. message_loop_.RunAllPending(); } GdkEventKey CreateKeyEvent(GdkEventType type, guint keyval, guint state) { GdkEventKey evt; memset(&evt, 0, sizeof(evt)); evt.type = type; evt.keyval = keyval; // The keyval won't be a "correct" hardware keycode for any real hardware, // but the code should never depend on exact hardware keycodes, just the // fact that the code for presses and releases of the same key match. evt.hardware_keycode = keyval; evt.state = state; GtkWidget* widget = GTK_WIDGET(window_->GetNativeWindow()); evt.window = widget->window; return evt; } // AcceleratorTarget implementation. virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) { if (accelerator == kMenuAccelerator) menu_pressed_ = true; else if (accelerator == kHomepageAccelerator) home_pressed_ = true; return true; } virtual bool CanHandleAccelerators() const { return true; } // WidgetDelegate Implementation. virtual View* GetContentsView() { if (!content_view_) content_view_ = new View(); return content_view_; } virtual const views::Widget* GetWidget() const { return content_view_->GetWidget(); } virtual views::Widget* GetWidget() { return content_view_->GetWidget(); } virtual void InitContentView() { } protected: bool menu_pressed_; bool home_pressed_; private: ui::Accelerator kMenuAccelerator; ui::Accelerator kHomepageAccelerator; Widget* window_; View* content_view_; MessageLoopForUI message_loop_; DISALLOW_COPY_AND_ASSIGN(AcceleratorHandlerGtkTest); }; // Test that the homepage accelerator (Alt+Home) is activated on key down // and that the menu accelerator (Alt) is never activated. TEST_F(AcceleratorHandlerGtkTest, TestHomepageAccelerator) { AcceleratorHandler handler; GdkEventKey evt; ASSERT_FALSE(menu_pressed_); ASSERT_FALSE(home_pressed_); evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); ASSERT_FALSE(home_pressed_); evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Home, GDK_MOD1_MASK); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); ASSERT_TRUE(home_pressed_); evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Home, GDK_MOD1_MASK); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); ASSERT_TRUE(home_pressed_); } // Test that the menu accelerator is activated on key up and not key down. TEST_F(AcceleratorHandlerGtkTest, TestMenuAccelerator) { AcceleratorHandler handler; GdkEventKey evt; ASSERT_FALSE(menu_pressed_); evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_TRUE(menu_pressed_); } // Test that the menu accelerator isn't confused by the interaction of the // Alt and Shift keys. Try the following sequence on Linux: // Press Alt // Press Shift // Release Alt // Release Shift // The key codes for pressing Alt and releasing Alt are different! This // caused a bug in a previous version of the code, which is now fixed by // keeping track of hardware keycodes, which are consistent. TEST_F(AcceleratorHandlerGtkTest, TestAltShiftInteraction) { AcceleratorHandler handler; GdkEventKey evt; ASSERT_FALSE(menu_pressed_); // Press Shift. evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Shift_L, 0); evt.hardware_keycode = 0x32; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // Press Alt - but GDK calls this Meta when Shift is also down. evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Meta_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // Release Shift. evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Shift_L, 0); evt.hardware_keycode = 0x32; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // Release Alt - with Shift not down, the keyval is now Alt, but // the hardware keycode is unchanged. evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); // Press Alt by itself. evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // This line fails if we don't keep track of hardware keycodes. ASSERT_FALSE(menu_pressed_); // Release Alt - now this should trigger the menu shortcut. evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_TRUE(menu_pressed_); } } // namespace views <commit_msg>Fix build.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gdk/gdkkeysyms.h> #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/accelerators/accelerator.h" #include "ui/gfx/rect.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace views { class AcceleratorHandlerGtkTest : public testing::Test, public WidgetDelegate, public ui::AcceleratorTarget { public: AcceleratorHandlerGtkTest() : kMenuAccelerator(ui::VKEY_MENU, false, false, false), kHomepageAccelerator(ui::VKEY_HOME, false, false, true), content_view_(NULL) { } virtual void SetUp() { window_ = Widget::CreateWindowWithBounds(this, gfx::Rect(0, 0, 500, 500)); window_->Show(); FocusManager* focus_manager = window_->GetFocusManager(); focus_manager->RegisterAccelerator( kMenuAccelerator, ui::AcceleratorManager::kNormalPriority, this); focus_manager->RegisterAccelerator( kHomepageAccelerator, ui::AcceleratorManager::kNormalPriority, this); menu_pressed_ = false; home_pressed_ = false; } virtual void TearDown() { window_->Close(); // Flush the message loop to make application verifiers happy. message_loop_.RunAllPending(); } GdkEventKey CreateKeyEvent(GdkEventType type, guint keyval, guint state) { GdkEventKey evt; memset(&evt, 0, sizeof(evt)); evt.type = type; evt.keyval = keyval; // The keyval won't be a "correct" hardware keycode for any real hardware, // but the code should never depend on exact hardware keycodes, just the // fact that the code for presses and releases of the same key match. evt.hardware_keycode = keyval; evt.state = state; GtkWidget* widget = GTK_WIDGET(window_->GetNativeWindow()); evt.window = widget->window; return evt; } // AcceleratorTarget implementation. virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) { if (accelerator == kMenuAccelerator) menu_pressed_ = true; else if (accelerator == kHomepageAccelerator) home_pressed_ = true; return true; } virtual bool CanHandleAccelerators() const { return true; } // WidgetDelegate Implementation. virtual View* GetContentsView() { if (!content_view_) content_view_ = new View(); return content_view_; } virtual const views::Widget* GetWidget() const { return content_view_->GetWidget(); } virtual views::Widget* GetWidget() { return content_view_->GetWidget(); } virtual void InitContentView() { } protected: bool menu_pressed_; bool home_pressed_; private: ui::Accelerator kMenuAccelerator; ui::Accelerator kHomepageAccelerator; Widget* window_; View* content_view_; MessageLoopForUI message_loop_; DISALLOW_COPY_AND_ASSIGN(AcceleratorHandlerGtkTest); }; // Test that the homepage accelerator (Alt+Home) is activated on key down // and that the menu accelerator (Alt) is never activated. TEST_F(AcceleratorHandlerGtkTest, TestHomepageAccelerator) { AcceleratorHandler handler; GdkEventKey evt; ASSERT_FALSE(menu_pressed_); ASSERT_FALSE(home_pressed_); evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); ASSERT_FALSE(home_pressed_); evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Home, GDK_MOD1_MASK); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); ASSERT_TRUE(home_pressed_); evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Home, GDK_MOD1_MASK); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); ASSERT_TRUE(home_pressed_); } // Test that the menu accelerator is activated on key up and not key down. TEST_F(AcceleratorHandlerGtkTest, TestMenuAccelerator) { AcceleratorHandler handler; GdkEventKey evt; ASSERT_FALSE(menu_pressed_); evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_TRUE(menu_pressed_); } // Test that the menu accelerator isn't confused by the interaction of the // Alt and Shift keys. Try the following sequence on Linux: // Press Alt // Press Shift // Release Alt // Release Shift // The key codes for pressing Alt and releasing Alt are different! This // caused a bug in a previous version of the code, which is now fixed by // keeping track of hardware keycodes, which are consistent. TEST_F(AcceleratorHandlerGtkTest, TestAltShiftInteraction) { AcceleratorHandler handler; GdkEventKey evt; ASSERT_FALSE(menu_pressed_); // Press Shift. evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Shift_L, 0); evt.hardware_keycode = 0x32; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // Press Alt - but GDK calls this Meta when Shift is also down. evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Meta_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // Release Shift. evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Shift_L, 0); evt.hardware_keycode = 0x32; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // Release Alt - with Shift not down, the keyval is now Alt, but // the hardware keycode is unchanged. evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_FALSE(menu_pressed_); // Press Alt by itself. evt = CreateKeyEvent(GDK_KEY_PRESS, GDK_Alt_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); // This line fails if we don't keep track of hardware keycodes. ASSERT_FALSE(menu_pressed_); // Release Alt - now this should trigger the menu shortcut. evt = CreateKeyEvent(GDK_KEY_RELEASE, GDK_Alt_L, 0); evt.hardware_keycode = 0x40; EXPECT_TRUE(handler.Dispatch(reinterpret_cast<GdkEvent*>(&evt))); ASSERT_TRUE(menu_pressed_); } } // namespace views <|endoftext|>
<commit_before>#include "view.h" #include "util/tileID.h" #include "platform.h" #include "glm/gtx/string_cast.hpp" const int View::s_maxZoom; // Create a stack reference to the static member variable View::View(int _width, int _height, ProjectionType _projType) { //Set the map projection for the view module to use. setMapProjection(_projType); // Set up projection matrix based on input width and height with an arbitrary zoom setSize(_width, _height); setZoom(16); // Arbitrary zoom for testing // Set up view matrix m_pos = glm::dvec3(0, 0, 1000); // Start at 0 to begin glm::dvec3 direction = glm::dvec3(0, 0, -1); // Look straight down glm::dvec3 up = glm::dvec3(0, 1, 0); // Y-axis is 'up' m_view = glm::lookAt(m_pos, m_pos + direction, up); } void View::setMapProjection(ProjectionType _projType) { switch(_projType) { case ProjectionType::mercator: m_projection.reset(new MercatorProjection()); break; default: logMsg("Error: not a valid map projection specified.\n Setting map projection to mercator by default"); m_projection.reset(new MercatorProjection()); break; } m_dirty = true; } const MapProjection& View::getMapProjection() { return *m_projection.get(); } void View::setSize(int _width, int _height) { m_vpWidth = _width; m_vpHeight = _height; m_aspect = (float)_width / (float)_height; setZoom(m_zoom); m_dirty = true; } void View::setPosition(double _x, double _y) { translate(_x - m_pos.x, _y - m_pos.y); m_dirty = true; } void View::translate(double _dx, double _dy) { m_pos.x += _dx; m_pos.y += _dy; m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0)); m_dirty = true; } void View::zoom(int _dz) { setZoom(m_zoom + _dz); } void View::setZoom(int _z) { // ensure zoom value is allowed glm::clamp(_z, 0, s_maxZoom); m_zoom = _z; // find dimensions of tiles in world space at new zoom level float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom); // viewport height in world space is such that each tile is 256 px square in screen space m_height = (float)m_vpHeight / (float)256.0 * tileSize; m_width = m_height * m_aspect; // set vertical field-of-view to 90 deg double fovy = PI * 0.5; // set camera z to produce desired viewable area m_pos.z = m_height * 0.5 / tan(fovy * 0.5); // set near clipping distance as a function of camera z double near = m_pos.z / 50.0; // update view and projection matrices m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0)); m_proj = glm::perspective(fovy, m_aspect, near, m_pos.z + 1.0); m_dirty = true; } const glm::dmat4 View::getViewProjectionMatrix() const { return m_proj * m_view; } glm::dmat2 View::getBoundsRect() const { double hw = m_width * 0.5; double hh = m_height * 0.5; return glm::dmat2(m_pos.x - hw, m_pos.y - hh, m_pos.x + hw, m_pos.y + hh); } const std::set<TileID>& View::getVisibleTiles() { if (!m_dirty) { return m_visibleTiles; } m_visibleTiles.clear(); float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom); float invTileSize = 1.0 / tileSize; float vpLeftEdge = m_pos.x - m_width * 0.5 + MapProjection::HALF_CIRCUMFERENCE; float vpRightEdge = vpLeftEdge + m_width; float vpBottomEdge = -m_pos.y - m_height * 0.5 + MapProjection::HALF_CIRCUMFERENCE; float vpTopEdge = vpBottomEdge + m_height; int tileX = (int) vpLeftEdge * invTileSize; int tileY = (int) vpBottomEdge * invTileSize; float x = tileX * tileSize; float y = tileY * tileSize; while (x < vpRightEdge) { while (y < vpTopEdge) { m_visibleTiles.insert(TileID(tileX, tileY, m_zoom)); tileY++; y += tileSize; } tileY = (int) vpBottomEdge * invTileSize; y = tileY * tileSize; tileX++; x += tileSize; } m_dirty = false; return m_visibleTiles; } <commit_msg>Fix zoom value clamping<commit_after>#include "view.h" #include "util/tileID.h" #include "platform.h" #include "glm/gtx/string_cast.hpp" const int View::s_maxZoom; // Create a stack reference to the static member variable View::View(int _width, int _height, ProjectionType _projType) { //Set the map projection for the view module to use. setMapProjection(_projType); // Set up projection matrix based on input width and height with an arbitrary zoom setSize(_width, _height); setZoom(16); // Arbitrary zoom for testing // Set up view matrix m_pos = glm::dvec3(0, 0, 1000); // Start at 0 to begin glm::dvec3 direction = glm::dvec3(0, 0, -1); // Look straight down glm::dvec3 up = glm::dvec3(0, 1, 0); // Y-axis is 'up' m_view = glm::lookAt(m_pos, m_pos + direction, up); } void View::setMapProjection(ProjectionType _projType) { switch(_projType) { case ProjectionType::mercator: m_projection.reset(new MercatorProjection()); break; default: logMsg("Error: not a valid map projection specified.\n Setting map projection to mercator by default"); m_projection.reset(new MercatorProjection()); break; } m_dirty = true; } const MapProjection& View::getMapProjection() { return *m_projection.get(); } void View::setSize(int _width, int _height) { m_vpWidth = _width; m_vpHeight = _height; m_aspect = (float)_width / (float)_height; setZoom(m_zoom); m_dirty = true; } void View::setPosition(double _x, double _y) { translate(_x - m_pos.x, _y - m_pos.y); m_dirty = true; } void View::translate(double _dx, double _dy) { m_pos.x += _dx; m_pos.y += _dy; m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0)); m_dirty = true; } void View::zoom(int _dz) { setZoom(m_zoom + _dz); } void View::setZoom(int _z) { // ensure zoom value is allowed m_zoom = glm::clamp(_z, 0, s_maxZoom); // find dimensions of tiles in world space at new zoom level float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom); // viewport height in world space is such that each tile is 256 px square in screen space m_height = (float)m_vpHeight / (float)256.0 * tileSize; m_width = m_height * m_aspect; // set vertical field-of-view to 90 deg double fovy = PI * 0.5; // set camera z to produce desired viewable area m_pos.z = m_height * 0.5 / tan(fovy * 0.5); // set near clipping distance as a function of camera z double near = m_pos.z / 50.0; // update view and projection matrices m_view = glm::lookAt(m_pos, m_pos + glm::dvec3(0, 0, -1), glm::dvec3(0, 1, 0)); m_proj = glm::perspective(fovy, m_aspect, near, m_pos.z + 1.0); m_dirty = true; } const glm::dmat4 View::getViewProjectionMatrix() const { return m_proj * m_view; } glm::dmat2 View::getBoundsRect() const { double hw = m_width * 0.5; double hh = m_height * 0.5; return glm::dmat2(m_pos.x - hw, m_pos.y - hh, m_pos.x + hw, m_pos.y + hh); } const std::set<TileID>& View::getVisibleTiles() { if (!m_dirty) { return m_visibleTiles; } m_visibleTiles.clear(); float tileSize = 2 * MapProjection::HALF_CIRCUMFERENCE * pow(2, -m_zoom); float invTileSize = 1.0 / tileSize; float vpLeftEdge = m_pos.x - m_width * 0.5 + MapProjection::HALF_CIRCUMFERENCE; float vpRightEdge = vpLeftEdge + m_width; float vpBottomEdge = -m_pos.y - m_height * 0.5 + MapProjection::HALF_CIRCUMFERENCE; float vpTopEdge = vpBottomEdge + m_height; int tileX = (int) vpLeftEdge * invTileSize; int tileY = (int) vpBottomEdge * invTileSize; float x = tileX * tileSize; float y = tileY * tileSize; while (x < vpRightEdge) { while (y < vpTopEdge) { m_visibleTiles.insert(TileID(tileX, tileY, m_zoom)); tileY++; y += tileSize; } tileY = (int) vpBottomEdge * invTileSize; y = tileY * tileSize; tileX++; x += tileSize; } m_dirty = false; return m_visibleTiles; } <|endoftext|>
<commit_before>#ifndef GUARD_handle_hpp #define GUARD_handle_hpp #include "sqloxx_exceptions.hpp" namespace sqloxx { /** * Handle for handling business objects of type T where T is a class * derived from PersistentObject and is * managed via IdentityMap<T> to ensure only one instance of T exists in * memory at any one time, in relation to any given record in a given * database. * * @todo Testing and documentation. */ template <typename T> class Handle { public: /** Construct a Handle<T> from a T*. * * @throws sqloxx::OverflowException if the maximum number * of handles for this underlying instance of T has been reached. * The circumstances under which this occurs depend on the * implementation of T::notify_handle_construction(), but should * be extremely rare. * * Exception safety: <em>strong guarantee</em>. * * @todo Testing. */ Handle(T* p_pointer); /** * Preconditions:\n * the object must have been managed * throughout its life by (a single instance of) IdentityMap, * and must only have ever been * accessed via instances of Handle<Derived>; and\n * The destructor of Derived must be non-throwing. * * Exception safety: <em>nothrow guarantee</em>, provided the * preconditions are met. * * @todo Testing. */ ~Handle(); /** * @throws sqloxx::OverflowException in the extremely unlikely * event that the number of Handle instances pointing to the * underlying instance of T is too large to be safely counted * by the type PersistentObject<T, Connection>::HandleCounter. * * Exception safety: <em>strong guarantee</em>. * * @todo Testing. */ Handle(Handle const& rhs); /** * @todo Testing and documentation. */ Handle& operator=(Handle const& rhs); /** * @todo Testing and documentation. */ operator bool() const; /** * @todo Testing and documentation. */ T& operator*() const; /** * @todo Testing and documentation. */ T* operator->() const; private: T* m_pointer; }; template <typename T> Handle<T>::Handle(T* p_pointer): m_pointer(p_pointer) { // Strong guarantee. Might throw OverflowException, though this // is extremely unlikely. p_pointer->notify_handle_construction(); } template <typename T> Handle<T>::~Handle() { // Nothrow provided preconditions met, viz. object must have // been handled throughout its life via Handle<T>, with the // Handle having been copied from another Handle<T>, or else // provided by IdentityMap via a call to provide_handle(...). // Also, the destructor of T must never throw. m_pointer->notify_handle_destruction(); } template <typename T> Handle<T>::Handle(Handle const& rhs) { m_pointer = rhs.m_pointer; // nothrow // Strong guarantee. Might throw OverflowException, though this // is extremely unlikely. m_pointer->notify_handle_copy_construction(); } template <typename T> Handle<T>& Handle<T>::operator=(Handle const& rhs) { // Strong guarantee, provided rhs has a valid pointer... rhs.m_pointer->notify_rhs_assignment_operation(); // Nothrow guarantee, provided preconditions met, and // provided rhs has a valid pointer. m_pointer->notify_lhs_assignment_operation(); m_pointer = rhs.m_pointer; // nothrow return *this; // throw, provided we have a valid pointer } template <typename T> Handle<T>::operator bool() const { return static_cast<bool>(m_pointer); // nothrow } template <typename T> T& Handle<T>::operator*() const { if (static_cast<bool>(m_pointer)) // nothrow { return *m_pointer; // nothrow } throw (UnboundHandleException("Unbound Handle.")); } template <typename T> T* Handle<T>::operator->() const { if (static_cast<bool>(m_pointer)) // nothrow { return m_pointer; // nothrow } throw (UnboundHandleException("Unbound Handle.")); } } // namespace sqloxx #endif // GUARD_handle_hpp <commit_msg>Worked on documentation of sqloxx::Handle<T>.<commit_after>#ifndef GUARD_handle_hpp #define GUARD_handle_hpp #include "sqloxx_exceptions.hpp" namespace sqloxx { /** * Handle for handling business objects of type T where T is a class * derived from PersistentObject and is * managed via IdentityMap<T> to ensure only one instance of T exists in * memory at any one time, in relation to any given record in a given * database. * * @todo Testing and documentation. */ template <typename T> class Handle { public: /** Construct a Handle<T> from a T*. * * @throws sqloxx::OverflowException if the maximum number * of handles for this underlying instance of T has been reached. * The circumstances under which this occurs depend on the * implementation of T::notify_handle_construction(), but should * be extremely rare. * * Exception safety: <em>strong guarantee</em>. * * @todo Testing. */ Handle(T* p_pointer); /** * Preconditions:\n * the object must have been managed * throughout its life by (a single instance of) IdentityMap, * and must only have ever been * accessed via instances of Handle<Derived>; and\n * The destructor of Derived must be non-throwing. * * Exception safety: <em>nothrow guarantee</em>, provided the * preconditions are met. * * @todo Testing. */ ~Handle(); /** * @throws sqloxx::OverflowException in the extremely unlikely * event that the number of Handle instances pointing to the * underlying instance of T is too large to be safely counted * by the type PersistentObject<T, Connection>::HandleCounter. * * Exception safety: <em>strong guarantee</em>. * * @todo Testing. */ Handle(Handle const& rhs); /** * @throws sqloxx::OverflowException in the extremely unlikely * event that the number of Handle instances pointing to the * underlying instance of T is too large to be safely counted * by the type PersistentObject<T, Connection>::HandleCounter. * * Exception safety: <em>strong guarantee</em>. * * @todo Testing. */ Handle& operator=(Handle const& rhs); /** * @return \e true if this Handle<T> is bound to some instance * of T; otherwise returns \e false. * * Exception safety: <em>nothrow guarantee</em>. * * @todo Testing. */ operator bool() const; /** * @todo Testing and documentation. */ T& operator*() const; /** * @todo Testing and documentation. */ T* operator->() const; private: T* m_pointer; }; template <typename T> Handle<T>::Handle(T* p_pointer): m_pointer(p_pointer) { p_pointer->notify_handle_construction(); } template <typename T> Handle<T>::~Handle() { m_pointer->notify_handle_destruction(); } template <typename T> Handle<T>::Handle(Handle const& rhs) { m_pointer = rhs.m_pointer; m_pointer->notify_handle_copy_construction(); } template <typename T> Handle<T>& Handle<T>::operator=(Handle const& rhs) { // Strong guarantee, provided rhs has a valid pointer... rhs.m_pointer->notify_rhs_assignment_operation(); // Nothrow guarantee, provided preconditions met, and // provided rhs has a valid pointer. m_pointer->notify_lhs_assignment_operation(); m_pointer = rhs.m_pointer; // nothrow return *this; // throw, provided we have a valid pointer } template <typename T> Handle<T>::operator bool() const { return static_cast<bool>(m_pointer); // nothrow } template <typename T> T& Handle<T>::operator*() const { if (static_cast<bool>(m_pointer)) // nothrow { return *m_pointer; // nothrow } throw (UnboundHandleException("Unbound Handle.")); } template <typename T> T* Handle<T>::operator->() const { if (static_cast<bool>(m_pointer)) // nothrow { return m_pointer; // nothrow } throw (UnboundHandleException("Unbound Handle.")); } } // namespace sqloxx #endif // GUARD_handle_hpp <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "searchwidget.h" #include "localhelpmanager.h" #include "openpagesmanager.h" #include <coreplugin/icore.h> #include <coreplugin/progressmanager/progressmanager.h> #include <utils/styledbar.h> #include <QMap> #include <QString> #include <QStringList> #include <QMenu> #include <QLayout> #include <QKeyEvent> #include <QClipboard> #include <QApplication> #include <QTextBrowser> #include <QHelpEngine> #include <QHelpSearchEngine> #include <QHelpSearchQueryWidget> #include <QHelpSearchResultWidget> using namespace Help::Internal; SearchWidget::SearchWidget() : zoomCount(0) , m_progress(0) , searchEngine(0) , resultWidget(0) { } SearchWidget::~SearchWidget() { } void SearchWidget::zoomIn() { QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); if (browser && zoomCount != 10) { zoomCount++; browser->zoomIn(); } } void SearchWidget::zoomOut() { QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); if (browser && zoomCount != -5) { zoomCount--; browser->zoomOut(); } } void SearchWidget::resetZoom() { if (zoomCount == 0) return; QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); if (browser) { browser->zoomOut(zoomCount); zoomCount = 0; } } void SearchWidget::showEvent(QShowEvent *event) { if (!event->spontaneous() && !searchEngine) { QVBoxLayout *vLayout = new QVBoxLayout(this); vLayout->setMargin(0); vLayout->setSpacing(0); searchEngine = (&LocalHelpManager::helpEngine())->searchEngine(); Utils::StyledBar *toolbar = new Utils::StyledBar(this); toolbar->setSingleRow(false); QHelpSearchQueryWidget *queryWidget = searchEngine->queryWidget(); QLayout *tbLayout = new QVBoxLayout(); tbLayout->setSpacing(6); tbLayout->setMargin(4); tbLayout->addWidget(queryWidget); toolbar->setLayout(tbLayout); Utils::StyledBar *toolbar2 = new Utils::StyledBar(this); toolbar2->setSingleRow(false); tbLayout = new QVBoxLayout(); tbLayout->setSpacing(0); tbLayout->setMargin(0); tbLayout->addWidget(resultWidget = searchEngine->resultWidget()); toolbar2->setLayout(tbLayout); vLayout->addWidget(toolbar); vLayout->addWidget(toolbar2); setFocusProxy(queryWidget); connect(queryWidget, SIGNAL(search()), this, SLOT(search())); connect(resultWidget, SIGNAL(requestShowLink(QUrl)), this, SIGNAL(linkActivated(QUrl))); connect(searchEngine, SIGNAL(searchingStarted()), this, SLOT(searchingStarted())); connect(searchEngine, SIGNAL(searchingFinished(int)), this, SLOT(searchingFinished(int))); QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); browser->viewport()->installEventFilter(this); connect(searchEngine, SIGNAL(indexingStarted()), this, SLOT(indexingStarted())); connect(searchEngine, SIGNAL(indexingFinished()), this, SLOT(indexingFinished())); QMetaObject::invokeMethod(&LocalHelpManager::helpEngine(), "setupFinished", Qt::QueuedConnection); } } void SearchWidget::search() const { static QStringList charsToEscapeList; if (charsToEscapeList.isEmpty()) { charsToEscapeList << QLatin1String("\\") << QLatin1String("+") << QLatin1String("-") << QLatin1String("!") << QLatin1String("(") << QLatin1String(")") << QLatin1String(":") << QLatin1String("^") << QLatin1String("[") << QLatin1String("]") << QLatin1String("{") << QLatin1String("}") << QLatin1String("~"); } static QString escapeChar(QLatin1String("\\")); static QRegExp regExp(QLatin1String("[\\+\\-\\!\\(\\)\\^\\[\\]\\{\\}~:]")); QList<QHelpSearchQuery> escapedQueries; const QList<QHelpSearchQuery> queries = searchEngine->queryWidget()->query(); foreach (const QHelpSearchQuery &query, queries) { QHelpSearchQuery escapedQuery; escapedQuery.fieldName = query.fieldName; foreach (QString word, query.wordList) { if (word.contains(regExp)) { foreach (const QString &charToEscape, charsToEscapeList) word.replace(charToEscape, escapeChar + charToEscape); escapedQuery.wordList.append(word); } } escapedQueries.append(escapedQuery); } searchEngine->search(escapedQueries); } void SearchWidget::searchingStarted() { qApp->setOverrideCursor(QCursor(Qt::WaitCursor)); } void SearchWidget::searchingFinished(int hits) { Q_UNUSED(hits) qApp->restoreOverrideCursor(); } void SearchWidget::indexingStarted() { Q_ASSERT(!m_progress); m_progress = new QFutureInterface<void>(); Core::ICore::progressManager() ->addTask(m_progress->future(), tr("Indexing"), QLatin1String("Help.Indexer")); m_progress->setProgressRange(0, 2); m_progress->setProgressValueAndText(1, tr("Indexing Documentation...")); m_progress->reportStarted(); m_watcher.setFuture(m_progress->future()); connect(&m_watcher, SIGNAL(canceled()), searchEngine, SLOT(cancelIndexing())); } void SearchWidget::indexingFinished() { m_progress->reportFinished(); delete m_progress; m_progress = NULL; } bool SearchWidget::eventFilter(QObject *o, QEvent *e) { QTextBrowser *browser = qFindChild<QTextBrowser *>(resultWidget); if (browser && o == browser->viewport() && e->type() == QEvent::MouseButtonRelease){ QMouseEvent *me = static_cast<QMouseEvent *>(e); QUrl link = resultWidget->linkAt(me->pos()); if (!link.isEmpty() || link.isValid()) { bool controlPressed = me->modifiers() & Qt::ControlModifier; if ((me->button() == Qt::LeftButton && controlPressed) || (me->button() == Qt::MidButton)) { OpenPagesManager::instance().createPageFromSearch(link); } } } return QWidget::eventFilter(o,e); } void SearchWidget::contextMenuEvent(QContextMenuEvent *contextMenuEvent) { QTextBrowser *browser = qFindChild<QTextBrowser *>(resultWidget); if (!browser) return; QPoint point = browser->mapFromGlobal(contextMenuEvent->globalPos()); if (!browser->rect().contains(point, true)) return; QAction *openLink = 0; QAction *openLinkInNewTab = 0; QAction *copyAnchorAction = 0; QMenu menu; QUrl link = browser->anchorAt(point); if (!link.isEmpty() && link.isValid()) { if (link.isRelative()) link = browser->source().resolved(link); openLink = menu.addAction(tr("Open Link")); openLinkInNewTab = menu.addAction(tr("Open Link as New Page")); copyAnchorAction = menu.addAction(tr("Copy Link")); } else if (browser->textCursor().hasSelection()) { menu.addAction(tr("Copy"), browser, SLOT(copy())); } else { menu.addAction(tr("Reload"), browser, SLOT(reload())); } QAction *usedAction = menu.exec(mapToGlobal(contextMenuEvent->pos())); if (usedAction == openLink) { browser->selectAll(); } else if (usedAction == openLinkInNewTab) { OpenPagesManager::instance().createPageFromSearch(link); } else if (usedAction == copyAnchorAction) { QApplication::clipboard()->setText(link.toString()); } } <commit_msg>Fix 38fe616d857234845b9169576433c28aa54fee89<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "searchwidget.h" #include "localhelpmanager.h" #include "openpagesmanager.h" #include <coreplugin/icore.h> #include <coreplugin/progressmanager/progressmanager.h> #include <utils/styledbar.h> #include <QMap> #include <QString> #include <QStringList> #include <QMenu> #include <QLayout> #include <QKeyEvent> #include <QClipboard> #include <QApplication> #include <QTextBrowser> #include <QHelpEngine> #include <QHelpSearchEngine> #include <QHelpSearchQueryWidget> #include <QHelpSearchResultWidget> using namespace Help::Internal; SearchWidget::SearchWidget() : zoomCount(0) , m_progress(0) , searchEngine(0) , resultWidget(0) { } SearchWidget::~SearchWidget() { } void SearchWidget::zoomIn() { QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); if (browser && zoomCount != 10) { zoomCount++; browser->zoomIn(); } } void SearchWidget::zoomOut() { QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); if (browser && zoomCount != -5) { zoomCount--; browser->zoomOut(); } } void SearchWidget::resetZoom() { if (zoomCount == 0) return; QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); if (browser) { browser->zoomOut(zoomCount); zoomCount = 0; } } void SearchWidget::showEvent(QShowEvent *event) { if (!event->spontaneous() && !searchEngine) { QVBoxLayout *vLayout = new QVBoxLayout(this); vLayout->setMargin(0); vLayout->setSpacing(0); searchEngine = (&LocalHelpManager::helpEngine())->searchEngine(); Utils::StyledBar *toolbar = new Utils::StyledBar(this); toolbar->setSingleRow(false); QHelpSearchQueryWidget *queryWidget = searchEngine->queryWidget(); QLayout *tbLayout = new QVBoxLayout(); tbLayout->setSpacing(6); tbLayout->setMargin(4); tbLayout->addWidget(queryWidget); toolbar->setLayout(tbLayout); Utils::StyledBar *toolbar2 = new Utils::StyledBar(this); toolbar2->setSingleRow(false); tbLayout = new QVBoxLayout(); tbLayout->setSpacing(0); tbLayout->setMargin(0); tbLayout->addWidget(resultWidget = searchEngine->resultWidget()); toolbar2->setLayout(tbLayout); vLayout->addWidget(toolbar); vLayout->addWidget(toolbar2); setFocusProxy(queryWidget); connect(queryWidget, SIGNAL(search()), this, SLOT(search())); connect(resultWidget, SIGNAL(requestShowLink(QUrl)), this, SIGNAL(linkActivated(QUrl))); connect(searchEngine, SIGNAL(searchingStarted()), this, SLOT(searchingStarted())); connect(searchEngine, SIGNAL(searchingFinished(int)), this, SLOT(searchingFinished(int))); QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget); browser->viewport()->installEventFilter(this); connect(searchEngine, SIGNAL(indexingStarted()), this, SLOT(indexingStarted())); connect(searchEngine, SIGNAL(indexingFinished()), this, SLOT(indexingFinished())); QMetaObject::invokeMethod(&LocalHelpManager::helpEngine(), "setupFinished", Qt::QueuedConnection); } } void SearchWidget::search() const { static QStringList charsToEscapeList; if (charsToEscapeList.isEmpty()) { charsToEscapeList << QLatin1String("\\") << QLatin1String("+") << QLatin1String("-") << QLatin1String("!") << QLatin1String("(") << QLatin1String(")") << QLatin1String(":") << QLatin1String("^") << QLatin1String("[") << QLatin1String("]") << QLatin1String("{") << QLatin1String("}") << QLatin1String("~"); } static QString escapeChar(QLatin1String("\\")); static QRegExp regExp(QLatin1String("[\\+\\-\\!\\(\\)\\^\\[\\]\\{\\}~:]")); QList<QHelpSearchQuery> escapedQueries; const QList<QHelpSearchQuery> queries = searchEngine->queryWidget()->query(); foreach (const QHelpSearchQuery &query, queries) { QHelpSearchQuery escapedQuery; escapedQuery.fieldName = query.fieldName; foreach (QString word, query.wordList) { if (word.contains(regExp)) { foreach (const QString &charToEscape, charsToEscapeList) word.replace(charToEscape, escapeChar + charToEscape); } escapedQuery.wordList.append(word); } escapedQueries.append(escapedQuery); } searchEngine->search(escapedQueries); } void SearchWidget::searchingStarted() { qApp->setOverrideCursor(QCursor(Qt::WaitCursor)); } void SearchWidget::searchingFinished(int hits) { Q_UNUSED(hits) qApp->restoreOverrideCursor(); } void SearchWidget::indexingStarted() { Q_ASSERT(!m_progress); m_progress = new QFutureInterface<void>(); Core::ICore::progressManager() ->addTask(m_progress->future(), tr("Indexing"), QLatin1String("Help.Indexer")); m_progress->setProgressRange(0, 2); m_progress->setProgressValueAndText(1, tr("Indexing Documentation...")); m_progress->reportStarted(); m_watcher.setFuture(m_progress->future()); connect(&m_watcher, SIGNAL(canceled()), searchEngine, SLOT(cancelIndexing())); } void SearchWidget::indexingFinished() { m_progress->reportFinished(); delete m_progress; m_progress = NULL; } bool SearchWidget::eventFilter(QObject *o, QEvent *e) { QTextBrowser *browser = qFindChild<QTextBrowser *>(resultWidget); if (browser && o == browser->viewport() && e->type() == QEvent::MouseButtonRelease){ QMouseEvent *me = static_cast<QMouseEvent *>(e); QUrl link = resultWidget->linkAt(me->pos()); if (!link.isEmpty() || link.isValid()) { bool controlPressed = me->modifiers() & Qt::ControlModifier; if ((me->button() == Qt::LeftButton && controlPressed) || (me->button() == Qt::MidButton)) { OpenPagesManager::instance().createPageFromSearch(link); } } } return QWidget::eventFilter(o,e); } void SearchWidget::contextMenuEvent(QContextMenuEvent *contextMenuEvent) { QTextBrowser *browser = qFindChild<QTextBrowser *>(resultWidget); if (!browser) return; QPoint point = browser->mapFromGlobal(contextMenuEvent->globalPos()); if (!browser->rect().contains(point, true)) return; QAction *openLink = 0; QAction *openLinkInNewTab = 0; QAction *copyAnchorAction = 0; QMenu menu; QUrl link = browser->anchorAt(point); if (!link.isEmpty() && link.isValid()) { if (link.isRelative()) link = browser->source().resolved(link); openLink = menu.addAction(tr("Open Link")); openLinkInNewTab = menu.addAction(tr("Open Link as New Page")); copyAnchorAction = menu.addAction(tr("Copy Link")); } else if (browser->textCursor().hasSelection()) { menu.addAction(tr("Copy"), browser, SLOT(copy())); } else { menu.addAction(tr("Reload"), browser, SLOT(reload())); } QAction *usedAction = menu.exec(mapToGlobal(contextMenuEvent->pos())); if (usedAction == openLink) { browser->selectAll(); } else if (usedAction == openLinkInNewTab) { OpenPagesManager::instance().createPageFromSearch(link); } else if (usedAction == copyAnchorAction) { QApplication::clipboard()->setText(link.toString()); } } <|endoftext|>
<commit_before>#include "Atm_servo.hpp" /* Add optional parameters for the state machine to begin() * Add extra initialization code */ Atm_servo& Atm_servo::begin( int pin, int pos ) { // clang-format off const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_MVUP EVT_MVDN EVT_TIMER ELSE */ /* IDLE */ ENT_IDLE, -1, -1, UP, DOWN, -1, -1, /* UP */ ENT_UP, -1, -1, -1, -1, UP_NEXT, -1, /* UP_NEXT */ -1, -1, -1, UP, DOWN, -1, FINISHED, /* DOWN */ ENT_DOWN, -1, -1, -1, -1, DOWN_NEXT, -1, /* DOWN_NEXT */ -1, -1, -1, UP, DOWN, -1, FINISHED, /* FINISHED */ ENT_FINISHED, -1, -1, -1, -1, -1, IDLE, }; // clang-format on Machine::begin( state_table, ELSE ); this->pin = pin; servo.attach( pin ); servo_pos = pos; servo_dest = pos; step_size = 180; timer.set( step_time = 0 ); servo.write( servo_dest ); return *this; } /* Add C++ code for each internally handled event (input) * The code must return 1 to trigger the event */ int Atm_servo::event( int id ) { switch ( id ) { case EVT_MVUP: return servo_dest > servo_pos; case EVT_MVDN: return servo_dest < servo_pos; case EVT_TIMER: return timer.expired( this ); } return 0; } /* Add C++ code for each action * This generates the 'output' for the state machine */ void Atm_servo::action( int id ) { switch ( id ) { case ENT_IDLE: return; case ENT_UP: push( connectors, ON_CHANGE, true, servo_pos, 1 ); servo_pos += step_size; if ( servo_pos > servo_dest ) servo_pos = servo_dest; servo.write( servo_pos ); timer.set( step_time ); return; case ENT_DOWN: push( connectors, ON_CHANGE, false, servo_pos, 0 ); servo_pos -= step_size; if ( servo_pos < servo_dest ) servo_pos = servo_dest; servo.write( servo_pos ); timer.set( step_time ); return; case ENT_FINISHED: push( connectors, ON_FINISH, 0, servo_pos, 0 ); return; } } Atm_servo& Atm_servo::step( int degrees, int time ) { step_size = degrees; timer.set( step_time = time ); return *this; } Atm_servo& Atm_servo::position( int pos ) { servo_dest = pos; return *this; } int Atm_servo::position( void ) { return servo_pos; } /* Optionally override the default trigger() method * Control how your machine processes triggers */ Atm_servo& Atm_servo::trigger( int event ) { switch ( event ) { case EVT_MVUP: servo_dest += step_size; if ( servo_dest > 180 ) servo_dest = 180; break; case EVT_MVDN: servo_dest -= step_size; if ( servo_dest < 0 ) servo_dest = 0; break; default: servo_dest = event; break; } return *this; } /* Optionally override the default state() method * Control what the machine returns when another process requests its state */ int Atm_servo::state( void ) { return Machine::state(); } /* Nothing customizable below this line ************************************************************************************************ */ /* onChange() push connector variants ( slots 2, autostore 0, broadcast 0 ) * * Usage in action() handler: push( connectors, ON_CHANGE, sub, v, up ); */ Atm_servo& Atm_servo::onChange( Machine& machine, int event ) { onPush( connectors, ON_CHANGE, 0, 2, 1, machine, event ); return *this; } Atm_servo& Atm_servo::onChange( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_CHANGE, 0, 2, 1, callback, idx ); return *this; } Atm_servo& Atm_servo::onChange( int sub, Machine& machine, int event ) { onPush( connectors, ON_CHANGE, sub, 2, 0, machine, event ); return *this; } Atm_servo& Atm_servo::onChange( int sub, atm_cb_push_t callback, int idx ) { onPush( connectors, ON_CHANGE, sub, 2, 0, callback, idx ); return *this; } /* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 ) * * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up ); */ Atm_servo& Atm_servo::onFinish( Machine& machine, int event ) { onPush( connectors, ON_FINISH, 0, 1, 1, machine, event ); return *this; } Atm_servo& Atm_servo::onFinish( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_FINISH, 0, 1, 1, callback, idx ); return *this; } /* State trace method * Sets the symbol table and the default logging method for serial monitoring */ Atm_servo& Atm_servo::trace( Stream& stream ) { Machine::setTrace( &stream, atm_serial_debug::trace, "SERVO\0EVT_MVUP\0EVT_MVDN\0EVT_TIMER\0ELSE\0IDLE\0UP\0UP_NEXT\0DOWN\0DOWN_NEXT\0FINISHED" ); return *this; } <commit_msg>Fixed trigger values<commit_after>#include "Atm_servo.hpp" /* Add optional parameters for the state machine to begin() * Add extra initialization code */ Atm_servo& Atm_servo::begin( int pin, int pos ) { // clang-format off const static state_t state_table[] PROGMEM = { /* ON_ENTER ON_LOOP ON_EXIT EVT_MVUP EVT_MVDN EVT_TIMER ELSE */ /* IDLE */ ENT_IDLE, -1, -1, UP, DOWN, -1, -1, /* UP */ ENT_UP, -1, -1, -1, -1, UP_NEXT, -1, /* UP_NEXT */ -1, -1, -1, UP, DOWN, -1, FINISHED, /* DOWN */ ENT_DOWN, -1, -1, -1, -1, DOWN_NEXT, -1, /* DOWN_NEXT */ -1, -1, -1, UP, DOWN, -1, FINISHED, /* FINISHED */ ENT_FINISHED, -1, -1, -1, -1, -1, IDLE, }; // clang-format on Machine::begin( state_table, ELSE ); this->pin = pin; servo.attach( pin ); servo_pos = pos; servo_dest = pos; step_size = 180; timer.set( step_time = 0 ); servo.write( servo_dest ); return *this; } /* Add C++ code for each internally handled event (input) * The code must return 1 to trigger the event */ int Atm_servo::event( int id ) { switch ( id ) { case EVT_MVUP: return servo_dest > servo_pos; case EVT_MVDN: return servo_dest < servo_pos; case EVT_TIMER: return timer.expired( this ); } return 0; } /* Add C++ code for each action * This generates the 'output' for the state machine */ void Atm_servo::action( int id ) { switch ( id ) { case ENT_IDLE: return; case ENT_UP: push( connectors, ON_CHANGE, true, servo_pos, 1 ); servo_pos += step_size; if ( servo_pos > servo_dest ) servo_pos = servo_dest; servo.write( servo_pos ); timer.set( step_time ); return; case ENT_DOWN: push( connectors, ON_CHANGE, false, servo_pos, 0 ); servo_pos -= step_size; if ( servo_pos < servo_dest ) servo_pos = servo_dest; servo.write( servo_pos ); timer.set( step_time ); return; case ENT_FINISHED: push( connectors, ON_FINISH, 0, servo_pos, 0 ); return; } } Atm_servo& Atm_servo::step( int degrees, int time ) { step_size = degrees; timer.set( step_time = time ); return *this; } Atm_servo& Atm_servo::position( int pos ) { servo_dest = pos; return *this; } int Atm_servo::position( void ) { return servo_pos; } /* Optionally override the default trigger() method * Control how your machine processes triggers */ Atm_servo& Atm_servo::trigger( int event ) { switch ( event ) { case EVT_UP: servo_dest += step_size; if ( servo_dest > 180 ) servo_dest = 180; break; case EVT_DOWN: servo_dest -= step_size; if ( servo_dest < 0 ) servo_dest = 0; break; default: servo_dest = event; break; } return *this; } /* Optionally override the default state() method * Control what the machine returns when another process requests its state */ int Atm_servo::state( void ) { return Machine::state(); } /* Nothing customizable below this line ************************************************************************************************ */ /* onChange() push connector variants ( slots 2, autostore 0, broadcast 0 ) * * Usage in action() handler: push( connectors, ON_CHANGE, sub, v, up ); */ Atm_servo& Atm_servo::onChange( Machine& machine, int event ) { onPush( connectors, ON_CHANGE, 0, 2, 1, machine, event ); return *this; } Atm_servo& Atm_servo::onChange( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_CHANGE, 0, 2, 1, callback, idx ); return *this; } Atm_servo& Atm_servo::onChange( int sub, Machine& machine, int event ) { onPush( connectors, ON_CHANGE, sub, 2, 0, machine, event ); return *this; } Atm_servo& Atm_servo::onChange( int sub, atm_cb_push_t callback, int idx ) { onPush( connectors, ON_CHANGE, sub, 2, 0, callback, idx ); return *this; } /* onFinish() push connector variants ( slots 1, autostore 0, broadcast 0 ) * * Usage in action() handler: push( connectors, ON_FINISH, 0, v, up ); */ Atm_servo& Atm_servo::onFinish( Machine& machine, int event ) { onPush( connectors, ON_FINISH, 0, 1, 1, machine, event ); return *this; } Atm_servo& Atm_servo::onFinish( atm_cb_push_t callback, int idx ) { onPush( connectors, ON_FINISH, 0, 1, 1, callback, idx ); return *this; } /* State trace method * Sets the symbol table and the default logging method for serial monitoring */ Atm_servo& Atm_servo::trace( Stream& stream ) { Machine::setTrace( &stream, atm_serial_debug::trace, "SERVO\0EVT_MVUP\0EVT_MVDN\0EVT_TIMER\0ELSE\0IDLE\0UP\0UP_NEXT\0DOWN\0DOWN_NEXT\0FINISHED" ); return *this; } <|endoftext|>
<commit_before>/* This file is part of WME Lite. http://dead-code.org/redir.php?target=wmelite Copyright (c) 2011 Jan Nedoma 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. */ #include "dcgf.h" #include "BViewport.h" namespace WinterMute { IMPLEMENT_PERSISTENT(CBViewport, false) ////////////////////////////////////////////////////////////////////////// CBViewport::CBViewport(CBGame *inGame): CBBase(inGame) { CBPlatform::SetRectEmpty(&m_Rect); m_MainObject = NULL; m_OffsetX = m_OffsetY = 0; } ////////////////////////////////////////////////////////////////////////// CBViewport::~CBViewport() { } ////////////////////////////////////////////////////////////////////////// HRESULT CBViewport::Persist(CBPersistMgr *PersistMgr) { PersistMgr->Transfer(TMEMBER(Game)); PersistMgr->Transfer(TMEMBER(m_MainObject)); PersistMgr->Transfer(TMEMBER(m_OffsetX)); PersistMgr->Transfer(TMEMBER(m_OffsetY)); PersistMgr->Transfer(TMEMBER(m_Rect)); return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CBViewport::SetRect(int left, int top, int right, int bottom, bool NoCheck) { if (!NoCheck) { left = std::max(left, 0); top = std::max(top, 0); right = std::min(right, Game->m_Renderer->m_Width); bottom = std::min(bottom, Game->m_Renderer->m_Height); } CBPlatform::SetRect(&m_Rect, left, top, right, bottom); m_OffsetX = left; m_OffsetY = top; return S_OK; } ////////////////////////////////////////////////////////////////////////// RECT *CBViewport::GetRect() { return &m_Rect; } ////////////////////////////////////////////////////////////////////////// int CBViewport::GetWidth() { return m_Rect.right - m_Rect.left; } ////////////////////////////////////////////////////////////////////////// int CBViewport::GetHeight() { return m_Rect.bottom - m_Rect.top; } } // end of namespace WinterMute <commit_msg>WINTERMUTE: Make BViewPort independent of dcgf<commit_after>/* This file is part of WME Lite. http://dead-code.org/redir.php?target=wmelite Copyright (c) 2011 Jan Nedoma 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. */ #include "BGame.h" #include "PlatformSDL.h" #include "BViewport.h" namespace WinterMute { IMPLEMENT_PERSISTENT(CBViewport, false) ////////////////////////////////////////////////////////////////////////// CBViewport::CBViewport(CBGame *inGame): CBBase(inGame) { CBPlatform::SetRectEmpty(&m_Rect); m_MainObject = NULL; m_OffsetX = m_OffsetY = 0; } ////////////////////////////////////////////////////////////////////////// CBViewport::~CBViewport() { } ////////////////////////////////////////////////////////////////////////// HRESULT CBViewport::Persist(CBPersistMgr *PersistMgr) { PersistMgr->Transfer(TMEMBER(Game)); PersistMgr->Transfer(TMEMBER(m_MainObject)); PersistMgr->Transfer(TMEMBER(m_OffsetX)); PersistMgr->Transfer(TMEMBER(m_OffsetY)); PersistMgr->Transfer(TMEMBER(m_Rect)); return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CBViewport::SetRect(int left, int top, int right, int bottom, bool NoCheck) { if (!NoCheck) { left = std::max(left, 0); top = std::max(top, 0); right = std::min(right, Game->m_Renderer->m_Width); bottom = std::min(bottom, Game->m_Renderer->m_Height); } CBPlatform::SetRect(&m_Rect, left, top, right, bottom); m_OffsetX = left; m_OffsetY = top; return S_OK; } ////////////////////////////////////////////////////////////////////////// RECT *CBViewport::GetRect() { return &m_Rect; } ////////////////////////////////////////////////////////////////////////// int CBViewport::GetWidth() { return m_Rect.right - m_Rect.left; } ////////////////////////////////////////////////////////////////////////// int CBViewport::GetHeight() { return m_Rect.bottom - m_Rect.top; } } // end of namespace WinterMute <|endoftext|>
<commit_before>/** \file Archive.cc * \brief Implementations of the archive processing functions and classes. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2016-2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Archive.h" #include <cstring> #include <fcntl.h> #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "StringUtil.h" #include "util.h" namespace Archive { const std::string Reader::EntryInfo::getFilename() const { return ::archive_entry_pathname(archive_entry_); } bool Reader::EntryInfo::isRegularFile() const { return ::archive_entry_filetype(archive_entry_) == AE_IFREG; } bool Reader::EntryInfo::isDirectory() const { return ::archive_entry_filetype(archive_entry_) == AE_IFDIR; } const unsigned DEFAULT_BLOCKSIZE(10240); Reader::Reader(const std::string &archive_file_name) { archive_handle_ = ::archive_read_new(); ::archive_read_support_filter_all(archive_handle_); ::archive_read_support_format_all(archive_handle_); if (unlikely(::archive_read_open_filename(archive_handle_, archive_file_name.c_str(), DEFAULT_BLOCKSIZE) != ARCHIVE_OK)) LOG_ERROR("archive_read_open_filename(3) failed: " + std::string(::archive_error_string(archive_handle_))); } Reader::~Reader() { if (unlikely(::archive_read_free(archive_handle_) != ARCHIVE_OK)) LOG_ERROR("archive_read_free(3) failed!"); } bool Reader::getNext(EntryInfo * const info) { int status; while ((status = ::archive_read_next_header(archive_handle_, &info->archive_entry_)) == ARCHIVE_RETRY) /* Intentionally empty! */; if (status == ARCHIVE_OK) return true; if (status == ARCHIVE_EOF) return false; LOG_ERROR("something went wrong! (" + std::string(::archive_error_string(archive_handle_)) + ")"); } ssize_t Reader::read(char * const buffer, const size_t size) { ssize_t retval; do retval = ::archive_read_data(archive_handle_, reinterpret_cast<void * const>(buffer), size); while (retval == ARCHIVE_RETRY); return (retval == ARCHIVE_FATAL or retval == ARCHIVE_WARN) ? -1 : retval; } bool Reader::extractEntry(const std::string &member_name, std::string output_filename) { if (output_filename.empty()) output_filename = member_name; EntryInfo entry_info; while (getNext(&entry_info)) { if (entry_info.getFilename() != member_name) continue; if (entry_info.isDirectory()) LOG_ERROR("an't extract a directory!"); const int to_fd(::open(output_filename.c_str(), O_WRONLY | O_CREAT, 0600)); if (unlikely(to_fd == -1)) LOG_ERROR("failed to open \"" + output_filename + "\" for writing!"); char buf[BUFSIZ]; for (;;) { const ssize_t no_of_bytes(read(&buf[0], sizeof(buf))); if (no_of_bytes == 0) { ::close(to_fd); return true; } if (unlikely(no_of_bytes < 0)) LOG_ERROR(getLastErrorMessage()); if (unlikely(::write(to_fd, &buf[0], no_of_bytes) != no_of_bytes)) LOG_ERROR("write(2) failed!"); } ::close(to_fd); } return false; } Writer::Writer(const std::string &archive_file_name, const std::string &archive_write_options, const FileType file_type) : archive_entry_(nullptr) { archive_handle_ = ::archive_write_new(); switch (file_type) { case FileType::AUTO: if (StringUtil::EndsWith(archive_file_name, ".tar")) { if (unlikely(not archive_write_options.empty())) LOG_ERROR("no write options are currently supported for the uncompressed tar format!"); ::archive_write_set_format_pax_restricted(archive_handle_); } else if (StringUtil::EndsWith(archive_file_name, ".tar.gz")) { ::archive_write_add_filter_gzip(archive_handle_); if (unlikely(::archive_write_set_options(archive_handle_, archive_write_options.c_str()) != ARCHIVE_OK)) LOG_ERROR("failed to call archive_write_set_options(3) w/ \"" + archive_write_options + "\"!"); ::archive_write_set_format_pax_restricted(archive_handle_); } else LOG_ERROR("FileType::AUTO selected but," " can't guess the file type from the given filename \"" + archive_file_name + "\"!"); break; case FileType::TAR: if (unlikely(not archive_write_options.empty())) LOG_ERROR("no write options are currently supported for the uncompressed tar format! (2)"); ::archive_write_set_format_pax_restricted(archive_handle_); break; case FileType::GZIPPED_TAR: ::archive_write_add_filter_gzip(archive_handle_); if (unlikely(::archive_write_set_options(archive_handle_, archive_write_options.c_str()) != ARCHIVE_OK)) LOG_ERROR("failed to call archive_write_set_options(3) w/ \"" + archive_write_options + "\"! (2)"); ::archive_write_set_format_pax_restricted(archive_handle_); break; } if (unlikely(::archive_write_open_filename(archive_handle_, archive_file_name.c_str()) != ARCHIVE_OK)) LOG_ERROR("archive_write_open_filename(3) failed: " + std::string(::archive_error_string(archive_handle_))); } Writer::~Writer() { if (archive_entry_ != nullptr) ::archive_entry_free(archive_entry_); if (unlikely(::archive_write_close(archive_handle_) != ARCHIVE_OK)) LOG_ERROR("archive_write_close(3) failed: " + std::string(::archive_error_string(archive_handle_))); if (unlikely(::archive_write_free(archive_handle_) != ARCHIVE_OK)) LOG_ERROR("archive_write_free(3) failed: " + std::string(::archive_error_string(archive_handle_))); } void Writer::add(const std::string &filename, std::string archive_name) { if (archive_name.empty()) archive_name = filename; if (unlikely(already_seen_archive_names_.find(archive_name) != already_seen_archive_names_.end())) LOG_ERROR("attempt to store a duplicate archive entry name \"" + archive_name + "\"!"); else already_seen_archive_names_.emplace(archive_name); struct stat stat_buf; if (unlikely(::stat(filename.c_str(), &stat_buf) != 0)) LOG_ERROR("stat(2) on \"" + filename + "\" failed: " + std::string(::strerror(errno))); if (archive_entry_ == nullptr) archive_entry_ = ::archive_entry_new(); else ::archive_entry_clear(archive_entry_); ::archive_entry_set_pathname(archive_entry_, archive_name.c_str()); ::archive_entry_copy_stat(archive_entry_, &stat_buf); int status; while ((status = ::archive_write_header(archive_handle_, archive_entry_)) == ARCHIVE_RETRY) /* Intentionally empty! */; if (unlikely(status != ARCHIVE_OK)) LOG_ERROR("archive_write_header(3) failed! (" + std::string(::archive_error_string(archive_handle_))); File input(filename, "r", File::THROW_ON_ERROR); char buffer[DEFAULT_BLOCKSIZE]; size_t count; while ((count = input.read(buffer, DEFAULT_BLOCKSIZE)) > 0) { if (count < DEFAULT_BLOCKSIZE and input.anErrorOccurred()) LOG_ERROR("error reading \"" + filename + "\" !"); if (unlikely(::archive_write_data(archive_handle_, buffer, count) != static_cast<const ssize_t>(count))) LOG_ERROR("archive_write_data(3) failed: " + std::string(::archive_error_string(archive_handle_))); } } void Writer::addEntry(const std::string &filename, const int64_t size, const mode_t mode, const EntryType entry_type) { if (archive_entry_ != nullptr) ::archive_entry_clear(archive_entry_); else archive_entry_ = ::archive_entry_new(); ::archive_entry_set_pathname(archive_entry_, filename.c_str()); ::archive_entry_set_size(archive_entry_, size); if (entry_type == EntryType::REGULAR_FILE) ::archive_entry_set_filetype(archive_entry_, AE_IFREG); else LOG_ERROR("unsupported entry type: " + std::to_string(static_cast<int>(entry_type)) + "!"); ::archive_entry_set_perm(archive_entry_, mode); } void Writer::write(char * const buffer, const size_t size) { if (::archive_write_data(archive_handle_, buffer, size) < 0) LOG_ERROR("archive_write_data failed!"); } void UnpackArchive(const std::string &archive_name, const std::string &directory) { if (unlikely(not FileUtil::MakeDirectory(directory))) LOG_ERROR("failed to create directory \"" + directory + "\"!"); Reader reader(archive_name); Reader::EntryInfo file_info; while (reader.getNext(&file_info)) { if (file_info.empty()) continue; if (unlikely(not file_info.isRegularFile())) LOG_ERROR("unexpectedly, the entry \"" + file_info.getFilename() + "\" in \"" + archive_name + "\" is not a regular file!"); const std::string output_filename(directory + "/" + file_info.getFilename()); const auto output(FileUtil::OpenOutputFileOrDie(output_filename)); char buf[8192]; size_t read_count; while ((read_count = reader.read(buf, sizeof buf)) > 0) { if (unlikely(output->write(buf, read_count) != read_count)) LOG_ERROR("failed to write data to \"" + output->getPath() + "\"! (No room?)"); } } } } // namespace Archive <commit_msg>Added missing call.<commit_after>/** \file Archive.cc * \brief Implementations of the archive processing functions and classes. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2016-2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Archive.h" #include <cstring> #include <fcntl.h> #include "Compiler.h" #include "File.h" #include "FileUtil.h" #include "StringUtil.h" #include "util.h" namespace Archive { const std::string Reader::EntryInfo::getFilename() const { return ::archive_entry_pathname(archive_entry_); } bool Reader::EntryInfo::isRegularFile() const { return ::archive_entry_filetype(archive_entry_) == AE_IFREG; } bool Reader::EntryInfo::isDirectory() const { return ::archive_entry_filetype(archive_entry_) == AE_IFDIR; } const unsigned DEFAULT_BLOCKSIZE(10240); Reader::Reader(const std::string &archive_file_name) { archive_handle_ = ::archive_read_new(); ::archive_read_support_filter_all(archive_handle_); ::archive_read_support_format_all(archive_handle_); if (unlikely(::archive_read_open_filename(archive_handle_, archive_file_name.c_str(), DEFAULT_BLOCKSIZE) != ARCHIVE_OK)) LOG_ERROR("archive_read_open_filename(3) failed: " + std::string(::archive_error_string(archive_handle_))); } Reader::~Reader() { if (unlikely(::archive_read_free(archive_handle_) != ARCHIVE_OK)) LOG_ERROR("archive_read_free(3) failed!"); } bool Reader::getNext(EntryInfo * const info) { int status; while ((status = ::archive_read_next_header(archive_handle_, &info->archive_entry_)) == ARCHIVE_RETRY) /* Intentionally empty! */; if (status == ARCHIVE_OK) return true; if (status == ARCHIVE_EOF) return false; LOG_ERROR("something went wrong! (" + std::string(::archive_error_string(archive_handle_)) + ")"); } ssize_t Reader::read(char * const buffer, const size_t size) { ssize_t retval; do retval = ::archive_read_data(archive_handle_, reinterpret_cast<void * const>(buffer), size); while (retval == ARCHIVE_RETRY); return (retval == ARCHIVE_FATAL or retval == ARCHIVE_WARN) ? -1 : retval; } bool Reader::extractEntry(const std::string &member_name, std::string output_filename) { if (output_filename.empty()) output_filename = member_name; EntryInfo entry_info; while (getNext(&entry_info)) { if (entry_info.getFilename() != member_name) continue; if (entry_info.isDirectory()) LOG_ERROR("an't extract a directory!"); const int to_fd(::open(output_filename.c_str(), O_WRONLY | O_CREAT, 0600)); if (unlikely(to_fd == -1)) LOG_ERROR("failed to open \"" + output_filename + "\" for writing!"); char buf[BUFSIZ]; for (;;) { const ssize_t no_of_bytes(read(&buf[0], sizeof(buf))); if (no_of_bytes == 0) { ::close(to_fd); return true; } if (unlikely(no_of_bytes < 0)) LOG_ERROR(getLastErrorMessage()); if (unlikely(::write(to_fd, &buf[0], no_of_bytes) != no_of_bytes)) LOG_ERROR("write(2) failed!"); } ::close(to_fd); } return false; } Writer::Writer(const std::string &archive_file_name, const std::string &archive_write_options, const FileType file_type) : archive_entry_(nullptr) { archive_handle_ = ::archive_write_new(); switch (file_type) { case FileType::AUTO: if (StringUtil::EndsWith(archive_file_name, ".tar")) { if (unlikely(not archive_write_options.empty())) LOG_ERROR("no write options are currently supported for the uncompressed tar format!"); ::archive_write_set_format_pax_restricted(archive_handle_); } else if (StringUtil::EndsWith(archive_file_name, ".tar.gz")) { ::archive_write_add_filter_gzip(archive_handle_); if (unlikely(::archive_write_set_options(archive_handle_, archive_write_options.c_str()) != ARCHIVE_OK)) LOG_ERROR("failed to call archive_write_set_options(3) w/ \"" + archive_write_options + "\"!"); ::archive_write_set_format_pax_restricted(archive_handle_); } else LOG_ERROR("FileType::AUTO selected but," " can't guess the file type from the given filename \"" + archive_file_name + "\"!"); break; case FileType::TAR: if (unlikely(not archive_write_options.empty())) LOG_ERROR("no write options are currently supported for the uncompressed tar format! (2)"); ::archive_write_set_format_pax_restricted(archive_handle_); break; case FileType::GZIPPED_TAR: ::archive_write_add_filter_gzip(archive_handle_); if (unlikely(::archive_write_set_options(archive_handle_, archive_write_options.c_str()) != ARCHIVE_OK)) LOG_ERROR("failed to call archive_write_set_options(3) w/ \"" + archive_write_options + "\"! (2)"); ::archive_write_set_format_pax_restricted(archive_handle_); break; } if (unlikely(::archive_write_open_filename(archive_handle_, archive_file_name.c_str()) != ARCHIVE_OK)) LOG_ERROR("archive_write_open_filename(3) failed: " + std::string(::archive_error_string(archive_handle_))); } Writer::~Writer() { if (archive_entry_ != nullptr) ::archive_entry_free(archive_entry_); if (unlikely(::archive_write_close(archive_handle_) != ARCHIVE_OK)) LOG_ERROR("archive_write_close(3) failed: " + std::string(::archive_error_string(archive_handle_))); if (unlikely(::archive_write_free(archive_handle_) != ARCHIVE_OK)) LOG_ERROR("archive_write_free(3) failed: " + std::string(::archive_error_string(archive_handle_))); } void Writer::add(const std::string &filename, std::string archive_name) { if (archive_name.empty()) archive_name = filename; if (unlikely(already_seen_archive_names_.find(archive_name) != already_seen_archive_names_.end())) LOG_ERROR("attempt to store a duplicate archive entry name \"" + archive_name + "\"!"); else already_seen_archive_names_.emplace(archive_name); struct stat stat_buf; if (unlikely(::stat(filename.c_str(), &stat_buf) != 0)) LOG_ERROR("stat(2) on \"" + filename + "\" failed: " + std::string(::strerror(errno))); if (archive_entry_ == nullptr) archive_entry_ = ::archive_entry_new(); else ::archive_entry_clear(archive_entry_); ::archive_entry_set_pathname(archive_entry_, archive_name.c_str()); ::archive_entry_copy_stat(archive_entry_, &stat_buf); int status; while ((status = ::archive_write_header(archive_handle_, archive_entry_)) == ARCHIVE_RETRY) /* Intentionally empty! */; if (unlikely(status != ARCHIVE_OK)) LOG_ERROR("archive_write_header(3) failed! (" + std::string(::archive_error_string(archive_handle_))); File input(filename, "r", File::THROW_ON_ERROR); char buffer[DEFAULT_BLOCKSIZE]; size_t count; while ((count = input.read(buffer, DEFAULT_BLOCKSIZE)) > 0) { if (count < DEFAULT_BLOCKSIZE and input.anErrorOccurred()) LOG_ERROR("error reading \"" + filename + "\" !"); if (unlikely(::archive_write_data(archive_handle_, buffer, count) != static_cast<const ssize_t>(count))) LOG_ERROR("archive_write_data(3) failed: " + std::string(::archive_error_string(archive_handle_))); } } void Writer::addEntry(const std::string &filename, const int64_t size, const mode_t mode, const EntryType entry_type) { if (archive_entry_ != nullptr) ::archive_entry_clear(archive_entry_); else archive_entry_ = ::archive_entry_new(); ::archive_entry_set_pathname(archive_entry_, filename.c_str()); ::archive_entry_set_size(archive_entry_, size); if (entry_type == EntryType::REGULAR_FILE) ::archive_entry_set_filetype(archive_entry_, AE_IFREG); else LOG_ERROR("unsupported entry type: " + std::to_string(static_cast<int>(entry_type)) + "!"); ::archive_entry_set_perm(archive_entry_, mode); ::archive_write_header(archive_handle_, archive_entry_); } void Writer::write(char * const buffer, const size_t size) { if (::archive_write_data(archive_handle_, buffer, size) < 0) LOG_ERROR("archive_write_data failed!"); } void UnpackArchive(const std::string &archive_name, const std::string &directory) { if (unlikely(not FileUtil::MakeDirectory(directory))) LOG_ERROR("failed to create directory \"" + directory + "\"!"); Reader reader(archive_name); Reader::EntryInfo file_info; while (reader.getNext(&file_info)) { if (file_info.empty()) continue; if (unlikely(not file_info.isRegularFile())) LOG_ERROR("unexpectedly, the entry \"" + file_info.getFilename() + "\" in \"" + archive_name + "\" is not a regular file!"); const std::string output_filename(directory + "/" + file_info.getFilename()); const auto output(FileUtil::OpenOutputFileOrDie(output_filename)); char buf[8192]; size_t read_count; while ((read_count = reader.read(buf, sizeof buf)) > 0) { if (unlikely(output->write(buf, read_count) != read_count)) LOG_ERROR("failed to write data to \"" + output->getPath() + "\"! (No room?)"); } } } } // namespace Archive <|endoftext|>
<commit_before>/** \file BSZUtil.h * \brief Various utility functions related to data etc. having to do w/ the BSZ. * \author Dr. Johannes Ruscheinski ([email protected]) * \author Oliver Obenland ([email protected]) * * \copyright 2017 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BSZUtil.h" #include "StringUtil.h" #include "util.h" #include "RegexMatcher.h" namespace BSZUtil { // Use the following indicators to select whether to fully delete a record or remove its local data // For a description of indicators // c.f. https://wiki.bsz-bw.de/doku.php?id=v-team:daten:datendienste:sekkor (20160426) const char FULL_RECORD_DELETE_INDICATORS[] = { 'A', 'B', 'C', 'D', 'E' }; const char LOCAL_DATA_DELETE_INDICATORS[] = { '3', '4', '5', '9' }; /* * The PPN length was increased from 9 to 10 in 2018. * The 10th character can optionally be a space */ const size_t MAX_LINE_LENGTH_OLD_WITH_ILN(25); const size_t MAX_LINE_LENGTH_OLD_NO_ILN(21); const size_t MAX_LINE_LENGTH_NEW_WITH_ILN(26); const size_t MAX_LINE_LENGTH_NEW_NO_ILN(22); const size_t PPN_LENGTH_OLD(9); const size_t PPN_LENGTH_NEW(10); const size_t PPN_START_INDEX(12); const size_t SEPARATOR_INDEX(PPN_START_INDEX - 1); void ExtractDeletionIds(File * const deletion_list, std::unordered_set <std::string> * const delete_full_record_ids, std::unordered_set <std::string> * const local_deletion_ids) { unsigned line_no(0); top_loop: while (not deletion_list->eof()) { const std::string line(StringUtil::Trim(deletion_list->getline())); ++line_no; if (unlikely(line.empty())) // Ignore empty lines. continue; const size_t line_len(line.length()); size_t ppn_len(0); if (line_len == MAX_LINE_LENGTH_OLD_WITH_ILN or line_len == MAX_LINE_LENGTH_OLD_NO_ILN) ppn_len = PPN_LENGTH_OLD; else if (line_len == MAX_LINE_LENGTH_NEW_WITH_ILN or line_len == MAX_LINE_LENGTH_NEW_NO_ILN) ppn_len = PPN_LENGTH_NEW; else { LOG_WARNING("unexpected line length " + std::to_string(line_len) + " for entry on line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!"); ppn_len = PPN_LENGTH_OLD; // fallback to the more conservative of the two lengths } for (const char indicator : FULL_RECORD_DELETE_INDICATORS) { if (line[SEPARATOR_INDEX] == indicator) { if (line_len != MAX_LINE_LENGTH_OLD_NO_ILN and line_len != MAX_LINE_LENGTH_NEW_NO_ILN) { LOG_ERROR("unexpected line length " + std::to_string(line_len) + " for non-local entry on line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!"); } delete_full_record_ids->insert(StringUtil::Trim(line.substr(PPN_START_INDEX, ppn_len))); goto top_loop; } } for (const char indicator : LOCAL_DATA_DELETE_INDICATORS) { if (line[SEPARATOR_INDEX] == indicator) { if (line_len != MAX_LINE_LENGTH_OLD_WITH_ILN and line_len != MAX_LINE_LENGTH_NEW_WITH_ILN) { LOG_ERROR("unexpected line length " + std::to_string(line_len) + " for local entry on line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!"); } local_deletion_ids->insert(StringUtil::Trim(line.substr(PPN_START_INDEX, ppn_len))); goto top_loop; } } LOG_WARNING("in \"" + deletion_list->getPath() + " \" on line #" + std::to_string(line_no) + " unknown indicator: '" + line.substr(SEPARATOR_INDEX, 1) + "'!"); } } std::string ExtractDateFromFilenameOrDie(const std::string &filename) { static const std::string DATE_EXTRACTION_REGEX(".*(\\d{6}).*"); static RegexMatcher *matcher; if (matcher == nullptr) { std::string err_msg; matcher = RegexMatcher::RegexMatcherFactory(DATE_EXTRACTION_REGEX, &err_msg); if (unlikely(not err_msg.empty())) LOG_ERROR("in ExtractDateFromFilenameOrDie: failed to compile regex: \"" + DATE_EXTRACTION_REGEX + "\"."); } if (unlikely(not matcher->matched(filename))) LOG_ERROR("in ExtractDateFromFilenameOrDie: \"" + filename + "\" failed to match the regex \"" + DATE_EXTRACTION_REGEX + "\"!"); return (*matcher)[1]; } } // namespace BSZUtil <commit_msg>Cosmetic.<commit_after>/** \file BSZUtil.h * \brief Various utility functions related to data etc. having to do w/ the BSZ. * \author Dr. Johannes Ruscheinski ([email protected]) * \author Oliver Obenland ([email protected]) * * \copyright 2017,2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BSZUtil.h" #include "StringUtil.h" #include "util.h" #include "RegexMatcher.h" namespace BSZUtil { // Use the following indicators to select whether to fully delete a record or remove its local data // For a description of indicators // c.f. https://wiki.bsz-bw.de/doku.php?id=v-team:daten:datendienste:sekkor (20160426) const char FULL_RECORD_DELETE_INDICATORS[] = { 'A', 'B', 'C', 'D', 'E' }; const char LOCAL_DATA_DELETE_INDICATORS[] = { '3', '4', '5', '9' }; /* * The PPN length was increased from 9 to 10 in 2018. * The 10th character can optionally be a space */ const size_t MAX_LINE_LENGTH_OLD_WITH_ILN(25); const size_t MAX_LINE_LENGTH_OLD_NO_ILN(21); const size_t MAX_LINE_LENGTH_NEW_WITH_ILN(26); const size_t MAX_LINE_LENGTH_NEW_NO_ILN(22); const size_t PPN_LENGTH_OLD(9); const size_t PPN_LENGTH_NEW(10); const size_t PPN_START_INDEX(12); const size_t SEPARATOR_INDEX(PPN_START_INDEX - 1); void ExtractDeletionIds(File * const deletion_list, std::unordered_set <std::string> * const delete_full_record_ids, std::unordered_set <std::string> * const local_deletion_ids) { unsigned line_no(0); top_loop: while (not deletion_list->eof()) { const std::string line(StringUtil::Trim(deletion_list->getline())); ++line_no; if (unlikely(line.empty())) // Ignore empty lines. continue; const size_t line_len(line.length()); size_t ppn_len(0); if (line_len == MAX_LINE_LENGTH_OLD_WITH_ILN or line_len == MAX_LINE_LENGTH_OLD_NO_ILN) ppn_len = PPN_LENGTH_OLD; else if (line_len == MAX_LINE_LENGTH_NEW_WITH_ILN or line_len == MAX_LINE_LENGTH_NEW_NO_ILN) ppn_len = PPN_LENGTH_NEW; else { LOG_WARNING("unexpected line length " + std::to_string(line_len) + " for entry on line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!"); ppn_len = PPN_LENGTH_OLD; // fallback to the more conservative of the two lengths } for (const char indicator : FULL_RECORD_DELETE_INDICATORS) { if (line[SEPARATOR_INDEX] == indicator) { if (line_len != MAX_LINE_LENGTH_OLD_NO_ILN and line_len != MAX_LINE_LENGTH_NEW_NO_ILN) { LOG_ERROR("unexpected line length " + std::to_string(line_len) + " for non-local entry on line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!"); } delete_full_record_ids->insert(StringUtil::Trim(line.substr(PPN_START_INDEX, ppn_len))); goto top_loop; } } for (const char indicator : LOCAL_DATA_DELETE_INDICATORS) { if (line[SEPARATOR_INDEX] == indicator) { if (line_len != MAX_LINE_LENGTH_OLD_WITH_ILN and line_len != MAX_LINE_LENGTH_NEW_WITH_ILN) { LOG_ERROR("unexpected line length " + std::to_string(line_len) + " for local entry on line " + std::to_string(line_no) + " in deletion list file \"" + deletion_list->getPath() + "\"!"); } local_deletion_ids->insert(StringUtil::Trim(line.substr(PPN_START_INDEX, ppn_len))); goto top_loop; } } LOG_WARNING("in \"" + deletion_list->getPath() + " \" on line #" + std::to_string(line_no) + " unknown indicator: '" + line.substr(SEPARATOR_INDEX, 1) + "'!"); } } std::string ExtractDateFromFilenameOrDie(const std::string &filename) { static const std::string DATE_EXTRACTION_REGEX(".*(\\d{6}).*"); static RegexMatcher *matcher; if (matcher == nullptr) { std::string err_msg; matcher = RegexMatcher::RegexMatcherFactory(DATE_EXTRACTION_REGEX, &err_msg); if (unlikely(not err_msg.empty())) LOG_ERROR("in ExtractDateFromFilenameOrDie: failed to compile regex: \"" + DATE_EXTRACTION_REGEX + "\"."); } if (unlikely(not matcher->matched(filename))) LOG_ERROR("in ExtractDateFromFilenameOrDie: \"" + filename + "\" failed to match the regex \"" + DATE_EXTRACTION_REGEX + "\"!"); return (*matcher)[1]; } } // namespace BSZUtil <|endoftext|>
<commit_before> // Copyright (c) 2013-2014 Quanta Research Cambridge, Inc. // 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. #include <assert.h> #include "dmaManager.h" #include "MMURequest.h" #include "MMUIndication.h" #include "MemServerRequest.h" #include "MemServerIndication.h" #define PLATFORM_TILE 0 class PortalPoller; int mmu_error_limit = 20; int mem_error_limit = 20; const char *dmaErrors[] = { "None", "SGL Id out of range for read", "SGL Id out of range for write", "MMU out of range for read", "MMU out of range for write", "Offset out of range", "SGL Id invalid", "Tile tag out of range" }; class MMUIndication : public MMUIndicationWrapper { DmaManager *portalMemory; public: MMUIndication(DmaManager *pm, unsigned int id, int tile=PLATFORM_TILE) : MMUIndicationWrapper(id,tile), portalMemory(pm) {} MMUIndication(DmaManager *pm, unsigned int id, PortalTransportFunctions *item, void *param) : MMUIndicationWrapper(id, item, param), portalMemory(pm) {} virtual void configResp(uint32_t pointer){ portalMemory->confResp(pointer); } virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) { fprintf(stderr, "MMUIndication::error(code=0x%x:%s, pointer=0x%x, offset=0x%" PRIx64 " extra=0x%" PRIx64 "\n", code, dmaErrors[code], pointer, offset, extra); if (--mmu_error_limit < 0) exit(-1); } virtual void idResponse(uint32_t sglId){ portalMemory->sglIdResp(sglId); } }; class MemServerIndication : public MemServerIndicationWrapper { MemServerRequestProxy *memServerRequestProxy; sem_t mtSem; uint64_t mtCnt; void init(){ if (sem_init(&mtSem, 0, 0)) PORTAL_PRINTF("MemServerIndication::init failed to init mtSem\n"); } public: MemServerIndication(unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(NULL) {init();} MemServerIndication(MemServerRequestProxy *p, unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(p) {init();} virtual void addrResponse(uint64_t physAddr){ fprintf(stderr, "DmaIndication::addrResponse(physAddr=%" PRIx64 ")\n", physAddr); } virtual void reportStateDbg(const DmaDbgRec rec){ fprintf(stderr, "MemServerIndication::reportStateDbg: {x:%08x y:%08x z:%08x w:%08x}\n", rec.x,rec.y,rec.z,rec.w); } virtual void reportMemoryTraffic(uint64_t words){ //fprintf(stderr, "reportMemoryTraffic: words=%" PRIx64 "\n", words); mtCnt = words; sem_post(&mtSem); } virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) { fprintf(stderr, "MemServerIndication::error(code=%x, pointer=%x, offset=%" PRIx64 " extra=%" PRIx64 "\n", code, pointer, offset, extra); if (--mem_error_limit < 0) exit(-1); } uint64_t receiveMemoryTraffic(){ sem_wait(&mtSem); return mtCnt; } uint64_t getMemoryTraffic(const ChannelType rc){ assert(memServerRequestProxy); memServerRequestProxy->memoryTraffic(rc); return receiveMemoryTraffic(); } }; static MemServerRequestProxy *hostMemServerRequest; static MemServerIndication *hostMemServerIndication; static MMUIndication *mmuIndication; static DmaManager *dma; static pthread_once_t once_control = PTHREAD_ONCE_INIT; void platformInitOnce(void) { hostMemServerRequest = new MemServerRequestProxy(PlatformIfcNames_MemServerRequestS2H, PLATFORM_TILE); MMURequestProxy *dmap = new MMURequestProxy(PlatformIfcNames_MMURequestS2H, PLATFORM_TILE); dma = new DmaManager(dmap); hostMemServerIndication = new MemServerIndication(hostMemServerRequest, PlatformIfcNames_MemServerIndicationH2S, PLATFORM_TILE); mmuIndication = new MMUIndication(dma, PlatformIfcNames_MMUIndicationH2S, PLATFORM_TILE); #ifdef FPGA0_CLOCK_FREQ long req_freq = FPGA0_CLOCK_FREQ; long freq = 0; setClockFrequency(0, req_freq, &freq); fprintf(stderr, "Requested FCLK[0]=%ld actually %ld\n", req_freq, freq); #endif } DmaManager *platformInit(void) { pthread_once(&once_control, platformInitOnce); return dma; } void platformStatistics(void) { uint64_t cycles = portalTimerLap(0); hostMemServerRequest->memoryTraffic(ChannelType_Read); uint64_t read_beats = hostMemServerIndication->receiveMemoryTraffic(); float read_util = (float)read_beats/(float)cycles; hostMemServerRequest->memoryTraffic(ChannelType_Write); uint64_t write_beats = hostMemServerIndication->receiveMemoryTraffic(); float write_util = (float)write_beats/(float)cycles; fprintf(stderr, " read_beats: %lld\n", (long long)read_beats); fprintf(stderr, " write_beats: %lld\n", (long long)write_beats); fprintf(stderr, " cycles: %lld\n", (long long)cycles); fprintf(stderr, "memory utilization (beats/cycle): read %f write %f\n", read_util, write_util); } <commit_msg>set the requested clock frequency on zynq boards<commit_after> // Copyright (c) 2013-2014 Quanta Research Cambridge, Inc. // 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. #include <assert.h> #include "dmaManager.h" #include "MMURequest.h" #include "MMUIndication.h" #include "MemServerRequest.h" #include "MemServerIndication.h" #define PLATFORM_TILE 0 class PortalPoller; int mmu_error_limit = 20; int mem_error_limit = 20; const char *dmaErrors[] = { "None", "SGL Id out of range for read", "SGL Id out of range for write", "MMU out of range for read", "MMU out of range for write", "Offset out of range", "SGL Id invalid", "Tile tag out of range" }; class MMUIndication : public MMUIndicationWrapper { DmaManager *portalMemory; public: MMUIndication(DmaManager *pm, unsigned int id, int tile=PLATFORM_TILE) : MMUIndicationWrapper(id,tile), portalMemory(pm) {} MMUIndication(DmaManager *pm, unsigned int id, PortalTransportFunctions *item, void *param) : MMUIndicationWrapper(id, item, param), portalMemory(pm) {} virtual void configResp(uint32_t pointer){ portalMemory->confResp(pointer); } virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) { fprintf(stderr, "MMUIndication::error(code=0x%x:%s, pointer=0x%x, offset=0x%" PRIx64 " extra=0x%" PRIx64 "\n", code, dmaErrors[code], pointer, offset, extra); if (--mmu_error_limit < 0) exit(-1); } virtual void idResponse(uint32_t sglId){ portalMemory->sglIdResp(sglId); } }; class MemServerIndication : public MemServerIndicationWrapper { MemServerRequestProxy *memServerRequestProxy; sem_t mtSem; uint64_t mtCnt; void init(){ if (sem_init(&mtSem, 0, 0)) PORTAL_PRINTF("MemServerIndication::init failed to init mtSem\n"); } public: MemServerIndication(unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(NULL) {init();} MemServerIndication(MemServerRequestProxy *p, unsigned int id, int tile=PLATFORM_TILE) : MemServerIndicationWrapper(id,tile), memServerRequestProxy(p) {init();} virtual void addrResponse(uint64_t physAddr){ fprintf(stderr, "DmaIndication::addrResponse(physAddr=%" PRIx64 ")\n", physAddr); } virtual void reportStateDbg(const DmaDbgRec rec){ fprintf(stderr, "MemServerIndication::reportStateDbg: {x:%08x y:%08x z:%08x w:%08x}\n", rec.x,rec.y,rec.z,rec.w); } virtual void reportMemoryTraffic(uint64_t words){ //fprintf(stderr, "reportMemoryTraffic: words=%" PRIx64 "\n", words); mtCnt = words; sem_post(&mtSem); } virtual void error (uint32_t code, uint32_t pointer, uint64_t offset, uint64_t extra) { fprintf(stderr, "MemServerIndication::error(code=%x, pointer=%x, offset=%" PRIx64 " extra=%" PRIx64 "\n", code, pointer, offset, extra); if (--mem_error_limit < 0) exit(-1); } uint64_t receiveMemoryTraffic(){ sem_wait(&mtSem); return mtCnt; } uint64_t getMemoryTraffic(const ChannelType rc){ assert(memServerRequestProxy); memServerRequestProxy->memoryTraffic(rc); return receiveMemoryTraffic(); } }; static MemServerRequestProxy *hostMemServerRequest; static MemServerIndication *hostMemServerIndication; static MMUIndication *mmuIndication; static DmaManager *dma; static pthread_once_t once_control = PTHREAD_ONCE_INIT; void platformInitOnce(void) { hostMemServerRequest = new MemServerRequestProxy(PlatformIfcNames_MemServerRequestS2H, PLATFORM_TILE); MMURequestProxy *dmap = new MMURequestProxy(PlatformIfcNames_MMURequestS2H, PLATFORM_TILE); dma = new DmaManager(dmap); hostMemServerIndication = new MemServerIndication(hostMemServerRequest, PlatformIfcNames_MemServerIndicationH2S, PLATFORM_TILE); mmuIndication = new MMUIndication(dma, PlatformIfcNames_MMUIndicationH2S, PLATFORM_TILE); #ifdef MainClockPeriod long req_freq = (long)(1e9 / MainClockPeriod); long freq = 0; setClockFrequency(0, req_freq, &freq); fprintf(stderr, "Requested FCLK[0]=%ld actually %ld\n", req_freq, freq); #endif } DmaManager *platformInit(void) { pthread_once(&once_control, platformInitOnce); return dma; } void platformStatistics(void) { uint64_t cycles = portalTimerLap(0); hostMemServerRequest->memoryTraffic(ChannelType_Read); uint64_t read_beats = hostMemServerIndication->receiveMemoryTraffic(); float read_util = (float)read_beats/(float)cycles; hostMemServerRequest->memoryTraffic(ChannelType_Write); uint64_t write_beats = hostMemServerIndication->receiveMemoryTraffic(); float write_util = (float)write_beats/(float)cycles; fprintf(stderr, " read_beats: %lld\n", (long long)read_beats); fprintf(stderr, " write_beats: %lld\n", (long long)write_beats); fprintf(stderr, " cycles: %lld\n", (long long)cycles); fprintf(stderr, "memory utilization (beats/cycle): read %f write %f\n", read_util, write_util); } <|endoftext|>
<commit_before>/** * @cond ___LICENSE___ * * Copyright (c) 2017 Zefiros Software. * * 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. * * @endcond */ #include "plot/surfPlot.h" #include "plot/properties/heatMapProperties.h" PLOTLIB_INLINE SurfPlot::SurfPlot( const PVec &x, const std::vector<PVec> &y, const std::vector<PVec> &z ) : SurfPlot() { mStream << "X=["; for ( auto &Y : y ) { mStream << this->ToArray( x ) << ","; } mStream << "]\n" << "Y=["; for ( auto &Y : y ) { mStream << this->ToArray( Y ) << ","; } mStream << "]\n" << "Z=["; for ( auto &Z : z ) { mStream << this->ToArray( Z ) << ","; } mStream << "]\n" << "surf = ax.plot_surface( X, Y, Z"; } PLOTLIB_INLINE SurfPlot::SurfPlot( const PVec &x, const PVec &y, const std::vector<PVec> &z ) : SurfPlot() { mStream << "X=["; for ( auto &Y : y.GetData() ) { mStream << this->ToArray( x ) << ","; } mStream << "]\n" << "Y=["; for ( auto &Y : y.GetData() ) { mStream << this->ToArray( std::vector<double>( x.GetSize(), Y ) ) << ","; } mStream << "]\n" << "Z=["; for ( auto &Z : z ) { mStream << this->ToArray( Z ) << ","; } mStream << "]\n" << "surf = ax.plot_surface( X, Y, Z"; } PLOTLIB_INLINE SurfPlot::SurfPlot( const PMat &x, const PMat &y, const PMat &z ) : SurfPlot() { mStream << "X=" << this->ToArray( x ) << "\n" << "Y=" << this->ToArray( y ) << "\n" << "Z=" << this->ToArray( z ) << "\n" << "surf = ax.plot_surface( X, Y, Z"; } PLOTLIB_INLINE std::string SurfPlot::ToString() { if ( !mHasColourMap ) { SetColourMap( ColourMap::Diverging::Coolwarm ); } return mStream.str() + ", antialiased = True )\n" + ( mShowColourBar ? "fig.colorbar( surf, shrink = 0.5, aspect = 5 )" : "" ); } PLOTLIB_INLINE SurfPlot &SurfPlot::SetColourMap( const ColourMap &pallet ) { this->AddArgument( "cmap", pallet.ToString() ); mHasColourMap = true; return *this; } PLOTLIB_INLINE SurfPlot &SurfPlot::ColourBar( bool bar ) { mShowColourBar = bar; return *this; } SurfPlot::SurfPlot() : mHasColourMap( false ), mShowColourBar( false ) { mStream << "\nfrom mpl_toolkits.mplot3d import Axes3D\n" << "from matplotlib import cm\n\n" << "fig = plt.figure()\n" << "ax = fig.gca(projection='3d')\n"; } <commit_msg>Fixed x repetition in surfplot<commit_after>/** * @cond ___LICENSE___ * * Copyright (c) 2017 Zefiros Software. * * 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. * * @endcond */ #include "plot/surfPlot.h" #include "plot/properties/heatMapProperties.h" PLOTLIB_INLINE SurfPlot::SurfPlot( const PVec &x, const std::vector<PVec> &y, const std::vector<PVec> &z ) : SurfPlot() { mStream << "X=["; for ( auto &Y : y ) { mStream << this->ToArray( x ) << ","; } mStream << "]\n" << "Y=["; for ( auto &Y : y ) { mStream << this->ToArray( Y ) << ","; } mStream << "]\n" << "Z=["; for ( auto &Z : z ) { mStream << this->ToArray( Z ) << ","; } mStream << "]\n" << "surf = ax.plot_surface( X, Y, Z"; } PLOTLIB_INLINE SurfPlot::SurfPlot( const PVec &x, const PVec &y, const std::vector<PVec> &z ) : SurfPlot() { mStream << "X=["; for ( auto &Z : z ) { mStream << this->ToArray( x ) << ","; } mStream << "]\n" << "Y=["; for ( auto &Y : y.GetData() ) { mStream << this->ToArray( std::vector<double>( x.GetSize(), Y ) ) << ","; } mStream << "]\n" << "Z=["; for ( auto &Z : z ) { mStream << this->ToArray( Z ) << ","; } mStream << "]\n" << "surf = ax.plot_surface( X, Y, Z"; } PLOTLIB_INLINE SurfPlot::SurfPlot( const PMat &x, const PMat &y, const PMat &z ) : SurfPlot() { mStream << "X=" << this->ToArray( x ) << "\n" << "Y=" << this->ToArray( y ) << "\n" << "Z=" << this->ToArray( z ) << "\n" << "surf = ax.plot_surface( X, Y, Z"; } PLOTLIB_INLINE std::string SurfPlot::ToString() { if ( !mHasColourMap ) { SetColourMap( ColourMap::Diverging::Coolwarm ); } return mStream.str() + ", antialiased = True )\n" + ( mShowColourBar ? "fig.colorbar( surf, shrink = 0.5, aspect = 5 )" : "" ); } PLOTLIB_INLINE SurfPlot &SurfPlot::SetColourMap( const ColourMap &pallet ) { this->AddArgument( "cmap", pallet.ToString() ); mHasColourMap = true; return *this; } PLOTLIB_INLINE SurfPlot &SurfPlot::ColourBar( bool bar ) { mShowColourBar = bar; return *this; } SurfPlot::SurfPlot() : mHasColourMap( false ), mShowColourBar( false ) { mStream << "\nfrom mpl_toolkits.mplot3d import Axes3D\n" << "from matplotlib import cm\n\n" << "fig = plt.figure()\n" << "ax = fig.gca(projection='3d')\n"; } <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include "intersection.h" namespace py = pybind11; namespace jtrace { void pyExportIntersection(py::module &m) { py::class_<Intersection>(m, "Intersection") .def_readonly("point", &Intersection::point) .def_readonly("surfaceNormal", &Intersection::surfaceNormal) .def("__repr__", &Intersection::repr) .def_readonly("t", &Intersection::t) .def_readonly("point", &Intersection::point) .def_readonly("surfaceNormal", &Intersection::surfaceNormal) .def("reflectedRay", &Intersection::reflectedRay); } } <commit_msg>Clean up pysrc/intersection.cpp<commit_after>#include <pybind11/pybind11.h> #include "intersection.h" namespace py = pybind11; namespace jtrace { void pyExportIntersection(py::module &m) { py::class_<Intersection>(m, "Intersection") .def_readonly("t", &Intersection::t) .def_readonly("point", &Intersection::point) .def_readonly("surfaceNormal", &Intersection::surfaceNormal) .def("__repr__", &Intersection::repr) .def("reflectedRay", &Intersection::reflectedRay); } } <|endoftext|>
<commit_before> #include "src/utils/md5.h" #include "others/mbedtls/md5.h" namespace modsecurity { namespace Utils { std::string Md5::hexdigest(std::string& input) { unsigned char digest[16]; mbedtls_md5(reinterpret_cast<const unsigned char *>(input.c_str()), input.size(), digest); char buf[32]; for (int i = 0; i < 16; i++) { sprintf(buf+i*2, "%02x", digest[i]); } return std::string(buf, 32); } std::string Md5::digest(std::string& input) { unsigned char output[16]; std::string ret; mbedtls_md5(reinterpret_cast<const unsigned char *>(input.c_str()), input.size(), output); ret.assign(reinterpret_cast<const char *>(output), 16); return ret; } } // namespace Utils } // namespace modsecurity <commit_msg>Fixed buffer overflow in Utils::Md5::hexdigest()<commit_after> #include "src/utils/md5.h" #include "others/mbedtls/md5.h" namespace modsecurity { namespace Utils { std::string Md5::hexdigest(std::string& input) { unsigned char digest[16]; mbedtls_md5(reinterpret_cast<const unsigned char *>(input.c_str()), input.size(), digest); char buf[33]; for (int i = 0; i < 16; i++) { sprintf(buf+i*2, "%02x", digest[i]); } return std::string(buf, 32); } std::string Md5::digest(std::string& input) { unsigned char output[16]; std::string ret; mbedtls_md5(reinterpret_cast<const unsigned char *>(input.c_str()), input.size(), output); ret.assign(reinterpret_cast<const char *>(output), 16); return ret; } } // namespace Utils } // namespace modsecurity <|endoftext|>
<commit_before>/* * Copyright 2009-2018 The VOTCA Development Team * (http://www.votca.org) * * 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 <vector> #include <string> #include <votca/xtp/polarsite.h> #include <votca/xtp/apolarsite.h> #include <votca/xtp/atom.h> #include <votca/xtp/fragment.h> #include <votca/xtp/segment.h> #include <votca/xtp/segmenttype.h> #include <votca/tools/vec.h> using namespace std; using namespace votca::tools; namespace votca { namespace xtp { /// Default constructor Segment::Segment(int id, string name) : _id(id), _name(name), _has_e(false), _has_h(false), _has_s(false), _has_t(false) { _eMpoles.resize(5); } // This constructor creates a copy of the stencil segment, without // adding it to any containers further up in the hierarchy; i.e. the topology // and molecules will neither know about the existence of this segment, nor // be able to access it. Used for creating the ghost in PB corrected pairs. Segment::Segment(Segment *stencil) : _id(stencil->getId()), _name(stencil->getName() + "_ghost"), _typ(stencil->getType()), _top(NULL), _mol(NULL), _CoM(stencil->getPos()), _has_e(false), _has_h(false), _has_s(false), _has_t(false) { _eMpoles.resize(5); vector<Fragment *>::iterator fit; for (fit = stencil->Fragments().begin(); fit < stencil->Fragments().end(); fit++) { Fragment *newFrag = new Fragment(*fit); this->AddFragment(newFrag); vector<Atom *>::iterator ait; for (ait = newFrag->Atoms().begin(); ait < newFrag->Atoms().end(); ait++) { this->AddAtom(*ait); } } } Segment::~Segment() { vector<Fragment *>::iterator fragit; for (fragit = this->Fragments().begin(); fragit < this->Fragments().end(); fragit++) { delete *fragit; } _fragments.clear(); _atoms.clear(); _eMpoles.clear(); _polarSites.clear(); } void Segment::TranslateBy(const vec &shift) { _CoM = _CoM + shift; vector<Fragment *>::iterator fit; for (fit = _fragments.begin(); fit < _fragments.end(); fit++) { (*fit)->TranslateBy(shift); } } void Segment::setHasState(bool yesno, int state) { if (state == -1) { _has_e = yesno; } else if (state == +1) { _has_h = yesno; } else if (state == +2) { _has_s = yesno; } else if (state == +3) { _has_t = yesno; } else { throw runtime_error(" ERROR CODE whe__00e11h__"); } } bool Segment::hasState(int state) { bool result; if (state == -1) { result = _has_e; } else if (state == +1) { result = _has_h; } else if (state == +2) { result = _has_s; } else if (state == +3) { result = _has_t; } else { throw runtime_error(" ERROR CODE whe__00s11o__"); } return result; } void Segment::setOcc(double occ, int e_h_s_t) { if (e_h_s_t == -1) { _occ_e = occ; } else if (e_h_s_t == +1) { _occ_h = occ; } else if (e_h_s_t == +2) { _occ_s = occ; } else if (e_h_s_t == +3) { _occ_t = occ; } else { throw runtime_error(" ERROR CODE whe__00s11o__"); } } double Segment::getOcc(int e_h_s_t) { double result; if (e_h_s_t == -1) { result = _occ_e; } else if (e_h_s_t == +1) { result = _occ_h; } else if (e_h_s_t == +2) { result = _occ_s; } else if (e_h_s_t == +3) { result = _occ_t; } else { throw runtime_error( " ERROR CODE whe__00s11o__"); // blabla what do I do here? } return result; } void Segment::setU_cC_nN(double dU, int state) { if (state == -1) { _U_cC_nN_e = dU; } else if (state == +1) { _U_cC_nN_h = dU; } else { throw runtime_error(" ERROR CODE whe__00u11a__"); } } void Segment::setU_nC_nN(double dU, int state) { if (state == -1) { _U_nC_nN_e = dU; } else if (state == +1) { _U_nC_nN_h = dU; } else { throw runtime_error(" ERROR CODE whe__00u11b__"); } } void Segment::setU_cN_cC(double dU, int state) { if (state == -1) { _U_cN_cC_e = dU; } else if (state == +1) { _U_cN_cC_h = dU; } else { throw runtime_error(" ERROR CODE whe__00u11c__"); } } void Segment::setU_xX_nN(double dU, int state) { if (state == +2) { _U_xX_nN_s = dU; } else if (state == +3) { _U_xX_nN_t = dU; } else { throw runtime_error( " ERROR CODE whe__00u11d__"); // blabla?? What do I do here? } } void Segment::setU_nX_nN(double dU, int state) { if (state == +2) { _U_nX_nN_s = dU; } else if (state == +3) { _U_nX_nN_t = dU; } else { throw runtime_error( " ERROR CODE whe__00u11d__"); // blabla?? What do I do here? } } void Segment::setU_xN_xX(double dU, int state) { if (state == +2) { _U_xN_xX_s = dU; } else if (state == +3) { _U_xN_xX_t = dU; } else { throw runtime_error( " ERROR CODE whe__00u11d__"); // blabla?? What do I do here? } } const double &Segment::getU_xX_nN(int state) { return (state == +3) ? _U_xX_nN_t : _U_xX_nN_s; } const double &Segment::getU_nX_nN(int state) { return (state == +3) ? _U_nX_nN_t : _U_nX_nN_s; } const double &Segment::getU_xN_xX(int state) { return (state == +3) ? _U_xN_xX_t : _U_xN_xX_s; } const double &Segment::getU_cC_nN(int state) { return (state == -1) ? _U_cC_nN_e : _U_cC_nN_h; } const double &Segment::getU_nC_nN(int state) { return (state == -1) ? _U_nC_nN_e : _U_nC_nN_h; } const double &Segment::getU_cN_cC(int state) { return (state == -1) ? _U_cN_cC_e : _U_cN_cC_h; } double Segment::getSiteEnergy(int state) { double result; if (state == -1) { result = getEMpoles(state) + _U_cC_nN_e; } else if (state == +1) { result = getEMpoles(state) + _U_cC_nN_h; } else if (state == +2) { result = getEMpoles(state) + _U_xX_nN_s; } else if (state == +3) { result = getEMpoles(state) + _U_xX_nN_t; } else { throw runtime_error( " ERROR CODE whe__00s11o__"); // blabla what do I do here? } return result; } void Segment::setEMpoles(int state, double energy) { _hasChrgState.resize(5); _hasChrgState[state + 1] = true; _eMpoles[state + 1] = energy; } double Segment::getEMpoles(int state) { return _eMpoles[state + 1] - _eMpoles[1]; } void Segment::AddFragment(Fragment *fragment) { _fragments.push_back(fragment); fragment->setSegment(this); } void Segment::AddAtom(Atom *atom) { _atoms.push_back(atom); atom->setSegment(this); } void Segment::AddPolarSite(PolarSite *pole) { _polarSites.push_back(pole); pole->setSegment(this); } void Segment::AddAPolarSite(APolarSite *pole) { _apolarSites.push_back(pole); pole->setSegment(this); } void Segment::calcPos() { vec pos = vec(0, 0, 0); double totWeight = 0.0; for (unsigned int i = 0; i < _atoms.size(); i++) { pos += _atoms[i]->getPos() * _atoms[i]->getWeight(); totWeight += _atoms[i]->getWeight(); } _CoM = pos / totWeight; } void Segment::calcApproxSize() { _approxsize = 0.0; tools::vec min = vec(numeric_limits<double>::max()); tools::vec max = vec(numeric_limits<double>::min()); vector<Fragment *>::iterator fragit1; for (fragit1 = Fragments().begin(); fragit1 < Fragments().end(); fragit1++) { const tools::vec &pos = (*fragit1)->getPos(); if (pos.getX() > max.getX()) { max.x() = pos.getX(); } else if (pos.getX() < min.getX()) { min.x() = pos.getX(); } if (pos.getY() > max.getY()) { max.y() = pos.getY(); } else if (pos.getY() < min.getY()) { min.y() = pos.getY(); } if (pos.getZ() > max.getZ()) { max.z() = pos.getZ(); } else if (pos.getZ() < min.getZ()) { min.z() = pos.getZ(); } } _approxsize = abs(max - min); return; } void Segment::Rigidify() { if (this->getType()->canRigidify()) { // Establish which atoms to use to define local frame vector<Fragment *>::iterator fit; for (fit = this->Fragments().begin(); fit < this->Fragments().end(); fit++) { (*fit)->Rigidify(); } } else { return; } } } } <commit_msg>removed use of polar site from segment.cc<commit_after>/* * Copyright 2009-2018 The VOTCA Development Team * (http://www.votca.org) * * 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 <vector> #include <string> #include <votca/xtp/apolarsite.h> #include <votca/xtp/atom.h> #include <votca/xtp/fragment.h> #include <votca/xtp/segment.h> #include <votca/xtp/segmenttype.h> #include <votca/tools/vec.h> using namespace std; using namespace votca::tools; namespace votca { namespace xtp { /// Default constructor Segment::Segment(int id, string name) : _id(id), _name(name), _has_e(false), _has_h(false), _has_s(false), _has_t(false) { _eMpoles.resize(5); } // This constructor creates a copy of the stencil segment, without // adding it to any containers further up in the hierarchy; i.e. the topology // and molecules will neither know about the existence of this segment, nor // be able to access it. Used for creating the ghost in PB corrected pairs. Segment::Segment(Segment *stencil) : _id(stencil->getId()), _name(stencil->getName() + "_ghost"), _typ(stencil->getType()), _top(NULL), _mol(NULL), _CoM(stencil->getPos()), _has_e(false), _has_h(false), _has_s(false), _has_t(false) { _eMpoles.resize(5); vector<Fragment *>::iterator fit; for (fit = stencil->Fragments().begin(); fit < stencil->Fragments().end(); fit++) { Fragment *newFrag = new Fragment(*fit); this->AddFragment(newFrag); vector<Atom *>::iterator ait; for (ait = newFrag->Atoms().begin(); ait < newFrag->Atoms().end(); ait++) { this->AddAtom(*ait); } } } Segment::~Segment() { vector<Fragment *>::iterator fragit; for (fragit = this->Fragments().begin(); fragit < this->Fragments().end(); fragit++) { delete *fragit; } _fragments.clear(); _atoms.clear(); _eMpoles.clear(); _apolarSites.clear(); } void Segment::TranslateBy(const vec &shift) { _CoM = _CoM + shift; vector<Fragment *>::iterator fit; for (fit = _fragments.begin(); fit < _fragments.end(); fit++) { (*fit)->TranslateBy(shift); } } void Segment::setHasState(bool yesno, int state) { if (state == -1) { _has_e = yesno; } else if (state == +1) { _has_h = yesno; } else if (state == +2) { _has_s = yesno; } else if (state == +3) { _has_t = yesno; } else { throw runtime_error(" ERROR CODE whe__00e11h__"); } } bool Segment::hasState(int state) { bool result; if (state == -1) { result = _has_e; } else if (state == +1) { result = _has_h; } else if (state == +2) { result = _has_s; } else if (state == +3) { result = _has_t; } else { throw runtime_error(" ERROR CODE whe__00s11o__"); } return result; } void Segment::setOcc(double occ, int e_h_s_t) { if (e_h_s_t == -1) { _occ_e = occ; } else if (e_h_s_t == +1) { _occ_h = occ; } else if (e_h_s_t == +2) { _occ_s = occ; } else if (e_h_s_t == +3) { _occ_t = occ; } else { throw runtime_error(" ERROR CODE whe__00s11o__"); } } double Segment::getOcc(int e_h_s_t) { double result; if (e_h_s_t == -1) { result = _occ_e; } else if (e_h_s_t == +1) { result = _occ_h; } else if (e_h_s_t == +2) { result = _occ_s; } else if (e_h_s_t == +3) { result = _occ_t; } else { throw runtime_error( " ERROR CODE whe__00s11o__"); // blabla what do I do here? } return result; } void Segment::setU_cC_nN(double dU, int state) { if (state == -1) { _U_cC_nN_e = dU; } else if (state == +1) { _U_cC_nN_h = dU; } else { throw runtime_error(" ERROR CODE whe__00u11a__"); } } void Segment::setU_nC_nN(double dU, int state) { if (state == -1) { _U_nC_nN_e = dU; } else if (state == +1) { _U_nC_nN_h = dU; } else { throw runtime_error(" ERROR CODE whe__00u11b__"); } } void Segment::setU_cN_cC(double dU, int state) { if (state == -1) { _U_cN_cC_e = dU; } else if (state == +1) { _U_cN_cC_h = dU; } else { throw runtime_error(" ERROR CODE whe__00u11c__"); } } void Segment::setU_xX_nN(double dU, int state) { if (state == +2) { _U_xX_nN_s = dU; } else if (state == +3) { _U_xX_nN_t = dU; } else { throw runtime_error( " ERROR CODE whe__00u11d__"); // blabla?? What do I do here? } } void Segment::setU_nX_nN(double dU, int state) { if (state == +2) { _U_nX_nN_s = dU; } else if (state == +3) { _U_nX_nN_t = dU; } else { throw runtime_error( " ERROR CODE whe__00u11d__"); // blabla?? What do I do here? } } void Segment::setU_xN_xX(double dU, int state) { if (state == +2) { _U_xN_xX_s = dU; } else if (state == +3) { _U_xN_xX_t = dU; } else { throw runtime_error( " ERROR CODE whe__00u11d__"); // blabla?? What do I do here? } } const double &Segment::getU_xX_nN(int state) { return (state == +3) ? _U_xX_nN_t : _U_xX_nN_s; } const double &Segment::getU_nX_nN(int state) { return (state == +3) ? _U_nX_nN_t : _U_nX_nN_s; } const double &Segment::getU_xN_xX(int state) { return (state == +3) ? _U_xN_xX_t : _U_xN_xX_s; } const double &Segment::getU_cC_nN(int state) { return (state == -1) ? _U_cC_nN_e : _U_cC_nN_h; } const double &Segment::getU_nC_nN(int state) { return (state == -1) ? _U_nC_nN_e : _U_nC_nN_h; } const double &Segment::getU_cN_cC(int state) { return (state == -1) ? _U_cN_cC_e : _U_cN_cC_h; } double Segment::getSiteEnergy(int state) { double result; if (state == -1) { result = getEMpoles(state) + _U_cC_nN_e; } else if (state == +1) { result = getEMpoles(state) + _U_cC_nN_h; } else if (state == +2) { result = getEMpoles(state) + _U_xX_nN_s; } else if (state == +3) { result = getEMpoles(state) + _U_xX_nN_t; } else { throw runtime_error( " ERROR CODE whe__00s11o__"); // blabla what do I do here? } return result; } void Segment::setEMpoles(int state, double energy) { _hasChrgState.resize(5); _hasChrgState[state + 1] = true; _eMpoles[state + 1] = energy; } double Segment::getEMpoles(int state) { return _eMpoles[state + 1] - _eMpoles[1]; } void Segment::AddFragment(Fragment *fragment) { _fragments.push_back(fragment); fragment->setSegment(this); } void Segment::AddAtom(Atom *atom) { _atoms.push_back(atom); atom->setSegment(this); } void Segment::AddAPolarSite(APolarSite *pole) { _apolarSites.push_back(pole); pole->setSegment(this); } void Segment::calcPos() { vec pos = vec(0, 0, 0); double totWeight = 0.0; for (unsigned int i = 0; i < _atoms.size(); i++) { pos += _atoms[i]->getPos() * _atoms[i]->getWeight(); totWeight += _atoms[i]->getWeight(); } _CoM = pos / totWeight; } void Segment::calcApproxSize() { _approxsize = 0.0; tools::vec min = vec(numeric_limits<double>::max()); tools::vec max = vec(numeric_limits<double>::min()); vector<Fragment *>::iterator fragit1; for (fragit1 = Fragments().begin(); fragit1 < Fragments().end(); fragit1++) { const tools::vec &pos = (*fragit1)->getPos(); if (pos.getX() > max.getX()) { max.x() = pos.getX(); } else if (pos.getX() < min.getX()) { min.x() = pos.getX(); } if (pos.getY() > max.getY()) { max.y() = pos.getY(); } else if (pos.getY() < min.getY()) { min.y() = pos.getY(); } if (pos.getZ() > max.getZ()) { max.z() = pos.getZ(); } else if (pos.getZ() < min.getZ()) { min.z() = pos.getZ(); } } _approxsize = abs(max - min); return; } void Segment::Rigidify() { if (this->getType()->canRigidify()) { // Establish which atoms to use to define local frame vector<Fragment *>::iterator fit; for (fit = this->Fragments().begin(); fit < this->Fragments().end(); fit++) { (*fit)->Rigidify(); } } else { return; } } } } <|endoftext|>
<commit_before>#pragma once #include <new> #include <memory> #include <utility> #include <type_traits> #include <chrono> #include <uv.h> #include "emitter.hpp" #ifdef _WIN32 #include <ciso646> #endif namespace uvw { namespace details { enum class UVLoopOption: std::underlying_type_t<uv_loop_option> { BLOCK_SIGNAL = UV_LOOP_BLOCK_SIGNAL }; enum class UVRunMode: std::underlying_type_t<uv_run_mode> { DEFAULT = UV_RUN_DEFAULT, ONCE = UV_RUN_ONCE, NOWAIT = UV_RUN_NOWAIT }; } /** * @brief Untyped handle class * * Handles' types are unknown from the point of view of the loop.<br/> * Anyway, a loop maintains a list of all the associated handles and let the * users walk them as untyped instances.<br/> * This can help to end all the pending requests by closing the handles. */ class BaseHandle { public: /** * @brief Checks if the handle is active. * * What _active_ means depends on the type of handle: * * * An AsyncHandle handle is always active and cannot be deactivated, * except by closing it with uv_close(). * * A PipeHandle, TcpHandle, UDPHandle, etc. handle - basically any handle * that deals with I/O - is active when it is doing something that involves * I/O, like reading, writing, connecting, accepting new connections, etc. * * A CheckHandle, IdleHandle, TimerHandle, etc. handle is active when it * has been started with a call to `start()`. * * Rule of thumb: if a handle of type `FooHandle` has a `start()` member * method, then it’s active from the moment that method is called. Likewise, * `stop()` deactivates the handle again. * * @return True if the handle is active, false otherwise. */ virtual bool active() const noexcept = 0; /** * @brief Checks if a handle is closing or closed. * * This function should only be used between the initialization of the * handle and the arrival of the close callback. * * @return True if the handle is closing or closed, false otherwise. */ virtual bool closing() const noexcept = 0; /** * @brief Reference the given handle. * * References are idempotent, that is, if a handle is already referenced * calling this function again will have no effect. */ virtual void reference() noexcept = 0; /** * @brief Unreference the given handle. * * References are idempotent, that is, if a handle is not referenced calling * this function again will have no effect. */ virtual void unreference() noexcept = 0; /** * @brief Checks if the given handle referenced. * @return True if the handle referenced, false otherwise. */ virtual bool referenced() const noexcept = 0; /** * @brief Request handle to be closed. * * This **must** be called on each handle before memory is released.<br/> * In-progress requests are cancelled and this can result in an ErrorEvent * emitted. */ virtual void close() noexcept = 0; }; /** * @brief The Loop class. * * The event loop is the central part of `uvw`'s functionalities, as well as * libuv's ones.<br/> * It takes care of polling for I/O and scheduling callbacks to be run based on * different sources of events. */ class Loop final: public Emitter<Loop>, public std::enable_shared_from_this<Loop> { using Deleter = void(*)(uv_loop_t *); template<typename, typename> friend class Resource; Loop(std::unique_ptr<uv_loop_t, Deleter> ptr) noexcept : loop{std::move(ptr)} { } public: using Time = std::chrono::milliseconds; using Configure = details::UVLoopOption; using Mode = details::UVRunMode; /** * @brief Initializes a new Loop instance. * @return A pointer to the newly created loop. */ static std::shared_ptr<Loop> create() { auto ptr = std::unique_ptr<uv_loop_t, Deleter>{new uv_loop_t, [](uv_loop_t *l){ delete l; }}; auto loop = std::shared_ptr<Loop>(new Loop{std::move(ptr)}); if(uv_loop_init(loop->loop.get())) { loop = nullptr; } return loop; } /** * @brief Gets the initialized default loop. * * It may return an empty pointer in case of failure.<br> * This function is just a convenient way for having a global loop * throughout an application, the default loop is in no way different than * the ones initialized with `create()`.<br> * As such, the default loop can be closed with `close()` so the resources * associated with it are freed (even if it is not strictly necessary). * * @return The initialized default loop. */ static std::shared_ptr<Loop> getDefault() { static std::weak_ptr<Loop> ref; std::shared_ptr<Loop> loop; if(ref.expired()) { auto def = uv_default_loop(); if(def) { auto ptr = std::unique_ptr<uv_loop_t, Deleter>(def, [](uv_loop_t *){ }); loop = std::shared_ptr<Loop>(new Loop{std::move(ptr)}); } ref = loop; } else { loop = ref.lock(); } return loop; } Loop(const Loop &) = delete; Loop(Loop &&other) = delete; Loop& operator=(const Loop &) = delete; Loop& operator=(Loop &&other) = delete; ~Loop() noexcept { if(loop) { close(); } } /** * @brief Sets additional loop options. * * You should normally call this before the first call to uv_run() unless * mentioned otherwise.<br/> * Supported options: * * * `Loop::Configure::BLOCK_SIGNAL`: Block a signal when polling for new * events. A second argument is required and it is the signal number. * * An ErrorEvent will be emitted in case of errors. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/loop.html#c.uv_loop_configure) * for further details. */ template<typename... Args> void configure(Configure flag, Args... args) { auto err = uv_loop_configure(loop.get(), static_cast<std::underlying_type_t<Configure>>(flag), std::forward<Args>(args)...); if(err) { publish(ErrorEvent{err}); } } /** * @brief Creates resources of handles' types. * * This should be used as a default method to create resources.<br/> * The arguments are the ones required for the specific resource. * * Use it as `loop->resource<uvw::TimerHandle>()`. * * @return A pointer to the newly created resource. */ template<typename R, typename... Args> std::enable_if_t<std::is_base_of<BaseHandle, R>::value, std::shared_ptr<R>> resource(Args&&... args) { auto ptr = R::create(shared_from_this(), std::forward<Args>(args)...); ptr = ptr->init() ? ptr : nullptr; return ptr; } /** * @brief Creates resources of types other than handles' ones. * * This should be used as a default method to create resources.<br/> * The arguments are the ones required for the specific resource. * * Use it as `loop->resource<uvw::WorkReq>()`. * * @return A pointer to the newly created resource. */ template<typename R, typename... Args> std::enable_if_t<not std::is_base_of<BaseHandle, R>::value, std::shared_ptr<R>> resource(Args&&... args) { return R::create(shared_from_this(), std::forward<Args>(args)...); } /** * @brief Releases all internal loop resources. * * Call this function only when the loop has finished executing and all open * handles and requests have been closed, or the loop will emit an error. * * An ErrorEvent will be emitted in case of errors. */ void close() { auto err = uv_loop_close(loop.get()); if(err) { publish(ErrorEvent{err}); } } /** * @brief Runs the event loop. * * Available modes are: * * * `Loop::Mode::DEFAULT`: Runs the event loop until there are no more * active and referenced handles or requests. * * `Loop::Mode::ONCE`: Poll for i/o once. Note that this function blocks * if there are no pending callbacks. * * `Loop::Mode::NOWAIT`: Poll for i/o once but don’t block if there are no * pending callbacks. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/loop.html#c.uv_run) * for further details. * * @return True when done, false in all other cases. */ template<Mode mode = Mode::DEFAULT> bool run() noexcept { auto utm = static_cast<std::underlying_type_t<Mode>>(mode); auto uvrm = static_cast<uv_run_mode>(utm); return (uv_run(loop.get(), uvrm) == 0); } /** * @brief Checks if there are active resources. * @return True if there are active resources in the loop. */ bool alive() const noexcept { return !(uv_loop_alive(loop.get()) == 0); } /** * @brief Stops the event loop. * * It causes `run()` to end as soon as possible.<br/> * This will happen not sooner than the next loop iteration.<br/> * If this function was called before blocking for I/O, the loop won’t block * for I/O on this iteration. */ void stop() noexcept { uv_stop(loop.get()); } /** * @brief Get backend file descriptor. * * Only kqueue, epoll and event ports are supported.<br/> * This can be used in conjunction with `run<Loop::Mode::NOWAIT>()` to poll * in one thread and run the event loop’s callbacks in another. * * @return The backend file descriptor. */ int descriptor() const noexcept { return uv_backend_fd(loop.get()); } /** * @brief Gets the poll timeout. * @return The return value is in milliseconds, or -1 for no timeout. */ Time timeout() const noexcept { return Time{uv_backend_timeout(loop.get())}; } /** * @brief Returns the current timestamp in milliseconds. * * The timestamp is cached at the start of the event loop tick.<br/> * The timestamp increases monotonically from some arbitrary point in * time.<br/> * Don’t make assumptions about the starting point, you will only get * disappointed. * * @return The current timestamp in milliseconds. */ Time now() const noexcept { return Time{uv_now(loop.get())}; } /** * @brief Updates the event loop’s concept of _now_. * * The current time is cached at the start of the event loop tick in order * to reduce the number of time-related system calls.<br/> * You won’t normally need to call this function unless you have callbacks * that block the event loop for longer periods of time, where _longer_ is * somewhat subjective but probably on the order of a millisecond or more. */ void update() const noexcept { return uv_update_time(loop.get()); } /** * @brief Walks the list of handles. * * The callback will be executed once for each handle that is still active. * * @param callback A function to be invoked once for each active handle. */ void walk(std::function<void(BaseHandle &)> callback) { // remember: non-capturing lambdas decay to pointers to functions uv_walk(loop.get(), [](uv_handle_t *handle, void *func) { BaseHandle &ref = *static_cast<BaseHandle*>(handle->data); std::function<void(BaseHandle &)> &f = *static_cast<std::function<void(BaseHandle &)>*>(func); f(ref); }, &callback); } private: std::unique_ptr<uv_loop_t, Deleter> loop; }; } <commit_msg>Reorder header includes as per comment<commit_after>#pragma once #ifdef _WIN32 #include <ciso646> #endif #include <new> #include <memory> #include <utility> #include <type_traits> #include <chrono> #include <uv.h> #include "emitter.hpp" namespace uvw { namespace details { enum class UVLoopOption: std::underlying_type_t<uv_loop_option> { BLOCK_SIGNAL = UV_LOOP_BLOCK_SIGNAL }; enum class UVRunMode: std::underlying_type_t<uv_run_mode> { DEFAULT = UV_RUN_DEFAULT, ONCE = UV_RUN_ONCE, NOWAIT = UV_RUN_NOWAIT }; } /** * @brief Untyped handle class * * Handles' types are unknown from the point of view of the loop.<br/> * Anyway, a loop maintains a list of all the associated handles and let the * users walk them as untyped instances.<br/> * This can help to end all the pending requests by closing the handles. */ class BaseHandle { public: /** * @brief Checks if the handle is active. * * What _active_ means depends on the type of handle: * * * An AsyncHandle handle is always active and cannot be deactivated, * except by closing it with uv_close(). * * A PipeHandle, TcpHandle, UDPHandle, etc. handle - basically any handle * that deals with I/O - is active when it is doing something that involves * I/O, like reading, writing, connecting, accepting new connections, etc. * * A CheckHandle, IdleHandle, TimerHandle, etc. handle is active when it * has been started with a call to `start()`. * * Rule of thumb: if a handle of type `FooHandle` has a `start()` member * method, then it’s active from the moment that method is called. Likewise, * `stop()` deactivates the handle again. * * @return True if the handle is active, false otherwise. */ virtual bool active() const noexcept = 0; /** * @brief Checks if a handle is closing or closed. * * This function should only be used between the initialization of the * handle and the arrival of the close callback. * * @return True if the handle is closing or closed, false otherwise. */ virtual bool closing() const noexcept = 0; /** * @brief Reference the given handle. * * References are idempotent, that is, if a handle is already referenced * calling this function again will have no effect. */ virtual void reference() noexcept = 0; /** * @brief Unreference the given handle. * * References are idempotent, that is, if a handle is not referenced calling * this function again will have no effect. */ virtual void unreference() noexcept = 0; /** * @brief Checks if the given handle referenced. * @return True if the handle referenced, false otherwise. */ virtual bool referenced() const noexcept = 0; /** * @brief Request handle to be closed. * * This **must** be called on each handle before memory is released.<br/> * In-progress requests are cancelled and this can result in an ErrorEvent * emitted. */ virtual void close() noexcept = 0; }; /** * @brief The Loop class. * * The event loop is the central part of `uvw`'s functionalities, as well as * libuv's ones.<br/> * It takes care of polling for I/O and scheduling callbacks to be run based on * different sources of events. */ class Loop final: public Emitter<Loop>, public std::enable_shared_from_this<Loop> { using Deleter = void(*)(uv_loop_t *); template<typename, typename> friend class Resource; Loop(std::unique_ptr<uv_loop_t, Deleter> ptr) noexcept : loop{std::move(ptr)} { } public: using Time = std::chrono::milliseconds; using Configure = details::UVLoopOption; using Mode = details::UVRunMode; /** * @brief Initializes a new Loop instance. * @return A pointer to the newly created loop. */ static std::shared_ptr<Loop> create() { auto ptr = std::unique_ptr<uv_loop_t, Deleter>{new uv_loop_t, [](uv_loop_t *l){ delete l; }}; auto loop = std::shared_ptr<Loop>(new Loop{std::move(ptr)}); if(uv_loop_init(loop->loop.get())) { loop = nullptr; } return loop; } /** * @brief Gets the initialized default loop. * * It may return an empty pointer in case of failure.<br> * This function is just a convenient way for having a global loop * throughout an application, the default loop is in no way different than * the ones initialized with `create()`.<br> * As such, the default loop can be closed with `close()` so the resources * associated with it are freed (even if it is not strictly necessary). * * @return The initialized default loop. */ static std::shared_ptr<Loop> getDefault() { static std::weak_ptr<Loop> ref; std::shared_ptr<Loop> loop; if(ref.expired()) { auto def = uv_default_loop(); if(def) { auto ptr = std::unique_ptr<uv_loop_t, Deleter>(def, [](uv_loop_t *){ }); loop = std::shared_ptr<Loop>(new Loop{std::move(ptr)}); } ref = loop; } else { loop = ref.lock(); } return loop; } Loop(const Loop &) = delete; Loop(Loop &&other) = delete; Loop& operator=(const Loop &) = delete; Loop& operator=(Loop &&other) = delete; ~Loop() noexcept { if(loop) { close(); } } /** * @brief Sets additional loop options. * * You should normally call this before the first call to uv_run() unless * mentioned otherwise.<br/> * Supported options: * * * `Loop::Configure::BLOCK_SIGNAL`: Block a signal when polling for new * events. A second argument is required and it is the signal number. * * An ErrorEvent will be emitted in case of errors. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/loop.html#c.uv_loop_configure) * for further details. */ template<typename... Args> void configure(Configure flag, Args... args) { auto err = uv_loop_configure(loop.get(), static_cast<std::underlying_type_t<Configure>>(flag), std::forward<Args>(args)...); if(err) { publish(ErrorEvent{err}); } } /** * @brief Creates resources of handles' types. * * This should be used as a default method to create resources.<br/> * The arguments are the ones required for the specific resource. * * Use it as `loop->resource<uvw::TimerHandle>()`. * * @return A pointer to the newly created resource. */ template<typename R, typename... Args> std::enable_if_t<std::is_base_of<BaseHandle, R>::value, std::shared_ptr<R>> resource(Args&&... args) { auto ptr = R::create(shared_from_this(), std::forward<Args>(args)...); ptr = ptr->init() ? ptr : nullptr; return ptr; } /** * @brief Creates resources of types other than handles' ones. * * This should be used as a default method to create resources.<br/> * The arguments are the ones required for the specific resource. * * Use it as `loop->resource<uvw::WorkReq>()`. * * @return A pointer to the newly created resource. */ template<typename R, typename... Args> std::enable_if_t<not std::is_base_of<BaseHandle, R>::value, std::shared_ptr<R>> resource(Args&&... args) { return R::create(shared_from_this(), std::forward<Args>(args)...); } /** * @brief Releases all internal loop resources. * * Call this function only when the loop has finished executing and all open * handles and requests have been closed, or the loop will emit an error. * * An ErrorEvent will be emitted in case of errors. */ void close() { auto err = uv_loop_close(loop.get()); if(err) { publish(ErrorEvent{err}); } } /** * @brief Runs the event loop. * * Available modes are: * * * `Loop::Mode::DEFAULT`: Runs the event loop until there are no more * active and referenced handles or requests. * * `Loop::Mode::ONCE`: Poll for i/o once. Note that this function blocks * if there are no pending callbacks. * * `Loop::Mode::NOWAIT`: Poll for i/o once but don’t block if there are no * pending callbacks. * * See the official * [documentation](http://docs.libuv.org/en/v1.x/loop.html#c.uv_run) * for further details. * * @return True when done, false in all other cases. */ template<Mode mode = Mode::DEFAULT> bool run() noexcept { auto utm = static_cast<std::underlying_type_t<Mode>>(mode); auto uvrm = static_cast<uv_run_mode>(utm); return (uv_run(loop.get(), uvrm) == 0); } /** * @brief Checks if there are active resources. * @return True if there are active resources in the loop. */ bool alive() const noexcept { return !(uv_loop_alive(loop.get()) == 0); } /** * @brief Stops the event loop. * * It causes `run()` to end as soon as possible.<br/> * This will happen not sooner than the next loop iteration.<br/> * If this function was called before blocking for I/O, the loop won’t block * for I/O on this iteration. */ void stop() noexcept { uv_stop(loop.get()); } /** * @brief Get backend file descriptor. * * Only kqueue, epoll and event ports are supported.<br/> * This can be used in conjunction with `run<Loop::Mode::NOWAIT>()` to poll * in one thread and run the event loop’s callbacks in another. * * @return The backend file descriptor. */ int descriptor() const noexcept { return uv_backend_fd(loop.get()); } /** * @brief Gets the poll timeout. * @return The return value is in milliseconds, or -1 for no timeout. */ Time timeout() const noexcept { return Time{uv_backend_timeout(loop.get())}; } /** * @brief Returns the current timestamp in milliseconds. * * The timestamp is cached at the start of the event loop tick.<br/> * The timestamp increases monotonically from some arbitrary point in * time.<br/> * Don’t make assumptions about the starting point, you will only get * disappointed. * * @return The current timestamp in milliseconds. */ Time now() const noexcept { return Time{uv_now(loop.get())}; } /** * @brief Updates the event loop’s concept of _now_. * * The current time is cached at the start of the event loop tick in order * to reduce the number of time-related system calls.<br/> * You won’t normally need to call this function unless you have callbacks * that block the event loop for longer periods of time, where _longer_ is * somewhat subjective but probably on the order of a millisecond or more. */ void update() const noexcept { return uv_update_time(loop.get()); } /** * @brief Walks the list of handles. * * The callback will be executed once for each handle that is still active. * * @param callback A function to be invoked once for each active handle. */ void walk(std::function<void(BaseHandle &)> callback) { // remember: non-capturing lambdas decay to pointers to functions uv_walk(loop.get(), [](uv_handle_t *handle, void *func) { BaseHandle &ref = *static_cast<BaseHandle*>(handle->data); std::function<void(BaseHandle &)> &f = *static_cast<std::function<void(BaseHandle &)>*>(func); f(ref); }, &callback); } private: std::unique_ptr<uv_loop_t, Deleter> loop; }; } <|endoftext|>
<commit_before>/// /// @file popcount.cpp /// @brief Fast algorithm to count the number of 1 bits in an array. /// /// Copyright (C) 2013 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #if !defined(__STDC_CONSTANT_MACROS) #define __STDC_CONSTANT_MACROS #endif #include <stdint.h> namespace primesieve { /// This algorithm counts the number of 1 bits (population count) in /// an array using 64-bit tree merging. To the best of my knowledge /// this is the fastest integer arithmetic bit population count /// algorithm, it uses only 8 operations for 8 bytes on 64-bit CPUs. /// The 64-bit tree merging popcount algorithm is due to /// Cdric Lauradoux, it is described in his paper: /// http://perso.citi.insa-lyon.fr/claurado/ham/overview.pdf /// http://perso.citi.insa-lyon.fr/claurado/hamming.html /// uint64_t popcount(const uint64_t* array, uint64_t size) { const uint64_t m1 = UINT64_C(0x5555555555555555); const uint64_t m2 = UINT64_C(0x3333333333333333); const uint64_t m4 = UINT64_C(0x0F0F0F0F0F0F0F0F); const uint64_t m8 = UINT64_C(0x00FF00FF00FF00FF); const uint64_t h01 = UINT64_C(0x0101010101010101); uint64_t limit30 = size - size % 30; uint64_t i, j; uint64_t count1, count2, half1, half2, acc; uint64_t bit_count = 0; uint64_t x; if (array == 0) return 0; // 64-bit tree merging (merging3) for (i = 0; i < limit30; i += 30, array += 30) { acc = 0; for (j = 0; j < 30; j += 3) { count1 = array[j]; count2 = array[j+1]; half1 = array[j+2]; half2 = array[j+2]; half1 &= m1; half2 = (half2 >> 1) & m1; count1 -= (count1 >> 1) & m1; count2 -= (count2 >> 1) & m1; count1 += half1; count2 += half2; count1 = (count1 & m2) + ((count1 >> 2) & m2); count1 += (count2 & m2) + ((count2 >> 2) & m2); acc += (count1 & m4) + ((count1 >> 4) & m4); } acc = (acc & m8) + ((acc >> 8) & m8); acc = (acc + (acc >> 16)); acc = (acc + (acc >> 32)); bit_count += acc & 0xffff; } // Count the bits of the remaining bytes (max 29*8 = 232) // http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation for (i = 0; i < size - limit30; i++) { x = array[i]; x = x - ((x >> 1) & m1); x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; x = (x * h01) >> 56; bit_count += x; } return bit_count; } } // namespace primesieve <commit_msg>Faster popcount algorithm (Harley-Seal 4th iteration)<commit_after>/// /// @file popcount.cpp /// @brief Fast algorithm to count the number of 1 bits in an array /// using only integer operations. /// /// Copyright (C) 2015 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #if !defined(__STDC_CONSTANT_MACROS) #define __STDC_CONSTANT_MACROS #endif #include <stdint.h> namespace { /// This uses fewer arithmetic operations than any other known /// implementation on machines with fast multiplication. /// It uses 12 arithmetic operations, one of which is a multiply. /// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation /// uint64_t popcount_mul(uint64_t x) { const uint64_t m1 = UINT64_C(0x5555555555555555); const uint64_t m2 = UINT64_C(0x3333333333333333); const uint64_t m4 = UINT64_C(0x0F0F0F0F0F0F0F0F); const uint64_t h01 = UINT64_C(0x0101010101010101); x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; } /// Carry-save adder (CSA). /// @see Chapter 5 in "Hacker's Delight". /// void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c) { uint64_t u = a ^ b; h = (a & b) | (u & c); l = u ^ c; } /// Harley-Seal popcount (4th iteration). /// The Harley-Seal popcount algorithm is one of the fastest algorithms /// for counting 1 bits in an array using only integer operations. /// This implementation uses only 5.69 instructions per 64-bit word. /// @see Chapter 5 in "Hacker's Delight" 2nd edition. /// uint64_t popcount_hs4(const uint64_t* array, uint64_t size) { uint64_t total = 0; uint64_t ones = 0, twos = 0, fours = 0, eights = 0, sixteens = 0; uint64_t twosA, twosB, foursA, foursB, eightsA, eightsB; uint64_t limit = size - size % 16; uint64_t i = 0; for(; i < limit; i += 16) { CSA(twosA, ones, ones, array[i+0], array[i+1]); CSA(twosB, ones, ones, array[i+2], array[i+3]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, array[i+4], array[i+5]); CSA(twosB, ones, ones, array[i+6], array[i+7]); CSA(foursB, twos, twos, twosA, twosB); CSA(eightsA,fours, fours, foursA, foursB); CSA(twosA, ones, ones, array[i+8], array[i+9]); CSA(twosB, ones, ones, array[i+10], array[i+11]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, array[i+12], array[i+13]); CSA(twosB, ones, ones, array[i+14], array[i+15]); CSA(foursB, twos, twos, twosA, twosB); CSA(eightsB, fours, fours, foursA, foursB); CSA(sixteens, eights, eights, eightsA, eightsB); total += popcount_mul(sixteens); } total *= 16; total += 8 * popcount_mul(eights); total += 4 * popcount_mul(fours); total += 2 * popcount_mul(twos); total += 1 * popcount_mul(ones); for(; i < size; i++) total += popcount_mul(array[i]); return total; } } // namespace namespace primesieve { uint64_t popcount(const uint64_t* array, uint64_t size) { return popcount_hs4(array, size); } } // namespace primesieve <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/geometry/boost_adapters.hpp> #include <mapnik/geometry/box2d.hpp> #include <mapnik/geometry/multi_point.hpp> #include <mapnik/projection.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/coord.hpp> #include <mapnik/util/is_clockwise.hpp> // boost #include <boost/geometry/algorithms/envelope.hpp> #ifdef MAPNIK_USE_PROJ4 // proj4 #include <proj_api.h> #endif // stl #include <vector> #include <stdexcept> namespace mapnik { namespace { // (local) // Returns points in clockwise order. This allows us to do anti-meridian checks. template <typename T> auto envelope_points(box2d<T> const& env, std::size_t num_points) -> geometry::multi_point<T> { auto width = env.width(); auto height = env.height(); geometry::multi_point<T> coords; coords.reserve(num_points); // top side: left >>> right // gets extra point if (num_points % 4 >= 1) for (std::size_t i = 0, n = (num_points + 3) / 4; i < n; ++i) { auto x = env.minx() + (i * width) / n; coords.emplace_back(x, env.maxy()); } // right side: top >>> bottom // gets extra point if (num_points % 4 >= 3) for (std::size_t i = 0, n = (num_points + 1) / 4; i < n; ++i) { auto y = env.maxy() - (i * height) / n; coords.emplace_back(env.maxx(), y); } // bottom side: right >>> left // gets extra point if (num_points % 4 >= 2) for (std::size_t i = 0, n = (num_points + 2) / 4; i < n; ++i) { auto x = env.maxx() - (i * width) / n; coords.emplace_back(x, env.miny()); } // left side: bottom >>> top // never gets extra point for (std::size_t i = 0, n = (num_points + 0) / 4; i < n; ++i) { auto y = env.miny() + (i * height) / n; coords.emplace_back(env.minx(), y); } return coords; } } // namespace mapnik::(local) proj_transform::proj_transform(projection const& source, projection const& dest) : source_(source), dest_(dest), is_source_longlat_(false), is_dest_longlat_(false), is_source_equal_dest_(false), wgs84_to_merc_(false), merc_to_wgs84_(false) { is_source_equal_dest_ = (source_ == dest_); if (!is_source_equal_dest_) { is_source_longlat_ = source_.is_geographic(); is_dest_longlat_ = dest_.is_geographic(); boost::optional<well_known_srs_e> src_k = source.well_known(); boost::optional<well_known_srs_e> dest_k = dest.well_known(); bool known_trans = false; if (src_k && dest_k) { if (*src_k == WGS_84 && *dest_k == G_MERC) { wgs84_to_merc_ = true; known_trans = true; } else if (*src_k == G_MERC && *dest_k == WGS_84) { merc_to_wgs84_ = true; known_trans = true; } } if (!known_trans) { #ifdef MAPNIK_USE_PROJ4 source_.init_proj4(); dest_.init_proj4(); #else throw std::runtime_error(std::string("Cannot initialize proj_transform for given projections without proj4 support (-DMAPNIK_USE_PROJ4): '") + source_.params() + "'->'" + dest_.params() + "'"); #endif } } } bool proj_transform::equal() const { return is_source_equal_dest_; } bool proj_transform::is_known() const { return merc_to_wgs84_ || wgs84_to_merc_; } bool proj_transform::forward (double & x, double & y , double & z) const { return forward(&x, &y, &z, 1); } bool proj_transform::forward (geometry::point<double> & p) const { double z = 0; return forward(&(p.x), &(p.y), &z, 1); } unsigned int proj_transform::forward (std::vector<geometry::point<double>> & ls) const { std::size_t size = ls.size(); if (size == 0) return 0; if (is_source_equal_dest_) return 0; if (wgs84_to_merc_) { lonlat2merc(ls); return 0; } else if (merc_to_wgs84_) { merc2lonlat(ls); return 0; } geometry::point<double> * ptr = ls.data(); double * x = reinterpret_cast<double*>(ptr); double * y = x + 1; double * z = nullptr; if(!forward(x, y, z, size, 2)) { return size; } return 0; } bool proj_transform::forward (double * x, double * y , double * z, int point_count, int offset) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_) { return lonlat2merc(x,y,point_count); } else if (merc_to_wgs84_) { return merc2lonlat(x,y,point_count); } #ifdef MAPNIK_USE_PROJ4 if (is_source_longlat_) { int i; for(i=0; i<point_count; i++) { x[i*offset] *= DEG_TO_RAD; y[i*offset] *= DEG_TO_RAD; } } if (pj_transform( source_.proj_, dest_.proj_, point_count, offset, x,y,z) != 0) { return false; } for(int j=0; j<point_count; j++) { if (x[j] == HUGE_VAL || y[j] == HUGE_VAL) { return false; } } if (is_dest_longlat_) { int i; for(i=0; i<point_count; i++) { x[i*offset] *= RAD_TO_DEG; y[i*offset] *= RAD_TO_DEG; } } #endif return true; } bool proj_transform::backward (double * x, double * y , double * z, int point_count, int offset) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_) { return merc2lonlat(x,y,point_count); } else if (merc_to_wgs84_) { return lonlat2merc(x,y,point_count); } #ifdef MAPNIK_USE_PROJ4 if (is_dest_longlat_) { for (int i = 0; i < point_count; ++i) { x[i * offset] *= DEG_TO_RAD; y[i * offset] *= DEG_TO_RAD; } } if (pj_transform(dest_.proj_, source_.proj_, point_count, offset, x, y, z) != 0) { return false; } for (int j = 0; j < point_count; ++j) { if (x[j] == HUGE_VAL || y[j] == HUGE_VAL) { return false; } } if (is_source_longlat_) { for (int i = 0; i < point_count; ++i) { x[i * offset] *= RAD_TO_DEG; y[i * offset] *= RAD_TO_DEG; } } #endif return true; } bool proj_transform::backward (double & x, double & y , double & z) const { return backward(&x, &y, &z, 1); } bool proj_transform::backward (geometry::point<double> & p) const { double z = 0; return backward(&(p.x), &(p.y), &z, 1); } unsigned int proj_transform::backward (std::vector<geometry::point<double>> & ls) const { std::size_t size = ls.size(); if (size == 0) return 0; if (is_source_equal_dest_) return 0; if (wgs84_to_merc_) { merc2lonlat(ls); return 0; } else if (merc_to_wgs84_) { lonlat2merc(ls); return 0; } geometry::point<double> * ptr = ls.data(); double * x = reinterpret_cast<double*>(ptr); double * y = x + 1; double * z = nullptr; if (!backward(x, y, z, size, 2)) { return size; } return 0; } bool proj_transform::forward (box2d<double> & box) const { if (is_source_equal_dest_) return true; double llx = box.minx(); double ulx = box.minx(); double lly = box.miny(); double lry = box.miny(); double lrx = box.maxx(); double urx = box.maxx(); double uly = box.maxy(); double ury = box.maxy(); double z = 0.0; if (!forward(llx,lly,z)) return false; if (!forward(lrx,lry,z)) return false; if (!forward(ulx,uly,z)) return false; if (!forward(urx,ury,z)) return false; double minx = std::min(ulx, llx); double miny = std::min(lly, lry); double maxx = std::max(urx, lrx); double maxy = std::max(ury, uly); box.init(minx, miny, maxx, maxy); return true; } bool proj_transform::backward (box2d<double> & box) const { if (is_source_equal_dest_) return true; double x[4], y[4]; x[0] = box.minx(); // llx 0 y[0] = box.miny(); // lly 1 x[1] = box.maxx(); // lrx 2 y[1] = box.miny(); // lry 3 x[2] = box.minx(); // ulx 4 y[2] = box.maxy(); // uly 5 x[3] = box.maxx(); // urx 6 y[3] = box.maxy(); // ury 7 if (!backward(x, y, nullptr, 4, 1)) return false; double minx = std::min(x[0], x[2]); double miny = std::min(y[0], y[1]); double maxx = std::max(x[1], x[3]); double maxy = std::max(y[2], y[3]); box.init(minx, miny, maxx, maxy); return true; } // More robust, but expensive, bbox transform // in the face of proj4 out of bounds conditions. // Can result in 20 -> 10 r/s performance hit. // Alternative is to provide proper clipping box // in the target srs by setting map 'maximum-extent' bool proj_transform::backward(box2d<double>& env, int points) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_ || merc_to_wgs84_) { return backward(env); } auto coords = envelope_points(env, points); // this is always clockwise for (auto & p : coords) { double z = 0; if (!backward(p.x, p.y, z)) return false; } box2d<double> result; boost::geometry::envelope(coords, result); if (is_source_longlat_ && !util::is_clockwise(coords)) { // we've gone to a geographic CS, and our clockwise envelope has // changed into an anticlockwise one. This means we've crossed the antimeridian, and // need to expand the X direction to +/-180 to include all the data. Once we can deal // with multiple bboxes in queries we can improve. double miny = result.miny(); result.expand_to_include(-180.0, miny); result.expand_to_include(180.0, miny); } env.re_center(result.center().x, result.center().y); env.height(result.height()); env.width(result.width()); return true; } bool proj_transform::forward(box2d<double>& env, int points) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_ || merc_to_wgs84_) { return forward(env); } auto coords = envelope_points(env, points); // this is always clockwise for (auto & p : coords) { double z = 0; if (!forward(p.x, p.y, z)) return false; } box2d<double> result; boost::geometry::envelope(coords, result); if (is_dest_longlat_ && !util::is_clockwise(coords)) { // we've gone to a geographic CS, and our clockwise envelope has // changed into an anticlockwise one. This means we've crossed the antimeridian, and // need to expand the X direction to +/-180 to include all the data. Once we can deal // with multiple bboxes in queries we can improve. double miny = result.miny(); result.expand_to_include(-180.0, miny); result.expand_to_include(180.0, miny); } env.re_center(result.center().x, result.center().y); env.height(result.height()); env.width(result.width()); return true; } mapnik::projection const& proj_transform::source() const { return source_; } mapnik::projection const& proj_transform::dest() const { return dest_; } } <commit_msg>proj_transform: fix strided coordinate array transform<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/geometry/boost_adapters.hpp> #include <mapnik/geometry/box2d.hpp> #include <mapnik/geometry/multi_point.hpp> #include <mapnik/projection.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/coord.hpp> #include <mapnik/util/is_clockwise.hpp> // boost #include <boost/geometry/algorithms/envelope.hpp> #ifdef MAPNIK_USE_PROJ4 // proj4 #include <proj_api.h> #endif // stl #include <vector> #include <stdexcept> namespace mapnik { namespace { // (local) // Returns points in clockwise order. This allows us to do anti-meridian checks. template <typename T> auto envelope_points(box2d<T> const& env, std::size_t num_points) -> geometry::multi_point<T> { auto width = env.width(); auto height = env.height(); geometry::multi_point<T> coords; coords.reserve(num_points); // top side: left >>> right // gets extra point if (num_points % 4 >= 1) for (std::size_t i = 0, n = (num_points + 3) / 4; i < n; ++i) { auto x = env.minx() + (i * width) / n; coords.emplace_back(x, env.maxy()); } // right side: top >>> bottom // gets extra point if (num_points % 4 >= 3) for (std::size_t i = 0, n = (num_points + 1) / 4; i < n; ++i) { auto y = env.maxy() - (i * height) / n; coords.emplace_back(env.maxx(), y); } // bottom side: right >>> left // gets extra point if (num_points % 4 >= 2) for (std::size_t i = 0, n = (num_points + 2) / 4; i < n; ++i) { auto x = env.maxx() - (i * width) / n; coords.emplace_back(x, env.miny()); } // left side: bottom >>> top // never gets extra point for (std::size_t i = 0, n = (num_points + 0) / 4; i < n; ++i) { auto y = env.miny() + (i * height) / n; coords.emplace_back(env.minx(), y); } return coords; } } // namespace mapnik::(local) proj_transform::proj_transform(projection const& source, projection const& dest) : source_(source), dest_(dest), is_source_longlat_(false), is_dest_longlat_(false), is_source_equal_dest_(false), wgs84_to_merc_(false), merc_to_wgs84_(false) { is_source_equal_dest_ = (source_ == dest_); if (!is_source_equal_dest_) { is_source_longlat_ = source_.is_geographic(); is_dest_longlat_ = dest_.is_geographic(); boost::optional<well_known_srs_e> src_k = source.well_known(); boost::optional<well_known_srs_e> dest_k = dest.well_known(); bool known_trans = false; if (src_k && dest_k) { if (*src_k == WGS_84 && *dest_k == G_MERC) { wgs84_to_merc_ = true; known_trans = true; } else if (*src_k == G_MERC && *dest_k == WGS_84) { merc_to_wgs84_ = true; known_trans = true; } } if (!known_trans) { #ifdef MAPNIK_USE_PROJ4 source_.init_proj4(); dest_.init_proj4(); #else throw std::runtime_error(std::string("Cannot initialize proj_transform for given projections without proj4 support (-DMAPNIK_USE_PROJ4): '") + source_.params() + "'->'" + dest_.params() + "'"); #endif } } } bool proj_transform::equal() const { return is_source_equal_dest_; } bool proj_transform::is_known() const { return merc_to_wgs84_ || wgs84_to_merc_; } bool proj_transform::forward (double & x, double & y , double & z) const { return forward(&x, &y, &z, 1); } bool proj_transform::forward (geometry::point<double> & p) const { double z = 0; return forward(&(p.x), &(p.y), &z, 1); } unsigned int proj_transform::forward (std::vector<geometry::point<double>> & ls) const { std::size_t size = ls.size(); if (size == 0) return 0; if (is_source_equal_dest_) return 0; if (wgs84_to_merc_) { lonlat2merc(ls); return 0; } else if (merc_to_wgs84_) { merc2lonlat(ls); return 0; } geometry::point<double> * ptr = ls.data(); double * x = reinterpret_cast<double*>(ptr); double * y = x + 1; double * z = nullptr; if(!forward(x, y, z, size, 2)) { return size; } return 0; } bool proj_transform::forward (double * x, double * y , double * z, int point_count, int offset) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_) { return lonlat2merc(x, y, point_count, offset); } else if (merc_to_wgs84_) { return merc2lonlat(x, y, point_count, offset); } #ifdef MAPNIK_USE_PROJ4 if (is_source_longlat_) { int i; for(i=0; i<point_count; i++) { x[i*offset] *= DEG_TO_RAD; y[i*offset] *= DEG_TO_RAD; } } if (pj_transform( source_.proj_, dest_.proj_, point_count, offset, x,y,z) != 0) { return false; } for(int j=0; j<point_count; j++) { if (x[j] == HUGE_VAL || y[j] == HUGE_VAL) { return false; } } if (is_dest_longlat_) { int i; for(i=0; i<point_count; i++) { x[i*offset] *= RAD_TO_DEG; y[i*offset] *= RAD_TO_DEG; } } #endif return true; } bool proj_transform::backward (double * x, double * y , double * z, int point_count, int offset) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_) { return merc2lonlat(x, y, point_count, offset); } else if (merc_to_wgs84_) { return lonlat2merc(x, y, point_count, offset); } #ifdef MAPNIK_USE_PROJ4 if (is_dest_longlat_) { for (int i = 0; i < point_count; ++i) { x[i * offset] *= DEG_TO_RAD; y[i * offset] *= DEG_TO_RAD; } } if (pj_transform(dest_.proj_, source_.proj_, point_count, offset, x, y, z) != 0) { return false; } for (int j = 0; j < point_count; ++j) { if (x[j] == HUGE_VAL || y[j] == HUGE_VAL) { return false; } } if (is_source_longlat_) { for (int i = 0; i < point_count; ++i) { x[i * offset] *= RAD_TO_DEG; y[i * offset] *= RAD_TO_DEG; } } #endif return true; } bool proj_transform::backward (double & x, double & y , double & z) const { return backward(&x, &y, &z, 1); } bool proj_transform::backward (geometry::point<double> & p) const { double z = 0; return backward(&(p.x), &(p.y), &z, 1); } unsigned int proj_transform::backward (std::vector<geometry::point<double>> & ls) const { std::size_t size = ls.size(); if (size == 0) return 0; if (is_source_equal_dest_) return 0; if (wgs84_to_merc_) { merc2lonlat(ls); return 0; } else if (merc_to_wgs84_) { lonlat2merc(ls); return 0; } geometry::point<double> * ptr = ls.data(); double * x = reinterpret_cast<double*>(ptr); double * y = x + 1; double * z = nullptr; if (!backward(x, y, z, size, 2)) { return size; } return 0; } bool proj_transform::forward (box2d<double> & box) const { if (is_source_equal_dest_) return true; double llx = box.minx(); double ulx = box.minx(); double lly = box.miny(); double lry = box.miny(); double lrx = box.maxx(); double urx = box.maxx(); double uly = box.maxy(); double ury = box.maxy(); double z = 0.0; if (!forward(llx,lly,z)) return false; if (!forward(lrx,lry,z)) return false; if (!forward(ulx,uly,z)) return false; if (!forward(urx,ury,z)) return false; double minx = std::min(ulx, llx); double miny = std::min(lly, lry); double maxx = std::max(urx, lrx); double maxy = std::max(ury, uly); box.init(minx, miny, maxx, maxy); return true; } bool proj_transform::backward (box2d<double> & box) const { if (is_source_equal_dest_) return true; double x[4], y[4]; x[0] = box.minx(); // llx 0 y[0] = box.miny(); // lly 1 x[1] = box.maxx(); // lrx 2 y[1] = box.miny(); // lry 3 x[2] = box.minx(); // ulx 4 y[2] = box.maxy(); // uly 5 x[3] = box.maxx(); // urx 6 y[3] = box.maxy(); // ury 7 if (!backward(x, y, nullptr, 4, 1)) return false; double minx = std::min(x[0], x[2]); double miny = std::min(y[0], y[1]); double maxx = std::max(x[1], x[3]); double maxy = std::max(y[2], y[3]); box.init(minx, miny, maxx, maxy); return true; } // More robust, but expensive, bbox transform // in the face of proj4 out of bounds conditions. // Can result in 20 -> 10 r/s performance hit. // Alternative is to provide proper clipping box // in the target srs by setting map 'maximum-extent' bool proj_transform::backward(box2d<double>& env, int points) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_ || merc_to_wgs84_) { return backward(env); } auto coords = envelope_points(env, points); // this is always clockwise for (auto & p : coords) { double z = 0; if (!backward(p.x, p.y, z)) return false; } box2d<double> result; boost::geometry::envelope(coords, result); if (is_source_longlat_ && !util::is_clockwise(coords)) { // we've gone to a geographic CS, and our clockwise envelope has // changed into an anticlockwise one. This means we've crossed the antimeridian, and // need to expand the X direction to +/-180 to include all the data. Once we can deal // with multiple bboxes in queries we can improve. double miny = result.miny(); result.expand_to_include(-180.0, miny); result.expand_to_include(180.0, miny); } env.re_center(result.center().x, result.center().y); env.height(result.height()); env.width(result.width()); return true; } bool proj_transform::forward(box2d<double>& env, int points) const { if (is_source_equal_dest_) return true; if (wgs84_to_merc_ || merc_to_wgs84_) { return forward(env); } auto coords = envelope_points(env, points); // this is always clockwise for (auto & p : coords) { double z = 0; if (!forward(p.x, p.y, z)) return false; } box2d<double> result; boost::geometry::envelope(coords, result); if (is_dest_longlat_ && !util::is_clockwise(coords)) { // we've gone to a geographic CS, and our clockwise envelope has // changed into an anticlockwise one. This means we've crossed the antimeridian, and // need to expand the X direction to +/-180 to include all the data. Once we can deal // with multiple bboxes in queries we can improve. double miny = result.miny(); result.expand_to_include(-180.0, miny); result.expand_to_include(180.0, miny); } env.re_center(result.center().x, result.center().y); env.height(result.height()); env.width(result.width()); return true; } mapnik::projection const& proj_transform::source() const { return source_; } mapnik::projection const& proj_transform::dest() const { return dest_; } } <|endoftext|>
<commit_before>#include <pylon_camera/internal/pylon_camera.h> using namespace Pylon; namespace pylon_camera { enum PYLON_CAM_TYPE { GIGE = 1, USB = 2, DART = 3, UNKNOWN = -1, }; PYLON_CAM_TYPE detectPylonCamType(CInstantCamera* cam) { VersionInfo sfnc_version; try { sfnc_version = cam->GetSfncVersion(); } catch (const GenICam::GenericException &e) { std::cerr << "An exception while detecting the pylon camera type from its SFNC-Version occurred:" << std::endl; std::cerr << e.GetDescription() << std::endl; return UNKNOWN; } switch (sfnc_version.getMinor()) { case 0: // GigE Camera: Sfnc_2_0_0 return GIGE; case 1: // USB Camera: Sfnc_2_1_0 return USB; case 2: // DART Camera: Sfnc_2_2_0 return DART; default: std::cerr << "Unknown Camera Type!" << std::endl; return UNKNOWN; } } PylonCamera* createFromDevice(PYLON_CAM_TYPE cam_type, IPylonDevice* device) { switch (cam_type) { case GIGE: return new PylonGigECamera(device); case USB: return new PylonUSBCamera(device); case DART: return new PylonDARTCamera(device); case UNKNOWN: default: return NULL; } } PylonCamera* PylonCamera::create() { try { CInstantCamera* cam = new CInstantCamera(CTlFactory::GetInstance().CreateFirstDevice()); cam->Open(); { GenApi::INodeMap& node_map = cam->GetNodeMap(); GenApi::CStringPtr DeviceUserID(node_map.GetNode("DeviceUserID")); std::string device_user_id(DeviceUserID->GetValue()); std::cout << "Using camera " << device_user_id << std::endl; } PYLON_CAM_TYPE cam_type = detectPylonCamType(cam); cam->Close(); delete cam; return createFromDevice(cam_type, CTlFactory::GetInstance().CreateFirstDevice()); } catch (const GenICam::GenericException &e) { std::cerr << "Error while PylonCamera::create(). Exception: " << e.what() << std::endl; return NULL; } } PylonCamera* PylonCamera::create(const std::string& name) { if (name.empty() || name.compare("x") == 0) { return create(); } try { // Get the transport layer factory. CTlFactory& transport_layer_factory = CTlFactory::GetInstance(); // Get all attached devices and exit application if no device is found. DeviceInfoList_t device_info_list; if (transport_layer_factory.EnumerateDevices(device_info_list) == 0) { throw RUNTIME_EXCEPTION( "No camera present."); return NULL; } // Create an array of instant cameras for the found devices CInstantCameraArray camera_array(device_info_list.size()); bool found_desired_device = false; // Create and attach all Pylon Devices. size_t cam_pos = -1; for (size_t i = 0; i < camera_array.GetSize(); ++i) { try { camera_array[i].Attach(transport_layer_factory.CreateDevice(device_info_list[i])); camera_array[i].Open(); GenApi::INodeMap& node_map = camera_array[i].GetNodeMap(); GenApi::CStringPtr DeviceUserID(node_map.GetNode("DeviceUserID")); std::string device_user_id(DeviceUserID->GetValue()); camera_array[i].Close(); if (device_user_id.compare(name) == 0 || device_user_id.compare(device_user_id.length() - name.length(), name.length(), name)) { found_desired_device = true; cam_pos = i; std::cout << "Found the desired Camera with Magazino ID: " << name << ": " << camera_array[cam_pos].GetDeviceInfo().GetModelName() << std::endl; break; } } catch (const GenICam::GenericException &e) { continue; } } if (!found_desired_device) { std::cerr << "Maybe the given magazino_cam_id (" << name << ") is wrong or has not yet been written to the camera using 'write_magazino_id_to_camera' ?!" << std::endl; return NULL; } if (!camera_array[cam_pos].IsOpen()) { camera_array[cam_pos].Open(); } PYLON_CAM_TYPE cam_type = detectPylonCamType(&camera_array[cam_pos]); camera_array[cam_pos].Close(); return createFromDevice(cam_type, transport_layer_factory.CreateDevice(camera_array[cam_pos].GetDeviceInfo())); } catch (GenICam::GenericException &e) { std::cerr << "An exception while opening the desired camera with Magazino ID: " << name << " occurred:" << std::endl; std::cerr << e.GetDescription() << std::endl; return NULL; } } PylonCamera::PylonCamera() : img_rows_(-1) , img_cols_(-1) , height_aoi_(-1) , width_aoi_(-1) , offset_height_aoi_(-1) , offset_width_aoi_(-1) , img_size_byte_(-1) , max_framerate_(-1.0) , has_auto_exposure_(false) , last_exposure_val_(2000.0) , last_brightness_val_(-1) , is_ready_(false) , is_cam_removed_(false) , is_own_brightness_function_running_(false) { } PylonCamera::~PylonCamera() { } const int& PylonCamera::imageRows() const { return img_rows_; } const int& PylonCamera::imageCols() const { return img_cols_; } void PylonCamera::setImageSize(const int& size) { img_size_byte_ = size; } const int& PylonCamera::imageSize() const { return img_size_byte_; } const float& PylonCamera::maxPossibleFramerate() const { return max_framerate_; } const bool& PylonCamera::hasAutoExposure() const { return has_auto_exposure_; } const bool& PylonCamera::isCamRemoved() const { return is_cam_removed_; } const double& PylonCamera::lastExposureValue() const { return last_exposure_val_; } const bool& PylonCamera::isReady() const { return is_ready_; } const int& PylonCamera::lastBrightnessValue() const { return last_brightness_val_; } const std::vector<float>& PylonCamera::sequencerExposureTimes() const { return seq_exp_times_; } const bool& PylonCamera::isOwnBrightnessFunctionRunning() const { return is_own_brightness_function_running_; } } <commit_msg>camera now also opens if no camera_name was written into it<commit_after>#include <pylon_camera/internal/pylon_camera.h> using namespace Pylon; namespace pylon_camera { enum PYLON_CAM_TYPE { GIGE = 1, USB = 2, DART = 3, UNKNOWN = -1, }; PYLON_CAM_TYPE detectPylonCamType(CInstantCamera* cam) { VersionInfo sfnc_version; try { sfnc_version = cam->GetSfncVersion(); } catch (const GenICam::GenericException &e) { std::cerr << "An exception while detecting the pylon camera type from its SFNC-Version occurred:" << std::endl; std::cerr << e.GetDescription() << std::endl; return UNKNOWN; } switch (sfnc_version.getMinor()) { case 0: // GigE Camera: Sfnc_2_0_0 return GIGE; case 1: // USB Camera: Sfnc_2_1_0 return USB; case 2: // DART Camera: Sfnc_2_2_0 return DART; default: std::cerr << "Unknown Camera Type!" << std::endl; return UNKNOWN; } } PylonCamera* createFromDevice(PYLON_CAM_TYPE cam_type, IPylonDevice* device) { switch (cam_type) { case GIGE: return new PylonGigECamera(device); case USB: return new PylonUSBCamera(device); case DART: return new PylonDARTCamera(device); case UNKNOWN: default: return NULL; } } PylonCamera* PylonCamera::create() { try { CInstantCamera* cam = new CInstantCamera(CTlFactory::GetInstance().CreateFirstDevice()); cam->Open(); { GenApi::INodeMap& node_map = cam->GetNodeMap(); GenApi::CStringPtr DeviceUserID(node_map.GetNode("DeviceUserID")); std::string device_user_id(DeviceUserID->GetValue()); std::cout << "Using camera " << device_user_id << std::endl; } PYLON_CAM_TYPE cam_type = detectPylonCamType(cam); cam->Close(); delete cam; return createFromDevice(cam_type, CTlFactory::GetInstance().CreateFirstDevice()); } catch (const GenICam::GenericException &e) { std::cerr << "Error while PylonCamera::create(). Exception: " << e.what() << std::endl; return NULL; } } PylonCamera* PylonCamera::create(const std::string& name) { if (name.empty() || name.compare("x") == 0) { return create(); } try { // Get the transport layer factory. CTlFactory& transport_layer_factory = CTlFactory::GetInstance(); // Get all attached devices and exit application if no device is found. DeviceInfoList_t device_info_list; if (transport_layer_factory.EnumerateDevices(device_info_list) == 0) { throw RUNTIME_EXCEPTION( "No camera present."); return NULL; } // Create an array of instant cameras for the found devices CInstantCameraArray camera_array(device_info_list.size()); bool found_desired_device = false; // Create and attach all Pylon Devices. size_t cam_pos = -1; for (size_t i = 0; i < camera_array.GetSize(); ++i) { try { camera_array[i].Attach(transport_layer_factory.CreateDevice(device_info_list[i])); camera_array[i].Open(); GenApi::INodeMap& node_map = camera_array[i].GetNodeMap(); GenApi::CStringPtr DeviceUserID(node_map.GetNode("DeviceUserID")); std::string device_user_id(DeviceUserID->GetValue()); camera_array[i].Close(); // std::cout << "device_user_id " << device_user_id << std::endl; // std::cout << "length " << device_user_id.size() << std::endl; if (device_user_id.compare(name) == 0) // || // device_user_id.compare(device_user_id.length() - name.length(), name.length(), name)) { found_desired_device = true; cam_pos = i; std::cout << "Found the desired Camera with Magazino ID: " << name << ": " << camera_array[cam_pos].GetDeviceInfo().GetModelName() << std::endl; break; } } catch (const GenICam::GenericException &e) { continue; } } if (!found_desired_device) { std::cerr << "Maybe the given magazino_cam_id (" << name << ") is wrong or has not yet been written to the camera using 'write_magazino_id_to_camera' ?!" << std::endl; return NULL; } if (!camera_array[cam_pos].IsOpen()) { camera_array[cam_pos].Open(); } PYLON_CAM_TYPE cam_type = detectPylonCamType(&camera_array[cam_pos]); camera_array[cam_pos].Close(); return createFromDevice(cam_type, transport_layer_factory.CreateDevice(camera_array[cam_pos].GetDeviceInfo())); } catch (GenICam::GenericException &e) { std::cerr << "An exception while opening the desired camera with Magazino ID: " << name << " occurred:" << std::endl; std::cerr << e.GetDescription() << std::endl; return NULL; } } PylonCamera::PylonCamera() : img_rows_(-1) , img_cols_(-1) , height_aoi_(-1) , width_aoi_(-1) , offset_height_aoi_(-1) , offset_width_aoi_(-1) , img_size_byte_(-1) , max_framerate_(-1.0) , has_auto_exposure_(false) , last_exposure_val_(2000.0) , last_brightness_val_(-1) , is_ready_(false) , is_cam_removed_(false) , is_own_brightness_function_running_(false) { } PylonCamera::~PylonCamera() { } const int& PylonCamera::imageRows() const { return img_rows_; } const int& PylonCamera::imageCols() const { return img_cols_; } void PylonCamera::setImageSize(const int& size) { img_size_byte_ = size; } const int& PylonCamera::imageSize() const { return img_size_byte_; } const float& PylonCamera::maxPossibleFramerate() const { return max_framerate_; } const bool& PylonCamera::hasAutoExposure() const { return has_auto_exposure_; } const bool& PylonCamera::isCamRemoved() const { return is_cam_removed_; } const double& PylonCamera::lastExposureValue() const { return last_exposure_val_; } const bool& PylonCamera::isReady() const { return is_ready_; } const int& PylonCamera::lastBrightnessValue() const { return last_brightness_val_; } const std::vector<float>& PylonCamera::sequencerExposureTimes() const { return seq_exp_times_; } const bool& PylonCamera::isOwnBrightnessFunctionRunning() const { return is_own_brightness_function_running_; } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // 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 "AssemblyFileWriter.hpp" #include "Functions.hpp" #include "Context.hpp" #include "Utils.hpp" using namespace eddic; using std::endl; using std::shared_ptr; std::string eddic::mangle(Type type){ if(type == INT){ return "I"; } else { return "S"; } } void MainDeclaration::write(AssemblyFileWriter& writer){ writer.stream() << ".text" << endl << ".globl main" << endl << "\t.type main, @function" << endl; } void FunctionCall::checkFunctions(Program& program){ m_function_mangled = mangle(m_function, m_values); if(!program.exists(m_function_mangled)){ throw CompilerException("The function \"" + m_function + "()\" does not exists", token()); } } void Function::addParameter(std::string name, Type type){ shared_ptr<Parameter> param(new Parameter(name, type, m_currentPosition)); m_parameters.push_back(param); m_currentPosition += size(type); } void Function::write(AssemblyFileWriter& writer){ writer.stream() << endl << mangledName() << ":" << endl; writer.stream() << "pushl %ebp" << std::endl; writer.stream() << "movl %esp, %ebp" << std::endl; context()->write(writer); ParseNode::write(writer); context()->release(writer); writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void FunctionCall::write(AssemblyFileWriter& writer){ std::vector<std::shared_ptr<Value>>::reverse_iterator it = m_values.rbegin(); std::vector<std::shared_ptr<Value>>::reverse_iterator end = m_values.rend(); for( ; it != end; ++it){ (*it)->write(writer); } writer.stream() << "call " << m_function_mangled << endl; } <commit_msg>Use for_each to simplify the management of Value<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // 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 <algorithm> #include "AssemblyFileWriter.hpp" #include "Functions.hpp" #include "Context.hpp" #include "Utils.hpp" using namespace eddic; using std::endl; using std::shared_ptr; std::string eddic::mangle(Type type){ if(type == INT){ return "I"; } else { return "S"; } } void MainDeclaration::write(AssemblyFileWriter& writer){ writer.stream() << ".text" << endl << ".globl main" << endl << "\t.type main, @function" << endl; } void FunctionCall::checkFunctions(Program& program){ m_function_mangled = mangle(m_function, m_values); if(!program.exists(m_function_mangled)){ throw CompilerException("The function \"" + m_function + "()\" does not exists", token()); } } void Function::addParameter(std::string name, Type type){ shared_ptr<Parameter> param(new Parameter(name, type, m_currentPosition)); m_parameters.push_back(param); m_currentPosition += size(type); } void Function::write(AssemblyFileWriter& writer){ writer.stream() << endl << mangledName() << ":" << endl; writer.stream() << "pushl %ebp" << std::endl; writer.stream() << "movl %esp, %ebp" << std::endl; context()->write(writer); ParseNode::write(writer); context()->release(writer); writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void FunctionCall::write(AssemblyFileWriter& writer){ for_each(m_values.rbegin(), m_values.rend(), [&](std::shared_ptr<Value> v){ v->write(writer); }); writer.stream() << "call " << m_function_mangled << endl; } <|endoftext|>
<commit_before>#include "IRVisitor.h" #include "IR.h" namespace Halide { namespace Internal { IRVisitor::~IRVisitor() { } void IRVisitor::visit(const IntImm *) { } void IRVisitor::visit(const FloatImm *) { } void IRVisitor::visit(const StringImm *) { } void IRVisitor::visit(const Cast *op) { op->value.accept(this); } void IRVisitor::visit(const Variable *) { } void IRVisitor::visit(const Add *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Sub *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Mul *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Div *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Mod *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Min *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Max *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const EQ *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const NE *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const LT *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const LE *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const GT *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const GE *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const And *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Or *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Not *op) { op->a.accept(this); } void IRVisitor::visit(const Select *op) { op->condition.accept(this); op->true_value.accept(this); op->false_value.accept(this); } void IRVisitor::visit(const Load *op) { op->index.accept(this); } void IRVisitor::visit(const Ramp *op) { op->base.accept(this); op->stride.accept(this); } void IRVisitor::visit(const Broadcast *op) { op->value.accept(this); } void IRVisitor::visit(const Call *op) { for (size_t i = 0; i < op->args.size(); i++) { op->args[i].accept(this); } } void IRVisitor::visit(const Let *op) { op->value.accept(this); op->body.accept(this); } void IRVisitor::visit(const LetStmt *op) { op->value.accept(this); op->body.accept(this); } void IRVisitor::visit(const AssertStmt *op) { op->condition.accept(this); } void IRVisitor::visit(const Pipeline *op) { op->produce.accept(this); if (op->update.defined()) op->update.accept(this); op->consume.accept(this); } void IRVisitor::visit(const For *op) { op->min.accept(this); op->extent.accept(this); op->body.accept(this); } void IRVisitor::visit(const Store *op) { op->value.accept(this); op->index.accept(this); } void IRVisitor::visit(const Provide *op) { for (size_t i = 0; i < op->values.size(); i++) { op->values[i].accept(this); } for (size_t i = 0; i < op->args.size(); i++) { op->args[i].accept(this); } } void IRVisitor::visit(const Allocate *op) { op->size.accept(this); op->body.accept(this); } void IRVisitor::visit(const Free *op) { } void IRVisitor::visit(const Realize *op) { for (size_t i = 0; i < op->bounds.size(); i++) { op->bounds[i].min.accept(this); op->bounds[i].extent.accept(this); } op->body.accept(this); } void IRVisitor::visit(const Block *op) { op->first.accept(this); if (op->rest.defined()) { op->rest.accept(this); } } void IRVisitor::visit(const IfThenElse *op) { op->condition.accept(this); op->then_case.accept(this); if (op->else_case.defined()) { op->else_case.accept(this); } } void IRVisitor::visit(const Evaluate *op) { op->value.accept(this); } void IRGraphVisitor::include(const Expr &e) { if (visited.count(e.ptr)) { return; } else { visited.insert(e.ptr); e.accept(this); return; } } void IRGraphVisitor::include(const Stmt &s) { if (visited.count(s.ptr)) { return; } else { visited.insert(s.ptr); s.accept(this); return; } } void IRGraphVisitor::visit(const IntImm *) { } void IRGraphVisitor::visit(const FloatImm *) { } void IRGraphVisitor::visit(const StringImm *) { } void IRGraphVisitor::visit(const Cast *op) { include(op->value); } void IRGraphVisitor::visit(const Variable *op) { } void IRGraphVisitor::visit(const Add *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Sub *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Mul *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Div *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Mod *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Min *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Max *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const EQ *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const NE *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const LT *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const LE *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const GT *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const GE *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const And *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Or *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Not *op) { include(op->a); } void IRGraphVisitor::visit(const Select *op) { include(op->condition); include(op->true_value); include(op->false_value); } void IRGraphVisitor::visit(const Load *op) { include(op->index); } void IRGraphVisitor::visit(const Ramp *op) { include(op->base); include(op->stride); } void IRGraphVisitor::visit(const Broadcast *op) { include(op->value); } void IRGraphVisitor::visit(const Call *op) { for (size_t i = 0; i < op->args.size(); i++) { include(op->args[i]); } } void IRGraphVisitor::visit(const Let *op) { include(op->value); include(op->body); } void IRGraphVisitor::visit(const LetStmt *op) { include(op->value); include(op->body); } void IRGraphVisitor::visit(const AssertStmt *op) { include(op->condition); } void IRGraphVisitor::visit(const Pipeline *op) { include(op->produce); if (op->update.defined()) include(op->update); include(op->consume); } void IRGraphVisitor::visit(const For *op) { include(op->min); include(op->extent); include(op->body); } void IRGraphVisitor::visit(const Store *op) { include(op->value); include(op->index); } void IRGraphVisitor::visit(const Provide *op) { for (size_t i = 0; i < op->values.size(); i++) { include(op->values[i]); } for (size_t i = 0; i < op->args.size(); i++) { include(op->args[i]); } } void IRGraphVisitor::visit(const Allocate *op) { include(op->size); include(op->body); } void IRGraphVisitor::visit(const Free *op) { } void IRGraphVisitor::visit(const Realize *op) { for (size_t i = 0; i < op->bounds.size(); i++) { include(op->bounds[i].min); include(op->bounds[i].extent); } include(op->body); } void IRGraphVisitor::visit(const Block *op) { include(op->first); if (op->rest.defined()) include(op->rest); } void IRGraphVisitor::visit(const IfThenElse *op) { include(op->condition); include(op->then_case); if (op->else_case.defined()) { include(op->else_case); } } void IRGraphVisitor::visit(const Evaluate *op) { include(op->value); } void IRDeepVisitor::visit(const Call *call) { IRVisitor::visit(call); if (call->call_type == Call::Halide) { Function f = call->func; std::map<std::string, Function>::iterator iter = funcs.find(f.name()); if (iter == funcs.end()) { funcs[f.name()] = f; visit_function(this, f); } else { assert(iter->second.same_as(f) && "Can't compile a pipeline using multiple functions with same name"); } } } void visit_function(IRVisitor *v, const Function &f) { // recursively add everything called in the definition of f for (size_t i = 0; i < f.values().size(); i++) { f.values()[i].accept(v); } // recursively add everything called in the definition of f's update steps for (size_t i = 0; i < f.reductions().size(); i++) { // Update value definition for (size_t j = 0; j < f.reductions()[i].values.size(); j++) { f.reductions()[i].values[j].accept(v); } // Update index expressions for (size_t j = 0; j < f.reductions()[i].args.size(); j++) { f.reductions()[i].args[j].accept(v); } // Reduction domain min/extent expressions for (size_t j = 0; j < f.reductions()[i].domain.domain().size(); j++) { f.reductions()[i].domain.domain()[j].min.accept(v); f.reductions()[i].domain.domain()[j].extent.accept(v); } } } } } <commit_msg>Traverse Expr ExternArguments in IRVisitor<commit_after>#include "IRVisitor.h" #include "IR.h" namespace Halide { namespace Internal { IRVisitor::~IRVisitor() { } void IRVisitor::visit(const IntImm *) { } void IRVisitor::visit(const FloatImm *) { } void IRVisitor::visit(const StringImm *) { } void IRVisitor::visit(const Cast *op) { op->value.accept(this); } void IRVisitor::visit(const Variable *) { } void IRVisitor::visit(const Add *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Sub *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Mul *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Div *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Mod *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Min *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Max *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const EQ *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const NE *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const LT *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const LE *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const GT *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const GE *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const And *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Or *op) { op->a.accept(this); op->b.accept(this); } void IRVisitor::visit(const Not *op) { op->a.accept(this); } void IRVisitor::visit(const Select *op) { op->condition.accept(this); op->true_value.accept(this); op->false_value.accept(this); } void IRVisitor::visit(const Load *op) { op->index.accept(this); } void IRVisitor::visit(const Ramp *op) { op->base.accept(this); op->stride.accept(this); } void IRVisitor::visit(const Broadcast *op) { op->value.accept(this); } void IRVisitor::visit(const Call *op) { for (size_t i = 0; i < op->args.size(); i++) { op->args[i].accept(this); } // Consider extern call args Function f = op->func; if (op->call_type == Call::Halide && f.has_extern_definition()) { for (size_t i = 0; i < f.extern_arguments().size(); i++) { ExternFuncArgument arg = f.extern_arguments()[i]; if (arg.is_expr()) { arg.expr.accept(this); } } } } void IRVisitor::visit(const Let *op) { op->value.accept(this); op->body.accept(this); } void IRVisitor::visit(const LetStmt *op) { op->value.accept(this); op->body.accept(this); } void IRVisitor::visit(const AssertStmt *op) { op->condition.accept(this); } void IRVisitor::visit(const Pipeline *op) { op->produce.accept(this); if (op->update.defined()) op->update.accept(this); op->consume.accept(this); } void IRVisitor::visit(const For *op) { op->min.accept(this); op->extent.accept(this); op->body.accept(this); } void IRVisitor::visit(const Store *op) { op->value.accept(this); op->index.accept(this); } void IRVisitor::visit(const Provide *op) { for (size_t i = 0; i < op->values.size(); i++) { op->values[i].accept(this); } for (size_t i = 0; i < op->args.size(); i++) { op->args[i].accept(this); } } void IRVisitor::visit(const Allocate *op) { op->size.accept(this); op->body.accept(this); } void IRVisitor::visit(const Free *op) { } void IRVisitor::visit(const Realize *op) { for (size_t i = 0; i < op->bounds.size(); i++) { op->bounds[i].min.accept(this); op->bounds[i].extent.accept(this); } op->body.accept(this); } void IRVisitor::visit(const Block *op) { op->first.accept(this); if (op->rest.defined()) { op->rest.accept(this); } } void IRVisitor::visit(const IfThenElse *op) { op->condition.accept(this); op->then_case.accept(this); if (op->else_case.defined()) { op->else_case.accept(this); } } void IRVisitor::visit(const Evaluate *op) { op->value.accept(this); } void IRGraphVisitor::include(const Expr &e) { if (visited.count(e.ptr)) { return; } else { visited.insert(e.ptr); e.accept(this); return; } } void IRGraphVisitor::include(const Stmt &s) { if (visited.count(s.ptr)) { return; } else { visited.insert(s.ptr); s.accept(this); return; } } void IRGraphVisitor::visit(const IntImm *) { } void IRGraphVisitor::visit(const FloatImm *) { } void IRGraphVisitor::visit(const StringImm *) { } void IRGraphVisitor::visit(const Cast *op) { include(op->value); } void IRGraphVisitor::visit(const Variable *op) { } void IRGraphVisitor::visit(const Add *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Sub *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Mul *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Div *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Mod *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Min *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Max *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const EQ *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const NE *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const LT *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const LE *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const GT *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const GE *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const And *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Or *op) { include(op->a); include(op->b); } void IRGraphVisitor::visit(const Not *op) { include(op->a); } void IRGraphVisitor::visit(const Select *op) { include(op->condition); include(op->true_value); include(op->false_value); } void IRGraphVisitor::visit(const Load *op) { include(op->index); } void IRGraphVisitor::visit(const Ramp *op) { include(op->base); include(op->stride); } void IRGraphVisitor::visit(const Broadcast *op) { include(op->value); } void IRGraphVisitor::visit(const Call *op) { for (size_t i = 0; i < op->args.size(); i++) { include(op->args[i]); } } void IRGraphVisitor::visit(const Let *op) { include(op->value); include(op->body); } void IRGraphVisitor::visit(const LetStmt *op) { include(op->value); include(op->body); } void IRGraphVisitor::visit(const AssertStmt *op) { include(op->condition); } void IRGraphVisitor::visit(const Pipeline *op) { include(op->produce); if (op->update.defined()) include(op->update); include(op->consume); } void IRGraphVisitor::visit(const For *op) { include(op->min); include(op->extent); include(op->body); } void IRGraphVisitor::visit(const Store *op) { include(op->value); include(op->index); } void IRGraphVisitor::visit(const Provide *op) { for (size_t i = 0; i < op->values.size(); i++) { include(op->values[i]); } for (size_t i = 0; i < op->args.size(); i++) { include(op->args[i]); } } void IRGraphVisitor::visit(const Allocate *op) { include(op->size); include(op->body); } void IRGraphVisitor::visit(const Free *op) { } void IRGraphVisitor::visit(const Realize *op) { for (size_t i = 0; i < op->bounds.size(); i++) { include(op->bounds[i].min); include(op->bounds[i].extent); } include(op->body); } void IRGraphVisitor::visit(const Block *op) { include(op->first); if (op->rest.defined()) include(op->rest); } void IRGraphVisitor::visit(const IfThenElse *op) { include(op->condition); include(op->then_case); if (op->else_case.defined()) { include(op->else_case); } } void IRGraphVisitor::visit(const Evaluate *op) { include(op->value); } void IRDeepVisitor::visit(const Call *call) { IRVisitor::visit(call); if (call->call_type == Call::Halide) { Function f = call->func; std::map<std::string, Function>::iterator iter = funcs.find(f.name()); if (iter == funcs.end()) { funcs[f.name()] = f; visit_function(this, f); } else { assert(iter->second.same_as(f) && "Can't compile a pipeline using multiple functions with same name"); } } } void visit_function(IRVisitor *v, const Function &f) { // recursively add everything called in the definition of f for (size_t i = 0; i < f.values().size(); i++) { f.values()[i].accept(v); } // recursively add everything called in the definition of f's update steps for (size_t i = 0; i < f.reductions().size(); i++) { // Update value definition for (size_t j = 0; j < f.reductions()[i].values.size(); j++) { f.reductions()[i].values[j].accept(v); } // Update index expressions for (size_t j = 0; j < f.reductions()[i].args.size(); j++) { f.reductions()[i].args[j].accept(v); } // Reduction domain min/extent expressions for (size_t j = 0; j < f.reductions()[i].domain.domain().size(); j++) { f.reductions()[i].domain.domain()[j].min.accept(v); f.reductions()[i].domain.domain()[j].extent.accept(v); } } } } } <|endoftext|>
<commit_before>#include "LeftAlign.h" //bool debug; // Attempts to left-realign all the indels represented by the alignment cigar. // // This is done by shifting all indels as far left as they can go without // mismatch, then merging neighboring indels of the same class. leftAlign // updates the alignment cigar with changes, and returns true if realignment // changed the alignment cigar. // // To left-align, we move multi-base indels left by their own length as long as // the preceding bases match the inserted or deleted sequence. After this // step, we handle multi-base homopolymer indels by shifting them one base to // the left until they mismatch the reference. // // To merge neighboring indels, we iterate through the set of left-stabilized // indels. For each indel we add a new cigar element to the new cigar. If a // deletion follows a deletion, or an insertion occurs at the same place as // another insertion, we merge the events by extending the previous cigar // element. // // In practice, we must call this function until the alignment is stabilized. // bool leftAlign(BamAlignment& alignment, string& referenceSequence, bool debug) { int arsOffset = 0; // pointer to insertion point in aligned reference sequence string alignedReferenceSequence = referenceSequence; int aabOffset = 0; string alignmentAlignedBases = alignment.QueryBases; // store information about the indels vector<IndelAllele> indels; int rp = 0; // read position, 0-based relative to read int sp = 0; // sequence position string softBegin; string softEnd; stringstream cigar_before, cigar_after; for (vector<CigarOp>::const_iterator c = alignment.CigarData.begin(); c != alignment.CigarData.end(); ++c) { unsigned int l = c->Length; char t = c->Type; cigar_before << l << t; if (t == 'M') { // match or mismatch sp += l; rp += l; } else if (t == 'D') { // deletion indels.push_back(IndelAllele(false, l, sp, rp, referenceSequence.substr(sp, l))); alignmentAlignedBases.insert(rp + aabOffset, string(l, '-')); aabOffset += l; sp += l; // update sample position } else if (t == 'I') { // insertion indels.push_back(IndelAllele(true, l, sp, rp, alignment.QueryBases.substr(rp, l))); alignedReferenceSequence.insert(sp + softBegin.size() + arsOffset, string(l, '-')); arsOffset += l; rp += l; } else if (t == 'S') { // soft clip, clipped sequence present in the read not matching the reference // remove these bases from the refseq and read seq, but don't modify the alignment sequence if (rp == 0) { alignedReferenceSequence = string(l, '*') + alignedReferenceSequence; softBegin = alignmentAlignedBases.substr(0, l); } else { alignedReferenceSequence = alignedReferenceSequence + string(l, '*'); softEnd = alignmentAlignedBases.substr(alignmentAlignedBases.size() - l, l); } rp += l; } else if (t == 'H') { // hard clip on the read, clipped sequence is not present in the read } else if (t == 'N') { // skipped region in the reference not present in read, aka splice sp += l; } } int alignedLength = sp; DEBUG("| " << cigar_before.str() << endl << "| " << alignedReferenceSequence << endl << "| " << alignmentAlignedBases << endl); // if no indels, return the alignment if (indels.empty()) { return false; } // for each indel, from left to right // while the indel sequence repeated to the left and we're not matched up with the left-previous indel // move the indel left vector<IndelAllele>::iterator previous = indels.begin(); for (vector<IndelAllele>::iterator id = indels.begin(); id != indels.end(); ++id) { IndelAllele& indel = *id; int steppos = indel.position - indel.length; int readsteppos = (indel.insertion ? indel.readPosition - indel.length : indel.readPosition) - 1; // repeated subunits, single base homopolymers while (steppos >= 0 && readsteppos >= 0 && indel.sequence == referenceSequence.substr(steppos, indel.length) && indel.sequence == alignment.QueryBases.substr(readsteppos, indel.length) && (id == indels.begin() || (previous->insertion && steppos >= previous->position) || (!previous->insertion && steppos >= previous->position + previous->length))) { DEBUG("indel " << indel << " shifting " << indel.length << "bp left" << endl); indel.position -= indel.length; indel.readPosition -= indel.length; steppos = indel.position - indel.length; readsteppos = (indel.insertion ? indel.readPosition - indel.length : indel.readPosition) - 1; } // multi-base homopolymers if (indel.homopolymer()) { while (indel.position > 0 && indel.sequence == referenceSequence.substr(indel.position - 1, indel.length) && indel.sequence == alignment.QueryBases.substr(indel.readPosition - 1, indel.length) && (id == indels.begin() || indel.position >= previous->position + previous->length)) { DEBUG("indel " << indel << " shifting " << 1 << "bp left" << endl); indel.position -= 1; indel.readPosition -= 1; } } previous = id; } // unhandled: // attempt to shift in lengths below the tandem dup size // replaces above loop, but... // buggy code: /* vector<IndelAllele>::iterator previous = indels.begin(); for (vector<IndelAllele>::iterator id = indels.begin(); id != indels.end(); ++id) { IndelAllele& indel = *id; int steppos = indel.position - indel.length; int step = indel.length; while (steppos >= 0 && step > 0) { step = indel.length; steppos = indel.position - step; while (step > 0) { DEBUG(step << endl); if (indel.sequence == referenceSequence.substr(steppos, indel.length) && (id == indels.begin() || (previous->insertion && steppos >= previous->position) || (!previous->insertion && steppos >= previous->position + previous->length))) { DEBUG("indel " << indel << " shifting " << indel.length << "bp left" << endl); indel.position -= step; steppos = indel.position; break; } else { --step; } } } // multi-base homopolymers previous = id; } */ // bring together floating indels // from left to right // check if we could merge with the next indel // if so, adjust so that we will merge in the next step if (indels.size() > 1) { previous = indels.begin(); for (vector<IndelAllele>::iterator id = (indels.begin() + 1); id != indels.end(); ++id) { IndelAllele& indel = *id; // could we shift right and merge with the previous indel? // if so, do it int prev_end = previous->insertion ? previous->position : previous->position + previous->length; if (previous->insertion == indel.insertion && ((previous->insertion && previous->position < indel.position) || (!previous->insertion && previous->position + previous->length < indel.position))) { if (previous->homopolymer()) { string seq = referenceSequence.substr(prev_end, indel.position - prev_end); if (previous->sequence.at(0) == seq.at(0) && homopolymer(seq)) { DEBUG("moving " << *previous << " right to " << (indel.insertion ? indel.position : indel.position - previous->length) << endl); previous->position = indel.insertion ? indel.position : indel.position - previous->length; } } else { int pos = previous->position; while (pos < (int) referenceSequence.length() && ((previous->insertion && pos + previous->length <= indel.position) || (!previous->insertion && pos + previous->length < indel.position)) && previous->sequence == referenceSequence.substr(pos + previous->length, previous->length)) { pos += previous->length; } if (pos < previous->position && ((previous->insertion && pos + previous->length == indel.position) || (!previous->insertion && pos == indel.position - previous->length)) ) { DEBUG("right-merging tandem repeat: moving " << *previous << " right to " << pos << endl); previous->position = pos; } } } } } // for each indel // if ( we're matched up to the previous insertion (or deletion) // and it's also an insertion or deletion ) // merge the indels vector<CigarOp> newCigar; if (!softBegin.empty()) { newCigar.push_back(CigarOp('S', softBegin.size())); } vector<IndelAllele>::iterator id = indels.begin(); IndelAllele last = *id++; if (last.position > 0) { newCigar.push_back(CigarOp('M', last.position)); newCigar.push_back(CigarOp((last.insertion ? 'I' : 'D'), last.length)); } else { newCigar.push_back(CigarOp((last.insertion ? 'I' : 'D'), last.length)); } int lastend = last.insertion ? last.position : (last.position + last.length); DEBUG(last << ","); for (; id != indels.end(); ++id) { IndelAllele& indel = *id; DEBUG(indel << ","); if (indel.position < lastend) { cerr << "impossibility?: indel realigned left of another indel" << endl << alignment.Name << " " << alignment.Position << endl << alignment.QueryBases << endl; exit(1); } else if (indel.position == lastend && indel.insertion == last.insertion) { CigarOp& op = newCigar.back(); op.Length += indel.length; } else if (indel.position > lastend) { newCigar.push_back(CigarOp('M', indel.position - lastend)); newCigar.push_back(CigarOp((indel.insertion ? 'I' : 'D'), indel.length)); } last = *id; lastend = last.insertion ? last.position : (last.position + last.length); } if ((last.position + last.length) < alignedLength) { newCigar.push_back(CigarOp('M', alignedLength - lastend)); } if (!softEnd.empty()) { newCigar.push_back(CigarOp('S', softEnd.size())); } DEBUG(endl); #ifdef VERBOSE_DEBUG if (debug) { for (vector<CigarOp>::const_iterator c = alignment.CigarData.begin(); c != alignment.CigarData.end(); ++c) { unsigned int l = c->Length; char t = c->Type; cerr << l << t; } cerr << endl; } #endif alignment.CigarData = newCigar; for (vector<CigarOp>::const_iterator c = alignment.CigarData.begin(); c != alignment.CigarData.end(); ++c) { unsigned int l = c->Length; char t = c->Type; cigar_after << l << t; } DEBUG(cigar_after.str() << endl); // check if we're realigned if (cigar_after.str() == cigar_before.str()) { return false; } else { return true; } } // Iteratively left-aligns the indels in the alignment until we have a stable // realignment. Returns true on realignment success or non-realignment. // Returns false if we exceed the maximum number of realignment iterations. // bool stablyLeftAlign(BamAlignment& alignment, string referenceSequence, int maxiterations, bool debug) { if (!leftAlign(alignment, referenceSequence, debug)) { DEBUG("did not realign" << endl); return true; } else { while (leftAlign(alignment, referenceSequence, debug) && --maxiterations > 0) { DEBUG("realigning ..." << endl); } if (maxiterations <= 0) { return false; } else { return true; } } } <commit_msg>move flanking sequence of deletion right, moving deletion left<commit_after>#include "LeftAlign.h" //bool debug; // Attempts to left-realign all the indels represented by the alignment cigar. // // This is done by shifting all indels as far left as they can go without // mismatch, then merging neighboring indels of the same class. leftAlign // updates the alignment cigar with changes, and returns true if realignment // changed the alignment cigar. // // To left-align, we move multi-base indels left by their own length as long as // the preceding bases match the inserted or deleted sequence. After this // step, we handle multi-base homopolymer indels by shifting them one base to // the left until they mismatch the reference. // // To merge neighboring indels, we iterate through the set of left-stabilized // indels. For each indel we add a new cigar element to the new cigar. If a // deletion follows a deletion, or an insertion occurs at the same place as // another insertion, we merge the events by extending the previous cigar // element. // // In practice, we must call this function until the alignment is stabilized. // bool leftAlign(BamAlignment& alignment, string& referenceSequence, bool debug) { int arsOffset = 0; // pointer to insertion point in aligned reference sequence string alignedReferenceSequence = referenceSequence; int aabOffset = 0; string alignmentAlignedBases = alignment.QueryBases; // store information about the indels vector<IndelAllele> indels; int rp = 0; // read position, 0-based relative to read int sp = 0; // sequence position string softBegin; string softEnd; stringstream cigar_before, cigar_after; for (vector<CigarOp>::const_iterator c = alignment.CigarData.begin(); c != alignment.CigarData.end(); ++c) { unsigned int l = c->Length; char t = c->Type; cigar_before << l << t; if (t == 'M') { // match or mismatch sp += l; rp += l; } else if (t == 'D') { // deletion indels.push_back(IndelAllele(false, l, sp, rp, referenceSequence.substr(sp, l))); alignmentAlignedBases.insert(rp + aabOffset, string(l, '-')); aabOffset += l; sp += l; // update sample position } else if (t == 'I') { // insertion indels.push_back(IndelAllele(true, l, sp, rp, alignment.QueryBases.substr(rp, l))); alignedReferenceSequence.insert(sp + softBegin.size() + arsOffset, string(l, '-')); arsOffset += l; rp += l; } else if (t == 'S') { // soft clip, clipped sequence present in the read not matching the reference // remove these bases from the refseq and read seq, but don't modify the alignment sequence if (rp == 0) { alignedReferenceSequence = string(l, '*') + alignedReferenceSequence; softBegin = alignmentAlignedBases.substr(0, l); } else { alignedReferenceSequence = alignedReferenceSequence + string(l, '*'); softEnd = alignmentAlignedBases.substr(alignmentAlignedBases.size() - l, l); } rp += l; } else if (t == 'H') { // hard clip on the read, clipped sequence is not present in the read } else if (t == 'N') { // skipped region in the reference not present in read, aka splice sp += l; } } int alignedLength = sp; DEBUG("| " << cigar_before.str() << endl << "| " << alignedReferenceSequence << endl << "| " << alignmentAlignedBases << endl); // if no indels, return the alignment if (indels.empty()) { return false; } // for each indel, from left to right // while the indel sequence repeated to the left and we're not matched up with the left-previous indel // move the indel left vector<IndelAllele>::iterator previous = indels.begin(); for (vector<IndelAllele>::iterator id = indels.begin(); id != indels.end(); ++id) { IndelAllele& indel = *id; int steppos = indel.position - indel.length; int readsteppos = (indel.insertion ? indel.readPosition - indel.length : indel.readPosition) - 1; // repeated subunits, single base homopolymers while (steppos >= 0 && readsteppos >= 0 && indel.sequence == referenceSequence.substr(steppos, indel.length) && indel.sequence == alignment.QueryBases.substr(readsteppos, indel.length) && (id == indels.begin() || (previous->insertion && steppos >= previous->position) || (!previous->insertion && steppos >= previous->position + previous->length))) { DEBUG("indel " << indel << " shifting " << indel.length << "bp left" << endl); indel.position -= indel.length; indel.readPosition -= indel.length; steppos = indel.position - indel.length; readsteppos = (indel.insertion ? indel.readPosition - indel.length : indel.readPosition) - 1; } // multi-base homopolymers if (indel.homopolymer()) { while (indel.position > 0 && indel.sequence == referenceSequence.substr(indel.position - 1, indel.length) && indel.sequence == alignment.QueryBases.substr(indel.readPosition - 1, indel.length) && (id == indels.begin() || indel.position >= previous->position + previous->length)) { DEBUG("indel " << indel << " shifting " << 1 << "bp left" << endl); indel.position -= 1; indel.readPosition -= 1; } } // deletions with exchangeable flanking sequence if (!indel.insertion) { while (indel.position > 0 && indel.sequence.at(indel.sequence.size() - 1) == referenceSequence.at(indel.position - 1) && (id == indels.begin() || indel.position >= previous->position + previous->length)) { indel.sequence = indel.sequence.at(indel.sequence.size() - 1) + indel.sequence.substr(0, indel.sequence.size() - 1); indel.position -= 1; indel.readPosition -= 1; } } previous = id; } // unhandled: // attempt to shift in lengths below the tandem dup size // replaces above loop, but... // buggy code: /* vector<IndelAllele>::iterator previous = indels.begin(); for (vector<IndelAllele>::iterator id = indels.begin(); id != indels.end(); ++id) { IndelAllele& indel = *id; int steppos = indel.position - indel.length; int step = indel.length; while (steppos >= 0 && step > 0) { step = indel.length; steppos = indel.position - step; while (step > 0) { DEBUG(step << endl); if (indel.sequence == referenceSequence.substr(steppos, indel.length) && (id == indels.begin() || (previous->insertion && steppos >= previous->position) || (!previous->insertion && steppos >= previous->position + previous->length))) { DEBUG("indel " << indel << " shifting " << indel.length << "bp left" << endl); indel.position -= step; steppos = indel.position; break; } else { --step; } } } // multi-base homopolymers previous = id; } */ // bring together floating indels // from left to right // check if we could merge with the next indel // if so, adjust so that we will merge in the next step if (indels.size() > 1) { previous = indels.begin(); for (vector<IndelAllele>::iterator id = (indels.begin() + 1); id != indels.end(); ++id) { IndelAllele& indel = *id; // could we shift right and merge with the previous indel? // if so, do it int prev_end = previous->insertion ? previous->position : previous->position + previous->length; if (previous->insertion == indel.insertion && ((previous->insertion && previous->position < indel.position) || (!previous->insertion && previous->position + previous->length < indel.position))) { if (previous->homopolymer()) { string seq = referenceSequence.substr(prev_end, indel.position - prev_end); if (previous->sequence.at(0) == seq.at(0) && homopolymer(seq)) { DEBUG("moving " << *previous << " right to " << (indel.insertion ? indel.position : indel.position - previous->length) << endl); previous->position = indel.insertion ? indel.position : indel.position - previous->length; } } else { int pos = previous->position; while (pos < (int) referenceSequence.length() && ((previous->insertion && pos + previous->length <= indel.position) || (!previous->insertion && pos + previous->length < indel.position)) && previous->sequence == referenceSequence.substr(pos + previous->length, previous->length)) { pos += previous->length; } if (pos < previous->position && ((previous->insertion && pos + previous->length == indel.position) || (!previous->insertion && pos == indel.position - previous->length)) ) { DEBUG("right-merging tandem repeat: moving " << *previous << " right to " << pos << endl); previous->position = pos; } } } } } // for each indel // if ( we're matched up to the previous insertion (or deletion) // and it's also an insertion or deletion ) // merge the indels vector<CigarOp> newCigar; if (!softBegin.empty()) { newCigar.push_back(CigarOp('S', softBegin.size())); } vector<IndelAllele>::iterator id = indels.begin(); IndelAllele last = *id++; if (last.position > 0) { newCigar.push_back(CigarOp('M', last.position)); newCigar.push_back(CigarOp((last.insertion ? 'I' : 'D'), last.length)); } else { newCigar.push_back(CigarOp((last.insertion ? 'I' : 'D'), last.length)); } int lastend = last.insertion ? last.position : (last.position + last.length); DEBUG(last << ","); for (; id != indels.end(); ++id) { IndelAllele& indel = *id; DEBUG(indel << ","); if (indel.position < lastend) { cerr << "impossibility?: indel realigned left of another indel" << endl << alignment.Name << " " << alignment.Position << endl << alignment.QueryBases << endl; exit(1); } else if (indel.position == lastend && indel.insertion == last.insertion) { CigarOp& op = newCigar.back(); op.Length += indel.length; } else if (indel.position > lastend) { newCigar.push_back(CigarOp('M', indel.position - lastend)); newCigar.push_back(CigarOp((indel.insertion ? 'I' : 'D'), indel.length)); } last = *id; lastend = last.insertion ? last.position : (last.position + last.length); } if ((last.position + last.length) < alignedLength) { newCigar.push_back(CigarOp('M', alignedLength - lastend)); } if (!softEnd.empty()) { newCigar.push_back(CigarOp('S', softEnd.size())); } DEBUG(endl); #ifdef VERBOSE_DEBUG if (debug) { for (vector<CigarOp>::const_iterator c = alignment.CigarData.begin(); c != alignment.CigarData.end(); ++c) { unsigned int l = c->Length; char t = c->Type; cerr << l << t; } cerr << endl; } #endif alignment.CigarData = newCigar; for (vector<CigarOp>::const_iterator c = alignment.CigarData.begin(); c != alignment.CigarData.end(); ++c) { unsigned int l = c->Length; char t = c->Type; cigar_after << l << t; } DEBUG(cigar_after.str() << endl); // check if we're realigned if (cigar_after.str() == cigar_before.str()) { return false; } else { return true; } } // Iteratively left-aligns the indels in the alignment until we have a stable // realignment. Returns true on realignment success or non-realignment. // Returns false if we exceed the maximum number of realignment iterations. // bool stablyLeftAlign(BamAlignment& alignment, string referenceSequence, int maxiterations, bool debug) { if (!leftAlign(alignment, referenceSequence, debug)) { DEBUG("did not realign" << endl); return true; } else { while (leftAlign(alignment, referenceSequence, debug) && --maxiterations > 0) { DEBUG("realigning ..." << endl); } if (maxiterations <= 0) { return false; } else { return true; } } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // 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 "FunctionContext.hpp" #include "Labels.hpp" #include "asm/Registers.hpp" #include "ltac/Compiler.hpp" #include "mtac/Utils.hpp" //TODO Perhaps this should be moved to ltac ? using namespace eddic; void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1){ function->add(std::make_shared<ltac::Instruction>(op, arg1)); } void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1, ltac::Argument arg2){ function->add(std::make_shared<ltac::Instruction>(op, arg1, arg2)); } void ltac::Compiler::compile(std::shared_ptr<mtac::Program> source, std::shared_ptr<ltac::Program> target){ for(auto& src_function : source->functions){ auto target_function = std::make_shared<ltac::Function>(src_function->context, src_function->getName()); target->functions.push_back(target_function); compile(src_function, target_function); } } void ltac::Compiler::compile(std::shared_ptr<mtac::Function> src_function, std::shared_ptr<ltac::Function> target_function){ auto size = src_function->context->size(); //Only if necessary, allocates size on the stack for the local variables if(size > 0){ add_instruction(target_function, ltac::Operator::ALLOC_STACK, size); } auto iter = src_function->context->begin(); auto end = src_function->context->end(); for(; iter != end; iter++){ auto var = iter->second; if(var->type().isArray() && var->position().isStack()){ int position = -var->position().offset(); add_instruction(target_function, ltac::Operator::MOV, ltac::Address(ltac::BP, position), var->type().size()); if(var->type().base() == BaseType::INT){ add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), var->type().size()); } else if(var->type().base() == BaseType::STRING){ add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), 2 * var->type().size()); } } } //Compute the block usage (in order to know if we have to output the label) mtac::computeBlockUsage(src_function, block_usage); resetNumbering(); //First we computes a label for each basic block for(auto block : src_function->getBasicBlocks()){ block->label = newLabel(); } //Then we compile each of them for(auto block : src_function->getBasicBlocks()){ compile(block, target_function); } //TODO Return optimization //Only if necessary, deallocates size on the stack for the local variables if(size > 0){ add_instruction(target_function, ltac::Operator::FREE_STACK, size); } } void ltac::Compiler::compile(std::shared_ptr<mtac::BasicBlock> block, std::shared_ptr<ltac::Function> target_function){ //Handle parameters //If necessary add a label for the block if(block_usage.find(block) != block_usage.end()){ target_function->add(block->label); } //statements //end basic block } struct StatementCompiler : public boost::static_visitor<> { //The registers as::Registers<ltac::Register> registers; as::Registers<ltac::FloatRegister> float_registers; }; <commit_msg>Init the registers<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // 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 "FunctionContext.hpp" #include "Labels.hpp" #include "asm/Registers.hpp" #include "ltac/Compiler.hpp" #include "mtac/Utils.hpp" //TODO Perhaps this should be moved to ltac ? using namespace eddic; void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1){ function->add(std::make_shared<ltac::Instruction>(op, arg1)); } void add_instruction(std::shared_ptr<ltac::Function> function, ltac::Operator op, ltac::Argument arg1, ltac::Argument arg2){ function->add(std::make_shared<ltac::Instruction>(op, arg1, arg2)); } void ltac::Compiler::compile(std::shared_ptr<mtac::Program> source, std::shared_ptr<ltac::Program> target){ for(auto& src_function : source->functions){ auto target_function = std::make_shared<ltac::Function>(src_function->context, src_function->getName()); target->functions.push_back(target_function); compile(src_function, target_function); } } void ltac::Compiler::compile(std::shared_ptr<mtac::Function> src_function, std::shared_ptr<ltac::Function> target_function){ auto size = src_function->context->size(); //Only if necessary, allocates size on the stack for the local variables if(size > 0){ add_instruction(target_function, ltac::Operator::ALLOC_STACK, size); } auto iter = src_function->context->begin(); auto end = src_function->context->end(); for(; iter != end; iter++){ auto var = iter->second; if(var->type().isArray() && var->position().isStack()){ int position = -var->position().offset(); add_instruction(target_function, ltac::Operator::MOV, ltac::Address(ltac::BP, position), var->type().size()); if(var->type().base() == BaseType::INT){ add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), var->type().size()); } else if(var->type().base() == BaseType::STRING){ add_instruction(target_function, ltac::Operator::MEMSET, ltac::Address(ltac::BP, position, -8), 2 * var->type().size()); } } } //Compute the block usage (in order to know if we have to output the label) mtac::computeBlockUsage(src_function, block_usage); resetNumbering(); //First we computes a label for each basic block for(auto block : src_function->getBasicBlocks()){ block->label = newLabel(); } //Then we compile each of them for(auto block : src_function->getBasicBlocks()){ compile(block, target_function); } //TODO Return optimization //Only if necessary, deallocates size on the stack for the local variables if(size > 0){ add_instruction(target_function, ltac::Operator::FREE_STACK, size); } } namespace { struct StatementCompiler : public boost::static_visitor<> { //The registers as::Registers<ltac::Register> registers; as::Registers<ltac::FloatRegister> float_registers; StatementCompiler(std::vector<ltac::Register> registers, std::vector<ltac::FloatRegister> float_registers) : registers(registers, std::make_shared<Variable>("__fake_int__", newSimpleType(BaseType::INT), Position(PositionType::TEMPORARY))), float_registers(float_registers, std::make_shared<Variable>("__fake_float__", newSimpleType(BaseType::FLOAT), Position(PositionType::TEMPORARY))){ //Nothing else to init } }; } //end of anonymous namespace void ltac::Compiler::compile(std::shared_ptr<mtac::BasicBlock> block, std::shared_ptr<ltac::Function> target_function){ //Handle parameters //If necessary add a label for the block if(block_usage.find(block) != block_usage.end()){ target_function->add(block->label); } //TODO Fill the registers StatementCompiler compiler({}, {}); //statements //end basic block } <|endoftext|>
<commit_before>// ComDirver.cpp: implementation of the CComDirver class. // ////////////////////////////////////////////////////////////////////// #include "vmlua.h" #include "lua/lua.hpp" #include <stdio.h> #include <string.h> #include <assert.h> #include "hash.h" #include "key.h" #include "main.h" #include <openssl/des.h> #include <vector> #include "vmrunevn.h" #include "tx.h" //#include "Typedef.h" #if 0 typedef struct NumArray{ int size; // С double values[1]; //黺 }NumArray; /* * ȡuserdatum*/ static NumArray *checkarray(lua_State *L){ //ջָλõĶǷΪиֵmetatableuserdatum void *ud = luaL_checkudata(L,1,"LuaBook.array"); luaL_argcheck(L,ud != NULL,1,"'array' expected"); return (NumArray *)ud; } /* * ȡָ*/ static double *getelem(lua_State *L){ NumArray *a = checkarray(L); int index = luaL_checkint(L,2); luaL_argcheck(L,1 <= index && index <= a->size,2,"index out of range"); /*return element address*/ return &a->values[index - 1]; } /* * */ int newarray(lua_State *L){ int n = luaL_checkint(L,1); //֤ʵluaL_checknumberı size_t nbytes = sizeof(NumArray) + (n -1) * sizeof(double); /*һuserdatum ṩһLuaûԤrawڴ ָĴСһڴ棬Ӧuserdatumŵջ,ڴĵַ*/ NumArray *a = (NumArray *)lua_newuserdata(L,nbytes); luaL_getmetatable(L,"LuaBook.array"); //ȡregistryеtnameӦmetatable lua_setmetatable(L,-2); //ջΪλõĶmetatable µuserdatum a->size = n; return 1; /*new userdatnum is already on the statck*/ } /* * 洢Ԫ,array.set(array,index,value)*/ int setarray(lua_State *L){ #if 0 NumArray *a = (NumArray *)lua_touserdata(L,1); int index = luaL_checkint(L,2); double value = luaL_checknumber(L,3); luaL_argcheck(L,a != NULL,1,"'array' expected"); luaL_argcheck(L,1 <= index && index <= a->size,2,"index out of range"); a->values[index -1] = value; #else double newvalue = luaL_checknumber(L,3); *getelem(L) = newvalue; #endif return 0; } /* * ȡһԪ*/ int getarray(lua_State *L){ #if 0 NumArray *a = (NumArray *)lua_touserdata(L,1); int index = luaL_checkint(L,2); luaL_argcheck(L,a != NULL,1,"'array' expected"); luaL_argcheck(L,1 <= index && index <= a->size,2,"index out of range"); lua_pushnumber(L,a->values[index - 1]); #else lua_pushnumber(L,*getelem(L)); #endif return 1; } /* * ȡĴС*/ int getsize(lua_State *L){ #if 0 NumArray *a = (NumArray *)lua_touserdata(L,1); luaL_argcheck(L,a != NULL,1,"'array' expected"); #else NumArray *a = checkarray(L); #endif lua_pushnumber(L,a->size); return 1; } static const struct luaL_Reg arraylib[] = { {"new",newarray}, {"set",setarray}, {"get",getarray}, {"size",getsize}, {NULL,NULL} }; static int luaopen_array(lua_State *L){ /*userdataҪõmetatable*/ luaL_newmetatable(L,"LuaBook.array"); luaL_openlib(L,"array",arraylib,0); /*now the statck has the metatable at index 1 and * 'array' at index 2*/ lua_pushstring(L,"__index"); lua_pushstring(L,"get"); lua_gettable(L,2); /*get array.get*/ lua_settable(L,1); /*metatable.__index - array.get*/ lua_pushstring(L,"__newindex"); lua_pushstring(L,"set"); lua_gettable(L,2); /*get array.get*/ lua_settable(L,1); /*metatable.__newindex - array.get*/ return 0; } #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CVmlua::CVmlua(const vector<unsigned char> & vRom, const vector<unsigned char> &InputData){ unsigned long len = 0; /*vRom script,InputData contract*/ memset(m_ExRam,0,sizeof(m_ExRam)); memset(m_ExeFile,0,sizeof(m_ExeFile)); len = vRom.size(); if(len >= sizeof(m_ExeFile)){ throw runtime_error("CVmlua::CVmlua() length of vRom exceptions"); } memcpy(m_ExeFile, &vRom[0], len); unsigned short count = InputData.size();//С4096ֽ if(count > sizeof(m_ExRam) - 2){ throw runtime_error("CVmlua::CVmlua() length of contract > 4094"); } memcpy(m_ExRam, &count, 2); memcpy(&m_ExRam[2], &InputData[0],count); } CVmlua::~CVmlua() { } #ifdef WIN_DLL extern "C" __declspec(dllexport) int luaopen_mylib(lua_State *L); #else LUAMOD_API int luaopen_mylib(lua_State *L); #endif void vm_openlibs (lua_State *L) { static const luaL_Reg lualibs[] = { { "base", luaopen_base }, { LUA_LOADLIBNAME, luaopen_package }, { LUA_TABLIBNAME, luaopen_table }, { LUA_MATHLIBNAME, luaopen_math }, { LUA_STRLIBNAME, luaopen_string}, { NULL, NULL } }; const luaL_Reg *lib; for (lib = lualibs; lib->func; lib++) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); /* remove lib */ } } tuple<bool,string> CVmlua::syntaxcheck(bool bFile, const char* filePathOrContent, int len) { //1.Luaл lua_State *lua_state = luaL_newstate(); if (NULL == lua_state) { LogPrint("vm", "luaL_newstate error\n"); return std::make_tuple(false, string("luaL_newstate error\n")); } vm_openlibs(lua_state); //3.עԶģ luaL_requiref(lua_state, "mylib", luaopen_mylib, 1); int nRet = 0; if(bFile) { nRet = luaL_loadfile(lua_state, filePathOrContent); } else { nRet = luaL_loadbuffer(lua_state, (char *)filePathOrContent, len, "line"); } if (nRet) { const char* errStr = lua_tostring(lua_state, -1); lua_close(lua_state); return std::make_tuple (false, string(errStr)); } lua_close(lua_state); return std::make_tuple (true, string("OK")); } } int64_t CVmlua::run(uint64_t maxstep,CVmRunEvn *pVmScriptRun) { long long step = 0; unsigned short count = 0; if((maxstep == 0) || (NULL == pVmScriptRun)){ return -1; } //1.Luaл lua_State *lua_state = luaL_newstate(); if(NULL == lua_state){ LogPrint("vm", "luaL_newstate error\n"); return -1; } /* //2.ôעLua׼ static const luaL_Reg lualibs[] = { {"base",luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, // {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, // {LUA_IOLIBNAME, luaopen_io}, // {LUA_OSLIBNAME, luaopen_os}, // {LUA_STRLIBNAME, luaopen_string}, // {LUA_MATHLIBNAME, luaopen_math}, // {LUA_UTF8LIBNAME, luaopen_utf8}, // {LUA_DBLIBNAME, luaopen_debug}, {NULL,NULL} }; //3.עLua׼Ⲣջ const luaL_Reg *lib = lualibs; for(;lib->func != NULL;lib++) { lib->func(lua_state); lua_settop(lua_state,0); } //ҪĿ //luaL_openlibs(lua_state); */ vm_openlibs(lua_state); //3.עԶģ luaL_requiref(lua_state,"mylib",luaopen_mylib,1); //4.luaűݺԼ lua_newtable(lua_state); //½һ,ѹջ lua_pushnumber(lua_state,-1); lua_rawseti(lua_state,-2,0); memcpy(&count,m_ExRam, 2);//ƣԼС4096ֽ for(unsigned short n = 0;n < count;n++) { lua_pushinteger(lua_state,m_ExRam[2 + n]);// valueֵ lua_rawseti(lua_state,-2,n+1); //set table at key 'n + 1' } lua_setglobal(lua_state,"contract"); //pVmScriptRunָ룬Աãȥʹȫֱָ lua_pushlightuserdata(lua_state, pVmScriptRun); lua_setglobal(lua_state,"VmScriptRun"); LogPrint("vm", "pVmScriptRun=%p\n",pVmScriptRun); //5.ؽű step = maxstep; if(luaL_loadbuffer(lua_state,(char *)m_ExeFile,strlen((char *)m_ExeFile),"line") || lua_pcallk(lua_state,0,0,0,0,NULL,&step)) { LogPrint("vm", "luaL_loadbuffer fail:%s\n", lua_tostring(lua_state,-1)); step = -1; lua_close(lua_state); LogPrint("vm", "run step=%ld\n",step); return step; } //6.ƽãĬϹرգűûøñ pVmScriptRun->SetCheckAccount(false); int res = lua_getglobal(lua_state, "gCheckAccount"); LogPrint("vm", "lua_getglobal:%d\n", res); if(LUA_TBOOLEAN == res) { if(lua_isboolean(lua_state,-1)) { bool bCheck = lua_toboolean(lua_state,-1); LogPrint("vm", "lua_toboolean:%d\n", bCheck); pVmScriptRun->SetCheckAccount(bCheck); } } lua_pop(lua_state, 1); //7.رLua lua_close(lua_state); LogPrint("vm", "run step=%ld\n",step); return step; } <commit_msg>修正一个错误:去掉多余的大括号。<commit_after>// ComDirver.cpp: implementation of the CComDirver class. // ////////////////////////////////////////////////////////////////////// #include "vmlua.h" #include "lua/lua.hpp" #include <stdio.h> #include <string.h> #include <assert.h> #include "hash.h" #include "key.h" #include "main.h" #include <openssl/des.h> #include <vector> #include "vmrunevn.h" #include "tx.h" //#include "Typedef.h" #if 0 typedef struct NumArray{ int size; // С double values[1]; //黺 }NumArray; /* * ȡuserdatum*/ static NumArray *checkarray(lua_State *L){ //ջָλõĶǷΪиֵmetatableuserdatum void *ud = luaL_checkudata(L,1,"LuaBook.array"); luaL_argcheck(L,ud != NULL,1,"'array' expected"); return (NumArray *)ud; } /* * ȡָ*/ static double *getelem(lua_State *L){ NumArray *a = checkarray(L); int index = luaL_checkint(L,2); luaL_argcheck(L,1 <= index && index <= a->size,2,"index out of range"); /*return element address*/ return &a->values[index - 1]; } /* * */ int newarray(lua_State *L){ int n = luaL_checkint(L,1); //֤ʵluaL_checknumberı size_t nbytes = sizeof(NumArray) + (n -1) * sizeof(double); /*һuserdatum ṩһLuaûԤrawڴ ָĴСһڴ棬Ӧuserdatumŵջ,ڴĵַ*/ NumArray *a = (NumArray *)lua_newuserdata(L,nbytes); luaL_getmetatable(L,"LuaBook.array"); //ȡregistryеtnameӦmetatable lua_setmetatable(L,-2); //ջΪλõĶmetatable µuserdatum a->size = n; return 1; /*new userdatnum is already on the statck*/ } /* * 洢Ԫ,array.set(array,index,value)*/ int setarray(lua_State *L){ #if 0 NumArray *a = (NumArray *)lua_touserdata(L,1); int index = luaL_checkint(L,2); double value = luaL_checknumber(L,3); luaL_argcheck(L,a != NULL,1,"'array' expected"); luaL_argcheck(L,1 <= index && index <= a->size,2,"index out of range"); a->values[index -1] = value; #else double newvalue = luaL_checknumber(L,3); *getelem(L) = newvalue; #endif return 0; } /* * ȡһԪ*/ int getarray(lua_State *L){ #if 0 NumArray *a = (NumArray *)lua_touserdata(L,1); int index = luaL_checkint(L,2); luaL_argcheck(L,a != NULL,1,"'array' expected"); luaL_argcheck(L,1 <= index && index <= a->size,2,"index out of range"); lua_pushnumber(L,a->values[index - 1]); #else lua_pushnumber(L,*getelem(L)); #endif return 1; } /* * ȡĴС*/ int getsize(lua_State *L){ #if 0 NumArray *a = (NumArray *)lua_touserdata(L,1); luaL_argcheck(L,a != NULL,1,"'array' expected"); #else NumArray *a = checkarray(L); #endif lua_pushnumber(L,a->size); return 1; } static const struct luaL_Reg arraylib[] = { {"new",newarray}, {"set",setarray}, {"get",getarray}, {"size",getsize}, {NULL,NULL} }; static int luaopen_array(lua_State *L){ /*userdataҪõmetatable*/ luaL_newmetatable(L,"LuaBook.array"); luaL_openlib(L,"array",arraylib,0); /*now the statck has the metatable at index 1 and * 'array' at index 2*/ lua_pushstring(L,"__index"); lua_pushstring(L,"get"); lua_gettable(L,2); /*get array.get*/ lua_settable(L,1); /*metatable.__index - array.get*/ lua_pushstring(L,"__newindex"); lua_pushstring(L,"set"); lua_gettable(L,2); /*get array.get*/ lua_settable(L,1); /*metatable.__newindex - array.get*/ return 0; } #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CVmlua::CVmlua(const vector<unsigned char> & vRom, const vector<unsigned char> &InputData){ unsigned long len = 0; /*vRom script,InputData contract*/ memset(m_ExRam,0,sizeof(m_ExRam)); memset(m_ExeFile,0,sizeof(m_ExeFile)); len = vRom.size(); if(len >= sizeof(m_ExeFile)){ throw runtime_error("CVmlua::CVmlua() length of vRom exceptions"); } memcpy(m_ExeFile, &vRom[0], len); unsigned short count = InputData.size();//С4096ֽ if(count > sizeof(m_ExRam) - 2){ throw runtime_error("CVmlua::CVmlua() length of contract > 4094"); } memcpy(m_ExRam, &count, 2); memcpy(&m_ExRam[2], &InputData[0],count); } CVmlua::~CVmlua() { } #ifdef WIN_DLL extern "C" __declspec(dllexport) int luaopen_mylib(lua_State *L); #else LUAMOD_API int luaopen_mylib(lua_State *L); #endif void vm_openlibs (lua_State *L) { static const luaL_Reg lualibs[] = { { "base", luaopen_base }, { LUA_LOADLIBNAME, luaopen_package }, { LUA_TABLIBNAME, luaopen_table }, { LUA_MATHLIBNAME, luaopen_math }, { LUA_STRLIBNAME, luaopen_string}, { NULL, NULL } }; const luaL_Reg *lib; for (lib = lualibs; lib->func; lib++) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); /* remove lib */ } } tuple<bool,string> CVmlua::syntaxcheck(bool bFile, const char* filePathOrContent, int len) { //1.Luaл lua_State *lua_state = luaL_newstate(); if (NULL == lua_state) { LogPrint("vm", "luaL_newstate error\n"); return std::make_tuple(false, string("luaL_newstate error\n")); } vm_openlibs(lua_state); //3.עԶģ luaL_requiref(lua_state, "mylib", luaopen_mylib, 1); int nRet = 0; if(bFile) { nRet = luaL_loadfile(lua_state, filePathOrContent); } else { nRet = luaL_loadbuffer(lua_state, (char *)filePathOrContent, len, "line"); } if (nRet) { const char* errStr = lua_tostring(lua_state, -1); lua_close(lua_state); return std::make_tuple (false, string(errStr)); } lua_close(lua_state); return std::make_tuple (true, string("OK")); } int64_t CVmlua::run(uint64_t maxstep,CVmRunEvn *pVmScriptRun) { long long step = 0; unsigned short count = 0; if((maxstep == 0) || (NULL == pVmScriptRun)){ return -1; } //1.Luaл lua_State *lua_state = luaL_newstate(); if(NULL == lua_state){ LogPrint("vm", "luaL_newstate error\n"); return -1; } /* //2.ôעLua׼ static const luaL_Reg lualibs[] = { {"base",luaopen_base}, {LUA_LOADLIBNAME, luaopen_package}, // {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, // {LUA_IOLIBNAME, luaopen_io}, // {LUA_OSLIBNAME, luaopen_os}, // {LUA_STRLIBNAME, luaopen_string}, // {LUA_MATHLIBNAME, luaopen_math}, // {LUA_UTF8LIBNAME, luaopen_utf8}, // {LUA_DBLIBNAME, luaopen_debug}, {NULL,NULL} }; //3.עLua׼Ⲣջ const luaL_Reg *lib = lualibs; for(;lib->func != NULL;lib++) { lib->func(lua_state); lua_settop(lua_state,0); } //ҪĿ //luaL_openlibs(lua_state); */ vm_openlibs(lua_state); //3.עԶģ luaL_requiref(lua_state,"mylib",luaopen_mylib,1); //4.luaűݺԼ lua_newtable(lua_state); //½һ,ѹջ lua_pushnumber(lua_state,-1); lua_rawseti(lua_state,-2,0); memcpy(&count,m_ExRam, 2);//ƣԼС4096ֽ for(unsigned short n = 0;n < count;n++) { lua_pushinteger(lua_state,m_ExRam[2 + n]);// valueֵ lua_rawseti(lua_state,-2,n+1); //set table at key 'n + 1' } lua_setglobal(lua_state,"contract"); //pVmScriptRunָ룬Աãȥʹȫֱָ lua_pushlightuserdata(lua_state, pVmScriptRun); lua_setglobal(lua_state,"VmScriptRun"); LogPrint("vm", "pVmScriptRun=%p\n",pVmScriptRun); //5.ؽű step = maxstep; if(luaL_loadbuffer(lua_state,(char *)m_ExeFile,strlen((char *)m_ExeFile),"line") || lua_pcallk(lua_state,0,0,0,0,NULL,&step)) { LogPrint("vm", "luaL_loadbuffer fail:%s\n", lua_tostring(lua_state,-1)); step = -1; lua_close(lua_state); LogPrint("vm", "run step=%ld\n",step); return step; } //6.ƽãĬϹرգűûøñ pVmScriptRun->SetCheckAccount(false); int res = lua_getglobal(lua_state, "gCheckAccount"); LogPrint("vm", "lua_getglobal:%d\n", res); if(LUA_TBOOLEAN == res) { if(lua_isboolean(lua_state,-1)) { bool bCheck = lua_toboolean(lua_state,-1); LogPrint("vm", "lua_toboolean:%d\n", bCheck); pVmScriptRun->SetCheckAccount(bCheck); } } lua_pop(lua_state, 1); //7.رLua lua_close(lua_state); LogPrint("vm", "run step=%ld\n",step); return step; } <|endoftext|>
<commit_before>#include "utest.h" #include "math/random.h" #include "math/numeric.h" #include "math/epsilon.h" #include "functions/test.h" #include "text/to_string.h" #include "stoch_optimizer.h" using namespace nano; static void check_function(const function_t& function) { const auto epochs = size_t(100); const auto epoch_size = size_t(1000); const auto trials = size_t(10); const auto dims = function.size(); auto rgen = make_rng(scalar_t(-1), scalar_t(+1)); // generate fixed random trials std::vector<vector_t> x0s(trials); for (auto& x0 : x0s) { x0.resize(dims); rgen(x0.data(), x0.data() + x0.size()); } // optimizers to try const auto ids = get_stoch_optimizers().ids(); for (const auto id : ids) { if ( id == "ngd" || id == "adadelta") { // NGD may not decrease the function to epsilon! // AdaDelta is not even guaranteed to decrease the function! continue; } const auto optimizer = get_stoch_optimizers().get(id); size_t out_of_domain = 0; for (size_t t = 0; t < trials; ++ t) { const auto& x0 = x0s[t]; const auto f0 = function.eval(x0); const auto g_thres = epsilon2<scalar_t>(); // optimize const auto params = stoch_params_t(epochs, epoch_size, epsilon1<scalar_t>()); const auto state = optimizer->minimize(params, function, x0); const auto x = state.x; const auto f = state.f; const auto g = state.convergence_criteria(); // ignore out-of-domain solutions if (!function.is_valid(x)) { out_of_domain ++; continue; } std::cout << function.name() << ", " << id << " [" << (t + 1) << "/" << trials << "]" << ": x = [" << x0.transpose() << "]/[" << x.transpose() << "]" << ", f = " << f0 << "/" << f << ", g = " << g << ".\n"; // check function value decrease NANO_CHECK_LESS_EQUAL(f, f0); // check convergence NANO_CHECK_LESS_EQUAL(g, g_thres); } std::cout << function.name() << ", " << id << ": out of domain " << out_of_domain << "/" << trials << ".\n"; } } NANO_BEGIN_MODULE(test_stoch_optimizers) NANO_CASE(evaluate) { foreach_test_function(make_convex_functions(1, 2), check_function); } NANO_END_MODULE() <commit_msg>faster unit test<commit_after>#include "utest.h" #include "math/random.h" #include "math/numeric.h" #include "math/epsilon.h" #include "functions/test.h" #include "text/to_string.h" #include "stoch_optimizer.h" using namespace nano; static void check_function(const function_t& function) { const auto epochs = size_t(100); const auto epoch_size = size_t(1000); const auto trials = size_t(10); const auto dims = function.size(); auto rgen = make_rng(scalar_t(-1), scalar_t(+1)); // generate fixed random trials std::vector<vector_t> x0s(trials); for (auto& x0 : x0s) { x0.resize(dims); rgen(x0.data(), x0.data() + x0.size()); } // optimizers to try const auto ids = get_stoch_optimizers().ids(); for (const auto id : ids) { if ( id == "ngd" || id == "adadelta") { // NGD may not decrease the function to epsilon! // AdaDelta is not even guaranteed to decrease the function! continue; } const auto optimizer = get_stoch_optimizers().get(id); size_t out_of_domain = 0; for (size_t t = 0; t < trials; ++ t) { const auto& x0 = x0s[t]; const auto f0 = function.eval(x0); const auto g_thres = epsilon2<scalar_t>(); // optimize const auto params = stoch_params_t(epochs, epoch_size, epsilon2<scalar_t>()); const auto state = optimizer->minimize(params, function, x0); const auto x = state.x; const auto f = state.f; const auto g = state.convergence_criteria(); // ignore out-of-domain solutions if (!function.is_valid(x)) { out_of_domain ++; continue; } std::cout << function.name() << ", " << id << " [" << (t + 1) << "/" << trials << "]" << ": x = [" << x0.transpose() << "]/[" << x.transpose() << "]" << ", f = " << f0 << "/" << f << ", g = " << g << ".\n"; // check function value decrease NANO_CHECK_LESS_EQUAL(f, f0); // check convergence NANO_CHECK_LESS_EQUAL(g, g_thres); } std::cout << function.name() << ", " << id << ": out of domain " << out_of_domain << "/" << trials << ".\n"; } } NANO_BEGIN_MODULE(test_stoch_optimizers) NANO_CASE(evaluate) { foreach_test_function(make_convex_functions(1, 2), check_function); } NANO_END_MODULE() <|endoftext|>
<commit_before>// (C) 2014 Arek Olek #pragma once #include <chrono> #include <random> #include <tuple> #include <boost/graph/graphml.hpp> #include "algorithm.hpp" #include "graph.hpp" template <class Iterator> void generate_seeds(Iterator begin, Iterator end, std::string seed) { std::seed_seq seq(seed.begin(), seed.end()); seq.generate(begin, end); } double pr_within(double x) { return x <= 1 ? .5*x*x*x*x - 8./3*x*x*x + M_PI*x*x : -.5*x*x*x*x - 4*x*x*atan(sqrt(x*x-1)) + 4./3*(2*x*x+1)*sqrt(x*x-1) + (M_PI-2)*x*x + 1./3; }; template <class Graph> class test_suite { public: unsigned size() const { return seeds.size() * degrees.size() * sizes.size(); } std::string type() const { return t; } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { auto run = i % seeds.size(); std::default_random_engine generator(seeds[run]); auto expected_degree = degrees[(i / seeds.size()) % degrees.size()]; auto n = sizes[i / seeds.size() / degrees.size()]; auto d = expected_degree; auto tree_degree = 2.*(n-1)/n; bool mst = found("mst", t); bool unite = !found("++", t); Graph G(n), G_shuffled(n); if(found("path", t)) { add_spider(G, 1, generator); // the overlap satisfies y = a x + b // full graph satisfies: 0 = a (n-1) + b // tree graph satisfies: 2(n-1)/n = a 2(n-1)/n + b // so we must subtract this: if(unite) d -= 2./(2.-n) * d + 1. + n/(n-2.); } double parameter; if(found("rgg", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/sinh(d-sqrt(2.)); // approximate fit parameter = find_argument(d/(n-1), pr_within, 0, sqrt(2.)); Geometric points(n, generator); points.add_random_geometric(G, parameter); if(mst) points.add_mst(G); } else if(found("gnp", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/(2*M_PI*sinh(d-M_PI/sqrt(3.))); // approximate fit parameter = d<0 ? 0 : d/(n-1); add_edges_uniform(G, parameter, generator, mst); } copy_edges_shuffled(G, G_shuffled, generator); return std::make_tuple(G_shuffled, run, expected_degree, parameter); } template<class Sizes, class Degrees> test_suite(std::string t, unsigned z, Sizes ns, Degrees ds, std::string seed) : t(t), sizes(ns), degrees(ds) { seeds.resize(z); generate_seeds(seeds.begin(), seeds.end(), seed); } private: std::string t; std::vector<unsigned> sizes; std::vector<double> degrees; std::vector<unsigned> seeds; }; template <class Graph> class file_suite { public: std::tuple<Graph, unsigned, double, double> get(unsigned i) const { return std::make_tuple(graphs[i], i, 0, 0); } unsigned size() const { return graphs.size(); } file_suite(std::string f) : t(f.substr(0, f.find('.'))) { std::ifstream file(f); if(!file.good()) { throw std::invalid_argument("File does not exist: " + f); } int z, n, m, s, t; file >> z; while(z--) { file >> n >> m; Graph G(n); for(int i = 0; i < m; ++i) { file >> s >> t; add_edge(s, t, G); } graphs.push_back(G); } file.close(); } std::string type() const { return t; } private: std::string t; std::vector<Graph> graphs; }; template <class Graph> class real_suite { public: unsigned size() const { return seeds.size(); } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { std::default_random_engine generator(seeds[i]); Graph g(num_vertices(G)); copy_edges_shuffled(G, g, generator); return std::make_tuple(g, i, 0, 0); } real_suite(std::string f, unsigned size, std::string seed) : G(0), t(f.substr(0, f.find('.'))), seeds(size) { std::ifstream file(f); if (!file.good()) { throw std::invalid_argument("File does not exist: " + f); } boost::dynamic_properties dp; read_graphml(file, G, dp); generate_seeds(seeds.begin(), seeds.end(), seed); } std::string type() const { return t; } private: Graph G; std::string t; std::vector<unsigned> seeds; }; <commit_msg>add special meaning to parameter -d when less than 1<commit_after>// (C) 2014 Arek Olek #pragma once #include <chrono> #include <random> #include <tuple> #include <boost/graph/graphml.hpp> #include "algorithm.hpp" #include "graph.hpp" template <class Iterator> void generate_seeds(Iterator begin, Iterator end, std::string seed) { std::seed_seq seq(seed.begin(), seed.end()); seq.generate(begin, end); } double pr_within(double x) { return x <= 1 ? .5*x*x*x*x - 8./3*x*x*x + M_PI*x*x : -.5*x*x*x*x - 4*x*x*atan(sqrt(x*x-1)) + 4./3*(2*x*x+1)*sqrt(x*x-1) + (M_PI-2)*x*x + 1./3; }; template <class Graph> class test_suite { public: unsigned size() const { return seeds.size() * degrees.size() * sizes.size(); } std::string type() const { return t; } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { auto run = i % seeds.size(); std::default_random_engine generator(seeds[run]); auto expected_degree = degrees[(i / seeds.size()) % degrees.size()]; auto n = sizes[i / seeds.size() / degrees.size()]; auto d = expected_degree; auto tree_degree = 2.*(n-1)/n; bool mst = found("mst", t); bool unite = !found("++", t); Graph G(n), G_shuffled(n); // use d in [0,1] to mean density (since connected graphs have d > 1 anyway) if(unite && d <= 1) d *= n-1; if(found("path", t)) { add_spider(G, 1, generator); // the overlap satisfies y = a x + b // full graph satisfies: 0 = a (n-1) + b // tree graph satisfies: 2(n-1)/n = a 2(n-1)/n + b // so we must subtract this: if(unite) d -= 2./(2.-n) * d + 1. + n/(n-2.); } double parameter; if(found("rgg", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/sinh(d-sqrt(2.)); // approximate fit parameter = find_argument(d/(n-1), pr_within, 0, sqrt(2.)); Geometric points(n, generator); points.add_random_geometric(G, parameter); if(mst) points.add_mst(G); } else if(found("gnp", t)) { if(mst && unite) d -= d<2 ? tree_degree : 1/(2*M_PI*sinh(d-M_PI/sqrt(3.))); // approximate fit parameter = d<0 ? 0 : d/(n-1); add_edges_uniform(G, parameter, generator, mst); } copy_edges_shuffled(G, G_shuffled, generator); return std::make_tuple(G_shuffled, run, expected_degree, parameter); } template<class Sizes, class Degrees> test_suite(std::string t, unsigned z, Sizes ns, Degrees ds, std::string seed) : t(t), sizes(ns), degrees(ds) { seeds.resize(z); generate_seeds(seeds.begin(), seeds.end(), seed); } private: std::string t; std::vector<unsigned> sizes; std::vector<double> degrees; std::vector<unsigned> seeds; }; template <class Graph> class file_suite { public: std::tuple<Graph, unsigned, double, double> get(unsigned i) const { return std::make_tuple(graphs[i], i, 0, 0); } unsigned size() const { return graphs.size(); } file_suite(std::string f) : t(f.substr(0, f.find('.'))) { std::ifstream file(f); if(!file.good()) { throw std::invalid_argument("File does not exist: " + f); } int z, n, m, s, t; file >> z; while(z--) { file >> n >> m; Graph G(n); for(int i = 0; i < m; ++i) { file >> s >> t; add_edge(s, t, G); } graphs.push_back(G); } file.close(); } std::string type() const { return t; } private: std::string t; std::vector<Graph> graphs; }; template <class Graph> class real_suite { public: unsigned size() const { return seeds.size(); } std::tuple<Graph, unsigned, double, double> get(unsigned i) const { std::default_random_engine generator(seeds[i]); Graph g(num_vertices(G)); copy_edges_shuffled(G, g, generator); return std::make_tuple(g, i, 0, 0); } real_suite(std::string f, unsigned size, std::string seed) : G(0), t(f.substr(0, f.find('.'))), seeds(size) { std::ifstream file(f); if (!file.good()) { throw std::invalid_argument("File does not exist: " + f); } boost::dynamic_properties dp; read_graphml(file, G, dp); generate_seeds(seeds.begin(), seeds.end(), seed); } std::string type() const { return t; } private: Graph G; std::string t; std::vector<unsigned> seeds; }; <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <warnings.h> #include <sync.h> #include <util/system.h> #include <util/translation.h> static RecursiveMutex cs_warnings; static std::string strMiscWarning GUARDED_BY(cs_warnings); static bool fLargeWorkForkFound GUARDED_BY(cs_warnings) = false; static bool fLargeWorkInvalidChainFound GUARDED_BY(cs_warnings) = false; void SetMiscWarning(const std::string& strWarning) { LOCK(cs_warnings); strMiscWarning = strWarning; } void SetfLargeWorkForkFound(bool flag) { LOCK(cs_warnings); fLargeWorkForkFound = flag; } bool GetfLargeWorkForkFound() { LOCK(cs_warnings); return fLargeWorkForkFound; } void SetfLargeWorkInvalidChainFound(bool flag) { LOCK(cs_warnings); fLargeWorkInvalidChainFound = flag; } std::string GetWarnings(bool verbose) { std::string warnings_concise; std::string warnings_verbose; const std::string uiAlertSeperator = "<hr />"; LOCK(cs_warnings); if (!CLIENT_VERSION_IS_RELEASE) { warnings_concise = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"; warnings_verbose = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications").translated; } // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { warnings_concise = strMiscWarning; warnings_verbose += (warnings_verbose.empty() ? "" : uiAlertSeperator) + strMiscWarning; } if (fLargeWorkForkFound) { warnings_concise = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues."; warnings_verbose += (warnings_verbose.empty() ? "" : uiAlertSeperator) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.").translated; } else if (fLargeWorkInvalidChainFound) { warnings_concise = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."; warnings_verbose += (warnings_verbose.empty() ? "" : uiAlertSeperator) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.").translated; } if (verbose) return warnings_verbose; else return warnings_concise; } <commit_msg>[style] Code style fixups in GetWarnings()<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <warnings.h> #include <sync.h> #include <util/system.h> #include <util/translation.h> static RecursiveMutex cs_warnings; static std::string strMiscWarning GUARDED_BY(cs_warnings); static bool fLargeWorkForkFound GUARDED_BY(cs_warnings) = false; static bool fLargeWorkInvalidChainFound GUARDED_BY(cs_warnings) = false; void SetMiscWarning(const std::string& strWarning) { LOCK(cs_warnings); strMiscWarning = strWarning; } void SetfLargeWorkForkFound(bool flag) { LOCK(cs_warnings); fLargeWorkForkFound = flag; } bool GetfLargeWorkForkFound() { LOCK(cs_warnings); return fLargeWorkForkFound; } void SetfLargeWorkInvalidChainFound(bool flag) { LOCK(cs_warnings); fLargeWorkInvalidChainFound = flag; } std::string GetWarnings(bool verbose) { std::string warnings_concise; std::string warnings_verbose; const std::string warning_separator = "<hr />"; LOCK(cs_warnings); // Pre-release build warning if (!CLIENT_VERSION_IS_RELEASE) { warnings_concise = "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"; warnings_verbose = _("This is a pre-release test build - use at your own risk - do not use for mining or merchant applications").translated; } // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { warnings_concise = strMiscWarning; warnings_verbose += (warnings_verbose.empty() ? "" : warning_separator) + strMiscWarning; } if (fLargeWorkForkFound) { warnings_concise = "Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues."; warnings_verbose += (warnings_verbose.empty() ? "" : warning_separator) + _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.").translated; } else if (fLargeWorkInvalidChainFound) { warnings_concise = "Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."; warnings_verbose += (warnings_verbose.empty() ? "" : warning_separator) + _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.").translated; } if (verbose) return warnings_verbose; else return warnings_concise; } <|endoftext|>
<commit_before> #include <windows.h> #include "yacasprivate.h" #include "lispenvironment.h" #include "lispplugin.h" #include "lispassert.h" #include "platdll.h" LispInt Win32Dll::Open(LispCharPtr aDllFile,LispEnvironment& aEnvironment) { iDllFileName = aDllFile; handle = LoadLibrary(aDllFile); if (handle) { iPlugin = GetPlugin(aDllFile); if (iPlugin) { iPlugin->Add(aEnvironment); } } return (handle != NULL && iPlugin != NULL); } LispInt Win32Dll::Close(LispEnvironment& aEnvironment) { if (iPlugin) { iPlugin->Remove(aEnvironment); delete iPlugin; iPlugin = NULL; return 1; } return 0; } Win32Dll::~Win32Dll() { if (handle) { LISPASSERT(iPlugin == NULL); FreeLibrary((HMODULE) handle); } handle = NULL; } LispPluginBase* Win32Dll::GetPlugin(LispCharPtr aDllFile) { LISPASSERT(handle != NULL); LispPluginBase* (*maker)(void); char buf[1024]; //TODO potential buffer overflow! sprintf(buf,"make_%s",aDllFile); maker = (LispPluginBase*(*)(void))GetProcAddress((HMODULE)handle,buf); return maker(); } <commit_msg>small patch to make windows version compile again.<commit_after> #include <windows.h> #include <stdlib.h> #include <stdio.h> #include "yacasprivate.h" #include "lispenvironment.h" #include "lispplugin.h" #include "lispassert.h" #include "platdll.h" LispInt Win32Dll::Open(LispCharPtr aDllFile,LispEnvironment& aEnvironment) { iDllFileName = aDllFile; handle = LoadLibrary(aDllFile); if (handle) { iPlugin = GetPlugin(aDllFile); if (iPlugin) { iPlugin->Add(aEnvironment); } } return (handle != NULL && iPlugin != NULL); } LispInt Win32Dll::Close(LispEnvironment& aEnvironment) { if (iPlugin) { iPlugin->Remove(aEnvironment); delete iPlugin; iPlugin = NULL; return 1; } return 0; } Win32Dll::~Win32Dll() { if (handle) { LISPASSERT(iPlugin == NULL); FreeLibrary((HMODULE) handle); } handle = NULL; } LispPluginBase* Win32Dll::GetPlugin(LispCharPtr aDllFile) { LISPASSERT(handle != NULL); LispPluginBase* (*maker)(void); char buf[1024]; //TODO potential buffer overflow! sprintf(buf,"make_%s",aDllFile); maker = (LispPluginBase*(*)(void))GetProcAddress((HMODULE)handle,buf); return maker(); } <|endoftext|>
<commit_before>/** * @file Heap.cpp * @author niob * @date Oct 21, 2016 * @brief Defines the {@link Heap} and {@link HeapBase} classes. */ #include "Heap.hpp" #include <algorithm> #include <cassert> #include <iomanip> #include <iterator> #include <utility> #include <type_traits> #include "RestoreStream.hpp" #include "TaggedPointer.hpp" namespace ssw { /** * Represents a block of memory in the heap. This class holds the block size and either a pointer to the * type of the stored object (in case the block is used) or a pointer to the next free block. */ class alignas(HeapBase::Align) HeapBase::Block { std::size_t mSize; TaggedPointer mPtr; public: /** * Initialize a new, free block with the specified size. * * @param size The usable size of the block (will be properly aligned). * @param next (optional) The next block in the free list. */ explicit Block(std::size_t size, Block *next = nullptr) noexcept : mSize(size), mPtr(next) { assert(size >= Align); mPtr.free(true); } /** * Get the data size of this block. * * @return The usable size of this block, not including the block descriptor. */ std::size_t size() const noexcept { return mSize; } /** * Mark this block as free and set the next block in the free list. * * @param next The next block in the free list, or `nullptr`. */ void next(Block *next) noexcept { assert(next != this); mPtr = next; mPtr.free(true); } /** * Mark this block as free and set its successor and size. * * @param next The next block in the free list, or `nullptr`. * @param size The usable size of this block, not including the block descriptor. */ void next(Block *next, std::size_t size) noexcept { this->next(next); assert(size >= Align); mSize = size; } /** * Get the next block in the free list. This block must represent a free block. * * @return Pointer to the next block in the free list. */ Block* next() const noexcept { assert(this->free() && !this->mark()); return mPtr.get<Block>(); } /** * Get a pointer to the block following this block in the heap. * * @return Pointer to the physically next block in the heap. */ Block* following() const noexcept { return reinterpret_cast<Block*>(this->data() + align(mSize)); } /** * Mark this block as used and set the data type. * * @param type The type descriptor for the data in this block. */ void type(const TypeDescriptor &type) noexcept { mPtr = &type; mPtr.free(false); } /** * Get the data type in this block. This block must represent a used block. * * @return Reference to the type descriptor for the data in this block. */ const TypeDescriptor& type() const noexcept { assert(this->used() && !this->mark()); return *mPtr.get<const TypeDescriptor>(); } /** * Get whether this block is free. * * @return `true` if this block is part of the free list and does not hold an object. */ bool free() const noexcept { return mPtr.free(); } /** * Get whether this block is used. * * @return `true` if this block contains an object and is not part of the free list. */ bool used() const noexcept { return mPtr.used(); } /** * Get the GC mark for this block. * * @return `true` if the mark is set, `false` otherwise. */ bool mark() const noexcept { return mPtr.mark(); } /** * Get the pointer in this block. * * @return Reference to the pointer. */ TaggedPointer& ptr() noexcept { return mPtr; } /** * Get a pointer to the data portion of this block. * * @return Pointer to the data portion of this block. */ byte* data() const noexcept { return const_cast<byte*>(reinterpret_cast<const byte*>(this) + Align); } /** * Split this block in two blocks if possible. If there is enough space for another block, then this * block will be resized to the new size and a new block will be added after it; if there is not enough * space then nothing will be changed. This block must be a free block. * * @param newSize The new size of this block, will be properly aligned. */ void split(std::size_t newSize) noexcept { assert(this->free()); const std::size_t restSize = align(mSize) - align(newSize) - Align; if(restSize >= Align) { Block *newBlock = reinterpret_cast<Block*>(reinterpret_cast<byte*>(this) + Align + align(newSize)); new(newBlock) Block(restSize, mPtr.get<Block>()); mPtr = newBlock; } } }; HeapBase::HeapBase(byte *storage, std::size_t size) noexcept : mFreeList(reinterpret_cast<Block*>(storage)), mHeapStart(reinterpret_cast<Block*>(storage)), mHeapEnd(reinterpret_cast<Block*>(storage + (size & ~(Align - 1)))), mRoots() { static_assert(sizeof(Block) <= Align, "Block class is too large"); assert((reinterpret_cast<std::uintptr_t>(storage) & (Align - 1)) == 0); assert(size >= 2 * Align); new(mFreeList) Block(size - Align); } void* HeapBase::allocate(const TypeDescriptor &type, bool isRoot) noexcept { if(mFreeList == nullptr) { // There are no free blocks at all, don't even try return nullptr; } auto result = this->tryAllocate(type); if(!result) { // No sufficiently sized block found using first-fit, merge blocks and try again this->mergeBlocks(); result = this->tryAllocate(type); } if(result && isRoot) { this->registerRoot(result); } return result; } void* HeapBase::tryAllocate(const TypeDescriptor &type) noexcept { Block *prev = nullptr; Block *cur = mFreeList; // Use first-fit method to find a block while(cur && cur->size() < type.size()) { prev = std::exchange(cur, cur->next()); } if(cur) { cur->split(type.size()); if(prev) { prev->next(cur->next()); } else { mFreeList = cur->next(); } cur->type(type); return cur->data(); } return nullptr; } void HeapBase::mergeBlocks() noexcept { // TODO implement merging of free blocks } void HeapBase::deallocate(byte *obj) noexcept { Block &blk = block(obj); assert(blk.used() /* Tried to deallocate an unused block */); assert(!blk.mark() /* Tried to deallocate during garbage collection (GC builds a new free list itself) */); blk.next(mFreeList); mFreeList = &blk; } void HeapBase::gc() noexcept { for(auto root : mRoots) { this->mark(root); } this->rebuildFreeList(); } // Mark the object graph for the specified heap root object using the Deutsch-Schorr-Waite marking algorithm void HeapBase::mark(byte *root) noexcept { assert(root); assert(!block(root).mark()); byte *cur = root; byte *prev = nullptr; while(true) { auto &blk = block(cur); if(!blk.mark()) { // Mark the object and begin iteration blk.ptr() = blk.type().begin(); blk.ptr().mark(true); } else { blk.ptr() = blk.ptr().get<const std::ptrdiff_t>() + 1; } auto offset = *blk.ptr().get<const std::ptrdiff_t>(); if(offset >= 0) { // Advance auto &field = *reinterpret_cast<byte**>(cur + offset); if(field && !block(field).mark()) { auto tmp = std::exchange(field, prev); prev = std::exchange(cur, tmp); } } else { // Retreat blk.ptr() = reinterpret_cast<const TypeDescriptor*>( reinterpret_cast<const byte*>(blk.ptr().get<const std::ptrdiff_t>()) + offset); if(!prev) { return; } auto tmp = std::exchange(cur, prev); offset = *block(cur).ptr().get<std::ptrdiff_t>(); prev = std::exchange(*reinterpret_cast<byte**>(cur + offset), tmp); } } // while(true) } // Rebuild the free list while destroying garbage objects void HeapBase::rebuildFreeList() noexcept { Block *freeList = nullptr; for(Block *blk = mHeapStart; blk < mHeapEnd;) { if(blk->mark()) { blk->ptr().mark(false); blk = blk->following(); } else { auto free = blk; // Extend the free block, destroying garbage objects as necessary do { if(free->used()) { free->type().destroy(free->data()); } free = free->following(); } while(free < mHeapEnd && !free->mark()); static_assert(std::is_trivially_destructible<Block>::value, "Block must be trivially destructible."); blk->next(freeList, reinterpret_cast<byte*>(free) - reinterpret_cast<byte*>(blk) - Align); freeList = blk; blk = free; } } mFreeList = freeList; } void HeapBase::dump(std::ostream &os) { RestoreStream osRestore{os}; const HeapStats stats = this->collectHeapStats(true); os << "==== Statistics for heap at 0x" << std::hex << mHeapStart << std::dec << " ====\n"; os << "Heap size: " << stats.heapSize << " bytes\n"; os << "Used space: " << stats.usedSize << " bytes\n"; os << "Free space: " << stats.freeSize << " bytes\n"; os << '\n'; os << "Object count: " << stats.numObjects << " (" << stats.numLiveObjects << " live)\n"; os << "Object size: " << stats.objectSize << " bytes (" << stats.liveObjectSize << " in live objects)\n"; os << "Available space: " << stats.freeBlockSize << "bytes in " << stats.numFreeBlocks << " blocks\n"; os << '\n'; os << "= Free Blocks =\nAddress Size(net)\n"; // Print free blocks: just use the free list os.fill('0'); for(auto blk = mFreeList; blk; blk = blk->next()) { os << std::hex << "0x" << std::setw(sizeof(void*)) << blk << ' ' << std::dec << blk->size() << '\n'; } os << std::setfill(' ') << '\n'; os << "= Live Objects =\n"; // For printing live objects we need to do marking this->dumpLiveObjects(os); } void HeapBase::dumpLiveObjects(std::ostream &os) { constexpr std::size_t numDataBytes = 4; static const std::string indent(4, ' '); for(auto root : mRoots) { this->mark(root); } os << std::hex; for(auto blk = mHeapStart; blk < mHeapEnd; blk = blk->following()) { if(blk->mark()) { blk->ptr().mark(false); os << blk->data() << ' ' << "TODO NAME" << '\n'; os << " Data: "; std::copy_n(blk->data(), std::min(blk->type().size(), numDataBytes), std::ostream_iterator<int>(os, " ")); if(blk->type().size() > numDataBytes) { os << "..."; } os << "\n Pointers: "; if(blk->type().offsets() > 0) { os << "\n"; for(auto offset : blk->type()) { os << indent << *reinterpret_cast<void**>(blk->data() + offset) << '\n'; } } else { os << "none\n"; } } // if(blk->mark()) } os << std::dec; } HeapBase::HeapStats HeapBase::collectHeapStats(bool countLiveObjects) noexcept { HeapStats result{}; result.heapSize = reinterpret_cast<byte*>(mHeapEnd) - reinterpret_cast<byte*>(mHeapStart); if(countLiveObjects) { for(auto root : mRoots) { this->mark(root); } } for(auto blk = mHeapStart; blk < mHeapEnd; blk = blk->following()) { if(blk->free()) { result.numFreeBlocks++; result.freeBlockSize += blk->size(); result.freeSize += Align + align(blk->size()); } else { if(blk->mark()) { blk->ptr().mark(false); result.numLiveObjects++; result.liveObjectSize += blk->type().size(); } result.numObjects++; result.objectSize += blk->type().size(); result.usedSize += Align + align(blk->size()); } } assert(result.freeSize + result.usedSize == result.heapSize); return result; } } // namespace ssw <commit_msg>Fix errors in dump output.<commit_after>/** * @file Heap.cpp * @author niob * @date Oct 21, 2016 * @brief Defines the {@link Heap} and {@link HeapBase} classes. */ #include "Heap.hpp" #include <algorithm> #include <cassert> #include <iomanip> #include <iterator> #include <utility> #include <type_traits> #include "RestoreStream.hpp" #include "TaggedPointer.hpp" namespace ssw { /** * Represents a block of memory in the heap. This class holds the block size and either a pointer to the * type of the stored object (in case the block is used) or a pointer to the next free block. */ class alignas(HeapBase::Align) HeapBase::Block { std::size_t mSize; TaggedPointer mPtr; public: /** * Initialize a new, free block with the specified size. * * @param size The usable size of the block (will be properly aligned). * @param next (optional) The next block in the free list. */ explicit Block(std::size_t size, Block *next = nullptr) noexcept : mSize(size), mPtr(next) { assert(size >= Align); mPtr.free(true); } /** * Get the data size of this block. * * @return The usable size of this block, not including the block descriptor. */ std::size_t size() const noexcept { return mSize; } /** * Mark this block as free and set the next block in the free list. * * @param next The next block in the free list, or `nullptr`. */ void next(Block *next) noexcept { assert(next != this); mPtr = next; mPtr.free(true); } /** * Mark this block as free and set its successor and size. * * @param next The next block in the free list, or `nullptr`. * @param size The usable size of this block, not including the block descriptor. */ void next(Block *next, std::size_t size) noexcept { this->next(next); assert(size >= Align); mSize = size; } /** * Get the next block in the free list. This block must represent a free block. * * @return Pointer to the next block in the free list. */ Block* next() const noexcept { assert(this->free() && !this->mark()); return mPtr.get<Block>(); } /** * Get a pointer to the block following this block in the heap. * * @return Pointer to the physically next block in the heap. */ Block* following() const noexcept { return reinterpret_cast<Block*>(this->data() + align(mSize)); } /** * Mark this block as used and set the data type. * * @param type The type descriptor for the data in this block. */ void type(const TypeDescriptor &type) noexcept { mPtr = &type; mPtr.free(false); } /** * Get the data type in this block. This block must represent a used block. * * @return Reference to the type descriptor for the data in this block. */ const TypeDescriptor& type() const noexcept { assert(this->used() && !this->mark()); return *mPtr.get<const TypeDescriptor>(); } /** * Get whether this block is free. * * @return `true` if this block is part of the free list and does not hold an object. */ bool free() const noexcept { return mPtr.free(); } /** * Get whether this block is used. * * @return `true` if this block contains an object and is not part of the free list. */ bool used() const noexcept { return mPtr.used(); } /** * Get the GC mark for this block. * * @return `true` if the mark is set, `false` otherwise. */ bool mark() const noexcept { return mPtr.mark(); } /** * Get the pointer in this block. * * @return Reference to the pointer. */ TaggedPointer& ptr() noexcept { return mPtr; } /** * Get a pointer to the data portion of this block. * * @return Pointer to the data portion of this block. */ byte* data() const noexcept { return const_cast<byte*>(reinterpret_cast<const byte*>(this) + Align); } /** * Split this block in two blocks if possible. If there is enough space for another block, then this * block will be resized to the new size and a new block will be added after it; if there is not enough * space then nothing will be changed. This block must be a free block. * * @param newSize The new size of this block, will be properly aligned. */ void split(std::size_t newSize) noexcept { assert(this->free()); const std::size_t restSize = align(mSize) - align(newSize) - Align; if(restSize >= Align) { Block *newBlock = reinterpret_cast<Block*>(reinterpret_cast<byte*>(this) + Align + align(newSize)); new(newBlock) Block(restSize, mPtr.get<Block>()); mPtr = newBlock; } } }; HeapBase::HeapBase(byte *storage, std::size_t size) noexcept : mFreeList(reinterpret_cast<Block*>(storage)), mHeapStart(reinterpret_cast<Block*>(storage)), mHeapEnd(reinterpret_cast<Block*>(storage + (size & ~(Align - 1)))), mRoots() { static_assert(sizeof(Block) <= Align, "Block class is too large"); assert((reinterpret_cast<std::uintptr_t>(storage) & (Align - 1)) == 0); assert(size >= 2 * Align); new(mFreeList) Block(size - Align); } void* HeapBase::allocate(const TypeDescriptor &type, bool isRoot) noexcept { if(mFreeList == nullptr) { // There are no free blocks at all, don't even try return nullptr; } auto result = this->tryAllocate(type); if(!result) { // No sufficiently sized block found using first-fit, merge blocks and try again this->mergeBlocks(); result = this->tryAllocate(type); } if(result && isRoot) { this->registerRoot(result); } return result; } void* HeapBase::tryAllocate(const TypeDescriptor &type) noexcept { Block *prev = nullptr; Block *cur = mFreeList; // Use first-fit method to find a block while(cur && cur->size() < type.size()) { prev = std::exchange(cur, cur->next()); } if(cur) { cur->split(type.size()); if(prev) { prev->next(cur->next()); } else { mFreeList = cur->next(); } cur->type(type); return cur->data(); } return nullptr; } void HeapBase::mergeBlocks() noexcept { // TODO implement merging of free blocks } void HeapBase::deallocate(byte *obj) noexcept { Block &blk = block(obj); assert(blk.used() /* Tried to deallocate an unused block */); assert(!blk.mark() /* Tried to deallocate during garbage collection (GC builds a new free list itself) */); blk.next(mFreeList); mFreeList = &blk; } void HeapBase::gc() noexcept { for(auto root : mRoots) { this->mark(root); } this->rebuildFreeList(); } // Mark the object graph for the specified heap root object using the Deutsch-Schorr-Waite marking algorithm void HeapBase::mark(byte *root) noexcept { assert(root); assert(!block(root).mark()); byte *cur = root; byte *prev = nullptr; while(true) { auto &blk = block(cur); if(!blk.mark()) { // Mark the object and begin iteration blk.ptr() = blk.type().begin(); blk.ptr().mark(true); } else { blk.ptr() = blk.ptr().get<const std::ptrdiff_t>() + 1; } auto offset = *blk.ptr().get<const std::ptrdiff_t>(); if(offset >= 0) { // Advance auto &field = *reinterpret_cast<byte**>(cur + offset); if(field && !block(field).mark()) { auto tmp = std::exchange(field, prev); prev = std::exchange(cur, tmp); } } else { // Retreat blk.ptr() = reinterpret_cast<const TypeDescriptor*>( reinterpret_cast<const byte*>(blk.ptr().get<const std::ptrdiff_t>()) + offset); if(!prev) { return; } auto tmp = std::exchange(cur, prev); offset = *block(cur).ptr().get<std::ptrdiff_t>(); prev = std::exchange(*reinterpret_cast<byte**>(cur + offset), tmp); } } // while(true) } // Rebuild the free list while destroying garbage objects void HeapBase::rebuildFreeList() noexcept { Block *freeList = nullptr; for(Block *blk = mHeapStart; blk < mHeapEnd;) { if(blk->mark()) { blk->ptr().mark(false); blk = blk->following(); } else { auto free = blk; // Extend the free block, destroying garbage objects as necessary do { if(free->used()) { free->type().destroy(free->data()); } free = free->following(); } while(free < mHeapEnd && !free->mark()); static_assert(std::is_trivially_destructible<Block>::value, "Block must be trivially destructible."); blk->next(freeList, reinterpret_cast<byte*>(free) - reinterpret_cast<byte*>(blk) - Align); freeList = blk; blk = free; } } mFreeList = freeList; } void HeapBase::dump(std::ostream &os) { RestoreStream osRestore{os}; const HeapStats stats = this->collectHeapStats(true); os << "==== Statistics for heap at " << std::hex << mHeapStart << std::dec << " ====\n"; os << "Heap size: " << stats.heapSize << " bytes\n"; os << "Used space: " << stats.usedSize << " bytes\n"; os << "Free space: " << stats.freeSize << " bytes\n"; os << '\n'; os << "Object count: " << stats.numObjects << " (" << stats.numLiveObjects << " live)\n"; os << "Object size: " << stats.objectSize << " bytes (" << stats.liveObjectSize << " in live objects)\n"; os << "Available space: " << stats.freeBlockSize << " bytes in " << stats.numFreeBlocks << " blocks\n"; os << '\n'; os << "= Free Blocks =\nAddress Size(net)\n"; // Print free blocks: just use the free list os.fill('0'); for(auto blk = mFreeList; blk; blk = blk->next()) { os << std::hex << std::setw(sizeof(void*)) << blk << ' ' << std::dec << blk->size() << '\n'; } os << std::setfill(' ') << '\n'; os << "= Live Objects =\n"; // For printing live objects we need to do marking this->dumpLiveObjects(os); } void HeapBase::dumpLiveObjects(std::ostream &os) { constexpr std::size_t numDataBytes = 4; static const std::string indent(4, ' '); for(auto root : mRoots) { this->mark(root); } os << std::hex; for(auto blk = mHeapStart; blk < mHeapEnd; blk = blk->following()) { if(blk->mark()) { blk->ptr().mark(false); os << static_cast<void*>(blk->data()) << ' ' << "TODO NAME" << '\n'; os << " Data: "; std::copy_n(blk->data(), std::min(blk->type().size(), numDataBytes), std::ostream_iterator<int>(os, " ")); if(blk->type().size() > numDataBytes) { os << "..."; } os << "\n Pointers: "; if(blk->type().offsets() > 0) { os << "\n"; for(auto offset : blk->type()) { os << indent << *reinterpret_cast<void**>(blk->data() + offset) << '\n'; } } else { os << "none\n"; } } // if(blk->mark()) } os << std::dec; } HeapBase::HeapStats HeapBase::collectHeapStats(bool countLiveObjects) noexcept { HeapStats result{}; result.heapSize = reinterpret_cast<byte*>(mHeapEnd) - reinterpret_cast<byte*>(mHeapStart); if(countLiveObjects) { for(auto root : mRoots) { this->mark(root); } } for(auto blk = mHeapStart; blk < mHeapEnd; blk = blk->following()) { if(blk->free()) { result.numFreeBlocks++; result.freeBlockSize += blk->size(); result.freeSize += Align + align(blk->size()); } else { if(blk->mark()) { blk->ptr().mark(false); result.numLiveObjects++; result.liveObjectSize += blk->type().size(); } result.numObjects++; result.objectSize += blk->type().size(); result.usedSize += Align + align(blk->size()); } } assert(result.freeSize + result.usedSize == result.heapSize); return result; } } // namespace ssw <|endoftext|>
<commit_before>#include "Test.h" #include "SkDeque.h" static void assert_count(skiatest::Reporter* reporter, const SkDeque& deq, int count) { if (0 == count) { REPORTER_ASSERT(reporter, deq.empty()); REPORTER_ASSERT(reporter, 0 == deq.count()); REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize()); REPORTER_ASSERT(reporter, NULL == deq.front()); REPORTER_ASSERT(reporter, NULL == deq.back()); } else { REPORTER_ASSERT(reporter, !deq.empty()); REPORTER_ASSERT(reporter, count == deq.count()); REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize()); REPORTER_ASSERT(reporter, NULL != deq.front()); REPORTER_ASSERT(reporter, NULL != deq.back()); if (1 == count) { REPORTER_ASSERT(reporter, deq.back() == deq.front()); } else { REPORTER_ASSERT(reporter, deq.back() != deq.front()); } } } static void assert_f2biter(skiatest::Reporter* reporter, const SkDeque& deq, int max, int min) { SkDeque::F2BIter iter(deq); void* ptr; int value = max; while ((ptr = iter.next()) != NULL) { REPORTER_ASSERT(reporter, value == *(int*)ptr); value -= 1; } REPORTER_ASSERT(reporter, value+1 == min); } static void TestDeque(skiatest::Reporter* reporter) { SkDeque deq(sizeof(int)); int i; assert_count(reporter, deq, 0); for (i = 1; i <= 10; i++) { *(int*)deq.push_front() = i; } assert_count(reporter, deq, 10); assert_f2biter(reporter, deq, 10, 1); for (i = 0; i < 5; i++) { deq.pop_front(); } assert_count(reporter, deq, 5); assert_f2biter(reporter, deq, 5, 1); for (i = 0; i < 5; i++) { deq.pop_front(); } assert_count(reporter, deq, 0); } #include "TestClassDef.h" DEFINE_TESTCLASS("Deque", TestDequeClass, TestDeque) <commit_msg>add tests for pushing on back as well as front<commit_after>#include "Test.h" #include "SkDeque.h" static void assert_count(skiatest::Reporter* reporter, const SkDeque& deq, int count) { if (0 == count) { REPORTER_ASSERT(reporter, deq.empty()); REPORTER_ASSERT(reporter, 0 == deq.count()); REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize()); REPORTER_ASSERT(reporter, NULL == deq.front()); REPORTER_ASSERT(reporter, NULL == deq.back()); } else { REPORTER_ASSERT(reporter, !deq.empty()); REPORTER_ASSERT(reporter, count == deq.count()); REPORTER_ASSERT(reporter, sizeof(int) == deq.elemSize()); REPORTER_ASSERT(reporter, NULL != deq.front()); REPORTER_ASSERT(reporter, NULL != deq.back()); if (1 == count) { REPORTER_ASSERT(reporter, deq.back() == deq.front()); } else { REPORTER_ASSERT(reporter, deq.back() != deq.front()); } } } static void assert_f2biter(skiatest::Reporter* reporter, const SkDeque& deq, int max, int min) { SkDeque::F2BIter iter(deq); void* ptr; int value = max; while ((ptr = iter.next()) != NULL) { REPORTER_ASSERT(reporter, value == *(int*)ptr); value -= 1; } REPORTER_ASSERT(reporter, value+1 == min); } static void TestDeque(skiatest::Reporter* reporter) { SkDeque deq(sizeof(int)); int i; // test pushing on the front assert_count(reporter, deq, 0); for (i = 1; i <= 10; i++) { *(int*)deq.push_front() = i; } assert_count(reporter, deq, 10); assert_f2biter(reporter, deq, 10, 1); for (i = 0; i < 5; i++) { deq.pop_front(); } assert_count(reporter, deq, 5); assert_f2biter(reporter, deq, 5, 1); for (i = 0; i < 5; i++) { deq.pop_front(); } assert_count(reporter, deq, 0); // now test pushing on the back for (i = 10; i >= 1; --i) { *(int*)deq.push_back() = i; } assert_count(reporter, deq, 10); assert_f2biter(reporter, deq, 10, 1); for (i = 0; i < 5; i++) { deq.pop_back(); } assert_count(reporter, deq, 5); assert_f2biter(reporter, deq, 10, 6); for (i = 0; i < 5; i++) { deq.pop_back(); } assert_count(reporter, deq, 0); // now tests pushing/poping on both ends *(int*)deq.push_front() = 5; *(int*)deq.push_back() = 4; *(int*)deq.push_front() = 6; *(int*)deq.push_back() = 3; *(int*)deq.push_front() = 7; *(int*)deq.push_back() = 2; *(int*)deq.push_front() = 8; *(int*)deq.push_back() = 1; assert_count(reporter, deq, 8); assert_f2biter(reporter, deq, 8, 1); } #include "TestClassDef.h" DEFINE_TESTCLASS("Deque", TestDequeClass, TestDeque) <|endoftext|>
<commit_before>// -*- mode:c++; indent-tabs-mode:nil; -*- /* Copyright (c) 2014, 2015, Anders Ronnbrant, [email protected] 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. */ #include "Recorder.h" #include "RecorderSink.h" #include "zmqutils.h" #include <boost/program_options.hpp> #include <zmq.hpp> #include <atomic> #include <chrono> #include <cstdlib> #include <string> #include <thread> #include <vector> namespace po = boost::program_options; namespace { typedef std::chrono::milliseconds msec; typedef std::chrono::microseconds usec; typedef std::chrono::nanoseconds nsec; } enum class FOO { A, B, C, D, E, X, Y, Z, Count }; enum class BAR { A, B, C, D, E, X, Y, Z, Count }; enum class FUU { A, B, C, D, E, X, Y, Z, Count }; enum class BER { A, B, C, D, E, X, Y, Z, Count }; template<typename T> void funcSetupRecorder(Recorder<T>& rec, char const* prefix, int const id) { char name[8][12]; snprintf(name[0], sizeof(name[0]), "%s-chr%02d", prefix, id); snprintf(name[1], sizeof(name[1]), "%s-dbl%02d", prefix, id); snprintf(name[2], sizeof(name[2]), "%s-i32%02d", prefix, id); snprintf(name[3], sizeof(name[3]), "%s-i64%02d", prefix, id); snprintf(name[4], sizeof(name[4]), "%s-uns%02d", prefix, id); snprintf(name[5], sizeof(name[5]), "%s-af3%02d", prefix, id); snprintf(name[6], sizeof(name[6]), "%s-ad3%02d", prefix, id); snprintf(name[7], sizeof(name[7]), "%s-id2%02d", prefix, id); // key[enum], name[string], type[enum], description[string], compare[pointer] rec.setup(T::A, name[0], "m"); rec.setup(T::B, name[1], "s"); rec.setup(T::C, name[2], "C"); rec.setup(T::D, name[3], "u"); rec.setup(T::E, name[4], "g"); rec.setup(T::X, name[5], "-"); rec.setup(T::Y, name[6], "-"); rec.setup(T::Z, name[7], "-"); } template<typename T> void funcRecordRecorder(Recorder<T>& rec, int x) { float data1[3] = {500.0f*x, 600.0f*x, 700.0f*x}; double data2[3] = {500.0*x, 600.0*x, 700.0*x}; rec.record(T::A, *reinterpret_cast<char*>(&x), x); rec.record(T::B, std::log(1+x), x); rec.record(T::C, reinterpret_cast<int32_t>(-x*x), x); rec.record(T::D, static_cast<int64_t>(-x*x), x); rec.record(T::E, static_cast<uint64_t>(x*x), x); rec.record(T::X, data1, x); rec.record(T::Y, data2, x); rec.record(T::Z, {10*x, 20*x}, x); } void funcProducer(int const id, int const num_rounds) { std::string prefix; char recorder_name[32]; prefix = "FOO"; snprintf(recorder_name, sizeof(recorder_name), "%s%02d", prefix.c_str() , id); Recorder<FOO> recfoo(recorder_name, random() % (1<<16)); funcSetupRecorder(recfoo, prefix.c_str(), id); prefix = "BAR"; snprintf(recorder_name, sizeof(recorder_name), "%s%02d", prefix.c_str() , id); Recorder<BAR> recbar(recorder_name, random() % (1<<16)); funcSetupRecorder(recbar, prefix.c_str(), id); prefix = "FUU"; snprintf(recorder_name, sizeof(recorder_name), "%s%02d", prefix.c_str() , id); Recorder<FUU> recfuu(recorder_name, random() % (1<<16)); funcSetupRecorder(recfuu, prefix.c_str(), id); prefix = "BER"; snprintf(recorder_name, sizeof(recorder_name), "%s%02d", prefix.c_str() , id); Recorder<BER> recber(recorder_name, random() % (1<<16)); funcSetupRecorder(recber, prefix.c_str(), id); for (int j = 0; j < num_rounds; ++j) { //std::this_thread::sleep_for(nsec(10)); funcRecordRecorder(recfoo, j); funcRecordRecorder(recbar, j); funcRecordRecorder(recfuu, j); funcRecordRecorder(recber, j); } } int main(int ac, char** av) { int num_rec_rounds = 2; int num_rec_threads = 2; int num_ctx_threads = 1; std::string addr = "inproc://recorder"; // ---------------------------------------------------------------------- po::options_description opts("Options", 80, 75); opts.add_options() ("help,h", "Show help") ("verbose,v", "Be verbose") ("rounds,r", po::value<int>(&num_rec_rounds)->default_value(num_rec_rounds), "Number of recording rounds") ("threads,t", po::value<int>(&num_rec_threads)->default_value(num_rec_threads), "Number of recording threads. Producer threads that records 8 " "different values per round.") ("context_io", po::value<int>(&num_ctx_threads)->default_value(num_ctx_threads), "Number of ZMQ context io threads. Defaults to one (1) and should " "almost always be that.") ("address,a", po::value<std::string>(&addr)->default_value(addr), "Socket address"); po::variables_map vm; po::store(po::parse_command_line(ac, av, opts), vm); po::notify(vm); if (vm.count("help")) { opts.print(std::cout); std::exit(0); } // ---------------------------------------------------------------------- zmq::context_t ctx(num_ctx_threads); RecorderBase::setContext(&ctx); RecorderBase::setAddress(addr); printf("PID: %d\n", getpid()); printf("Item size: %lu\n", sizeof(Item)); RecorderSink backend; backend.start(vm.count("verbose")); int const num_recorder_per_thread = 4; int const num_messages_per_recorder = 8; // Each item recording generates two messages per round except for the // first, which only creates a single message. auto num_messages = num_rec_threads * num_recorder_per_thread * num_messages_per_recorder * (2 * num_rec_rounds - 1); printf("Running %d threads %d rounds\n" " %d recorders per thread\n" " %d items per recorder\n" "Total %d (%ldMiB)\n", num_rec_threads, num_rec_rounds, num_recorder_per_thread, num_messages_per_recorder, num_messages, (num_messages * sizeof(Item))/(1024*1024)); std::vector<std::thread> recorders; for (int i = 0; i < num_rec_threads; ++i) { recorders.emplace_back(std::thread(&funcProducer, i+1, num_rec_rounds)); } for (auto& th : recorders) { if (th.joinable()) th.join(); } std::this_thread::sleep_for(msec(1)); backend.stop(); RecorderBase::shutDown(); return 0; } <commit_msg>Adjust producer data, less recorders and different values<commit_after>// -*- mode:c++; indent-tabs-mode:nil; -*- /* Copyright (c) 2014, 2015, Anders Ronnbrant, [email protected] 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. */ #include "Recorder.h" #include "RecorderSink.h" #include "zmqutils.h" #include <boost/program_options.hpp> #include <zmq.hpp> #include <atomic> #include <chrono> #include <cstdlib> #include <string> #include <thread> #include <vector> namespace po = boost::program_options; namespace { typedef std::chrono::milliseconds msec; typedef std::chrono::microseconds usec; typedef std::chrono::nanoseconds nsec; } enum class FOO { A, B, C, D, E, X, Y, Z, Count }; enum class BAR { A, B, C, D, E, X, Y, Z, Count }; enum class FUU { A, B, C, D, E, X, Y, Z, Count }; enum class BER { A, B, C, D, E, X, Y, Z, Count }; template<typename T> void funcSetupRecorder(Recorder<T>& rec, char const* prefix, int const id) { char name[8][12]; snprintf(name[0], sizeof(name[0]), "%s-chr%02d", prefix, id); snprintf(name[1], sizeof(name[1]), "%s-dbl%02d", prefix, id); snprintf(name[2], sizeof(name[2]), "%s-i32%02d", prefix, id); snprintf(name[3], sizeof(name[3]), "%s-i64%02d", prefix, id); snprintf(name[4], sizeof(name[4]), "%s-uns%02d", prefix, id); snprintf(name[5], sizeof(name[5]), "%s-af3%02d", prefix, id); snprintf(name[6], sizeof(name[6]), "%s-ad3%02d", prefix, id); snprintf(name[7], sizeof(name[7]), "%s-id2%02d", prefix, id); // key[enum], name[string], type[enum], description[string], compare[pointer] rec.setup(T::A, name[0], "m"); rec.setup(T::B, name[1], "s"); rec.setup(T::C, name[2], "C"); rec.setup(T::D, name[3], "u"); rec.setup(T::E, name[4], "g"); rec.setup(T::X, name[5], "-"); rec.setup(T::Y, name[6], "-"); rec.setup(T::Z, name[7], "-"); } template<typename T> void funcRecordRecorder(Recorder<T>& rec, int x) { float data1[3] = {500.0f*x, 600.0f*x, 700.0f*x}; double data2[3] = {500.0*x, 600.0*x, 700.0*x}; rec.record(T::A, *reinterpret_cast<char*>(&x), x); rec.record(T::B, std::log(2+x), x); rec.record(T::C, reinterpret_cast<int32_t>(-1), x); rec.record(T::D, static_cast<int64_t>(-2+x), x); rec.record(T::E, static_cast<uint64_t>(2*(1+x)), x); rec.record(T::X, data1, x); rec.record(T::Y, data2, x); rec.record(T::Z, {10*(1+x), 20*(1+x)}, x); } void funcProducer(int const id, int const num_rounds) { std::string prefix; char recorder_name[32]; prefix = "FOO"; snprintf(recorder_name, sizeof(recorder_name), "%s%02d", prefix.c_str() , id); Recorder<FOO> recfoo(recorder_name, random() % (1<<16)); funcSetupRecorder(recfoo, prefix.c_str(), id); //prefix = "BAR"; //snprintf(recorder_name, sizeof(recorder_name), "%s%02d", prefix.c_str() , id); //Recorder<BAR> recbar(recorder_name, random() % (1<<16)); //funcSetupRecorder(recbar, prefix.c_str(), id); for (int j = 0; j < num_rounds; ++j) { std::this_thread::sleep_for(nsec(1)); funcRecordRecorder(recfoo, j); //funcRecordRecorder(recbar, j); } } int main(int ac, char** av) { int num_rec_rounds = 2; int num_rec_threads = 2; int num_ctx_threads = 1; std::string addr = "inproc://recorder"; // ---------------------------------------------------------------------- po::options_description opts("Options", 80, 75); opts.add_options() ("help,h", "Show help") ("verbose,v", "Be verbose") ("rounds,r", po::value<int>(&num_rec_rounds)->default_value(num_rec_rounds), "Number of recording rounds") ("threads,t", po::value<int>(&num_rec_threads)->default_value(num_rec_threads), "Number of recording threads. Producer threads that records 8 " "different values per round.") ("context_io", po::value<int>(&num_ctx_threads)->default_value(num_ctx_threads), "Number of ZMQ context io threads. Defaults to one (1) and should " "almost always be that.") ("address,a", po::value<std::string>(&addr)->default_value(addr), "Socket address"); po::variables_map vm; po::store(po::parse_command_line(ac, av, opts), vm); po::notify(vm); if (vm.count("help")) { opts.print(std::cout); std::exit(0); } // ---------------------------------------------------------------------- zmq::context_t ctx(num_ctx_threads); RecorderBase::setContext(&ctx); RecorderBase::setAddress(addr); printf("PID: %d\n", getpid()); printf("Item size: %lu\n", sizeof(Item)); RecorderSink backend; backend.start(vm.count("verbose")); int const num_recorder_per_thread = 2; int const num_messages_per_recorder = 8; // Each item recording generates two messages per round except for the // first, which only creates a single message. auto num_messages = num_rec_threads * num_recorder_per_thread * num_messages_per_recorder * (2 * num_rec_rounds - 1); printf("Running %d threads %d rounds\n" " %d recorders per thread\n" " %d items per recorder\n" "Total %d (%ldMiB)\n", num_rec_threads, num_rec_rounds, num_recorder_per_thread, num_messages_per_recorder, num_messages, (num_messages * sizeof(Item))/(1024*1024)); std::vector<std::thread> recorders; for (int i = 0; i < num_rec_threads; ++i) { recorders.emplace_back(std::thread(&funcProducer, i+1, num_rec_rounds)); } for (auto& th : recorders) { if (th.joinable()) th.join(); } std::this_thread::sleep_for(msec(1)); backend.stop(); RecorderBase::shutDown(); return 0; } <|endoftext|>
<commit_before>// // This file is a part of pomerol - a scientific ED code for obtaining // properties of a Hubbard model on a finite-size lattice // // Copyright (C) 2010-2012 Andrey Antipov <[email protected]> // Copyright (C) 2010-2012 Igor Krivenko <[email protected]> // // pomerol 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. // // pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>. /** \file tests/IndexTerm.cpp ** \brief Test of the IndexHamiltonian::Term. ** ** \author Andrey Antipov ([email protected]) */ #include "Misc.h" #include "Logger.h" #include "Index.h" #include "IndexClassification.h" #include "IndexHamiltonian.h" #include <boost/shared_ptr.hpp> using namespace Pomerol; int main(int argc, char* argv[]) { /* Test of IndexHamiltonian::Term*/ Log.setDebugging(true); bool Seq[4] = {0,0,1,0}; ParticleIndex Ind[] = {1,2,2,4}; std::vector<bool> seq_v(Seq, Seq+4); std::vector<ParticleIndex> ind_v(Ind, Ind+4); IndexHamiltonian::Term IT1(4, seq_v, ind_v, 1.0); INFO("Created IndexHamiltonian::Term" << IT1); INFO("Rearranging it to normal order"); boost::shared_ptr<std::list<IndexHamiltonian::Term*> > out_terms=IT1.makeNormalOrder(); INFO("Received " << IT1); INFO(out_terms->size() << " additional terms emerged : "); for (std::list<IndexHamiltonian::Term*>::const_iterator it1=out_terms->begin(); it1!=out_terms->end(); ++it1) DEBUG(**it1); /* end of test of IndexHamiltonian::Term */ return EXIT_SUCCESS; } <commit_msg>minor upd<commit_after>// // This file is a part of pomerol - a scientific ED code for obtaining // properties of a Hubbard model on a finite-size lattice // // Copyright (C) 2010-2012 Andrey Antipov <[email protected]> // Copyright (C) 2010-2012 Igor Krivenko <[email protected]> // // pomerol 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. // // pomerol 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 pomerol. If not, see <http://www.gnu.org/licenses/>. /** \file tests/IndexTerm.cpp ** \brief Test of the IndexHamiltonian::Term. ** ** \author Andrey Antipov ([email protected]) */ #include "Misc.h" #include "Logger.h" #include "Index.h" #include "IndexClassification.h" #include "IndexHamiltonian.h" #include <boost/shared_ptr.hpp> using namespace Pomerol; int main(int argc, char* argv[]) { /* Test of IndexHamiltonian::Term*/ Log.setDebugging(true); bool Seq[4] = {0,0,1,0}; ParticleIndex Ind[] = {1,2,2,4}; std::vector<bool> seq_v(Seq, Seq+4); std::vector<ParticleIndex> ind_v(Ind, Ind+4); IndexHamiltonian::Term IT1(4, seq_v, ind_v, 1.0); INFO("Created IndexHamiltonian::Term" << IT1); INFO("Rearranging it to normal order"); try { boost::shared_ptr<std::list<IndexHamiltonian::Term*> > out_terms=IT1.makeNormalOrder(); INFO("Received " << IT1); INFO(out_terms->size() << " additional terms emerged : "); for (std::list<IndexHamiltonian::Term*>::const_iterator it1=out_terms->begin(); it1!=out_terms->end(); ++it1) DEBUG(**it1); } catch (std::exception &e) { return EXIT_FAILURE; } /* end of test of IndexHamiltonian::Term */ return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include "TestRunner.h" #include "TestBenchmark.h" #include "JSON/JSON.h" using namespace Tundra; using namespace Tundra::Test; const String StringData = "\" Json String Test\tHello World \""; const String ObjectData = "{\n\"Hello\":true , \"World\" \n: 00010, \"Str\" :" + StringData + " }"; const String ArrayData = "[ \"Hello World\", 0 ,-1234, 1234.5678 , true,false, \n null, [ \"World Hello\", 10, false ] \t , " + ObjectData + " \n]"; TEST_F(Runner, ParseJSON) { Tundra::Benchmark::Iterations = 10000; BENCHMARK("String", 10) { JSONValue value; ASSERT_TRUE(value.FromString(StringData)); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_STRING); ASSERT_TRUE(value.IsString()); ASSERT_EQ(value.GetString(), " Json String Test\tHello World "); } BENCHMARK_END; Tundra::Benchmark::Iterations = 10000; BENCHMARK("Array", 10) { JSONValue value; ASSERT_TRUE(value.FromString(ArrayData)); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_ARRAY); ASSERT_TRUE(value.IsArray()); ASSERT_EQ(value[0].GetString(), "Hello World"); ASSERT_DOUBLE_EQ(value[1].GetNumber(), 0.0); ASSERT_DOUBLE_EQ(value[2].GetNumber(), -1234.0); ASSERT_DOUBLE_EQ(value[3].GetNumber(), 1234.5678); ASSERT_TRUE(value[4].GetBool()); ASSERT_FALSE(value[5].GetBool()); ASSERT_TRUE(value[6].IsNull()); // Embedded array ASSERT_TRUE(value[7].IsArray()); ASSERT_TRUE(value[7][0].IsString()); ASSERT_TRUE(value[7][1].IsNumber()); ASSERT_TRUE(value[7][2].IsBool()); // Embedded object ASSERT_TRUE(value[8].IsObject()); JSONObject obj = value[8].GetObject(); ASSERT_TRUE(obj["Hello"].IsBool() && obj["Hello"].GetBool()); ASSERT_TRUE(obj["World"].IsNumber()); ASSERT_DOUBLE_EQ(obj["World"].GetNumber(), 10.0); ASSERT_TRUE(obj["Str"].IsString()); ASSERT_EQ(obj["Str"].GetString().Length(), StringData.Length() - 2); } BENCHMARK_END; Tundra::Benchmark::Iterations = 10000; BENCHMARK("Object", 10) { JSONValue value; ASSERT_TRUE(value.FromString(ObjectData)); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_OBJECT); ASSERT_TRUE(value.IsObject()); JSONObject obj = value.GetObject(); ASSERT_TRUE(obj["Hello"].IsBool() && obj["Hello"].GetBool()); ASSERT_TRUE(obj["World"].IsNumber()); ASSERT_DOUBLE_EQ(obj["World"].GetNumber(), 10.0); ASSERT_TRUE(obj["Str"].IsString()); ASSERT_EQ(obj["Str"].GetString().Length(), StringData.Length() - 2); } BENCHMARK_END; } TUNDRA_TEST_MAIN(); <commit_msg>Expand JSON tests for Null, Number, Bool. Embed both array and object to array and object test data.<commit_after> #include "TestRunner.h" #include "TestBenchmark.h" #include "JSON/JSON.h" using namespace Tundra; using namespace Tundra::Test; const String StringData = "\" Json String Test\tHello World \""; const String ObjectData = "{\n\"Hello\":true , \"World\" \n: 00010, \"Str\" :" + StringData + " , \"Arr\" : [1,2],\"Obj\":{\"test\" : true} }"; const String ArrayData = "[ \"Hello World\", 0 ,-1234, 1234.5678 , true,false, \n null, [ \"World Hello\", 10, false ] \t , " + ObjectData + " \n]"; TEST_F(Runner, ParseJSON) { Tundra::Benchmark::Iterations = 10000; BENCHMARK("Null", 10) { JSONValue value; ASSERT_TRUE(value.FromString(" \t \n null ")); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_NULL); ASSERT_TRUE(value.IsNull()); } BENCHMARK_END; Tundra::Benchmark::Iterations = 10000; BENCHMARK("Bool", 10) { JSONValue value; ASSERT_TRUE(value.FromString(" \t \n true ")); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_BOOL); ASSERT_TRUE(value.IsBool()); ASSERT_TRUE(value.GetBool()); } BENCHMARK_END; Tundra::Benchmark::Iterations = 10000; BENCHMARK("Number", 10) { JSONValue value; ASSERT_TRUE(value.FromString(" \n 1238972313.12312412 ")); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_NUMBER); ASSERT_TRUE(value.IsNumber()); ASSERT_DOUBLE_EQ(value.GetNumber(), 1238972313.12312412); } BENCHMARK_END; Tundra::Benchmark::Iterations = 10000; BENCHMARK("String", 10) { JSONValue value; ASSERT_TRUE(value.FromString(StringData)); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_STRING); ASSERT_TRUE(value.IsString()); ASSERT_EQ(value.GetString(), " Json String Test\tHello World "); } BENCHMARK_END; Tundra::Benchmark::Iterations = 10000; BENCHMARK("Array", 10) { JSONValue value; ASSERT_TRUE(value.FromString(ArrayData)); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_ARRAY); ASSERT_TRUE(value.IsArray()); ASSERT_EQ(value[0].GetString(), "Hello World"); ASSERT_DOUBLE_EQ(value[1].GetNumber(), 0.0); ASSERT_DOUBLE_EQ(value[2].GetNumber(), -1234.0); ASSERT_DOUBLE_EQ(value[3].GetNumber(), 1234.5678); ASSERT_TRUE(value[4].GetBool()); ASSERT_FALSE(value[5].GetBool()); ASSERT_TRUE(value[6].IsNull()); // Embedded array ASSERT_TRUE(value[7].IsArray()); ASSERT_TRUE(value[7][0].IsString()); ASSERT_TRUE(value[7][1].IsNumber()); ASSERT_TRUE(value[7][2].IsBool()); // Embedded object ASSERT_TRUE(value[8].IsObject()); JSONObject obj = value[8].GetObject(); ASSERT_TRUE(obj["Hello"].IsBool() && obj["Hello"].GetBool()); ASSERT_TRUE(obj["World"].IsNumber()); ASSERT_DOUBLE_EQ(obj["World"].GetNumber(), 10.0); ASSERT_TRUE(obj["Str"].IsString()); ASSERT_EQ(obj["Str"].GetString().Length(), StringData.Length() - 2); // Embedded child array ASSERT_TRUE(obj["Arr"].IsArray()); ASSERT_EQ(obj["Arr"].GetArray()[1], 2); // Embedded child Object ASSERT_TRUE(obj["Obj"].IsObject()); JSONObject childObj = obj["Obj"].GetObject(); ASSERT_TRUE(childObj["test"].GetBool()); } BENCHMARK_END; Tundra::Benchmark::Iterations = 10000; BENCHMARK("Object", 10) { JSONValue value; ASSERT_TRUE(value.FromString(ObjectData)); BENCHMARK_STEP_END; ASSERT_EQ(value.Type(), JSON_OBJECT); ASSERT_TRUE(value.IsObject()); JSONObject obj = value.GetObject(); ASSERT_TRUE(obj["Hello"].IsBool() && obj["Hello"].GetBool()); ASSERT_TRUE(obj["World"].IsNumber()); ASSERT_DOUBLE_EQ(obj["World"].GetNumber(), 10.0); ASSERT_TRUE(obj["Str"].IsString()); ASSERT_EQ(obj["Str"].GetString().Length(), StringData.Length() - 2); // Embedded array ASSERT_TRUE(obj["Arr"].IsArray()); ASSERT_EQ(obj["Arr"].GetArray()[1], 2); // Embedded Object ASSERT_TRUE(obj["Obj"].IsObject()); JSONObject childObj = obj["Obj"].GetObject(); ASSERT_TRUE(childObj["test"].GetBool()); } BENCHMARK_END; } TUNDRA_TEST_MAIN(); <|endoftext|>
<commit_before>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/PlatformSpecificFunctions.h" TEST_GROUP(UtestShell) { TestTestingFixture fixture; }; static void _failMethod() { FAIL("This test fails"); } static void _passingTestMethod() { CHECK(true); } static void _passingCheckEqualTestMethod() { CHECK_EQUAL(1, 1); } TEST(UtestShell, compareDoubles) { double zero = 0.0; double not_a_number = zero / zero; CHECK(doubles_equal(1.0, 1.001, 0.01)); CHECK(!doubles_equal(not_a_number, 1.001, 0.01)); CHECK(!doubles_equal(1.0, not_a_number, 0.01)); CHECK(!doubles_equal(1.0, 1.001, not_a_number)); CHECK(!doubles_equal(1.0, 1.1, 0.05)); double a = 1.2345678; CHECK(doubles_equal(a, a, 0.000000001)); } TEST(UtestShell, FailWillIncreaseTheAmountOfChecks) { fixture.setTestFunction(_failMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getCheckCount()); } TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks) { fixture.setTestFunction(_passingCheckEqualTestMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getCheckCount()); } IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture) { CHECK(&fixture != 0); } TEST(UtestShell, MacrosUsedInSetup) { IGNORE_ALL_LEAKS_IN_TEST(); fixture.setSetup(_failMethod); fixture.setTestFunction(_passingTestMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); } TEST(UtestShell, MacrosUsedInTearDown) { IGNORE_ALL_LEAKS_IN_TEST(); fixture.setTeardown(_failMethod); fixture.setTestFunction(_passingTestMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); } static int teardownCalled = 0; static void _teardownMethod() { teardownCalled++; } TEST(UtestShell, TeardownCalledAfterTestFailure) { teardownCalled = 0; IGNORE_ALL_LEAKS_IN_TEST(); fixture.setTeardown(_teardownMethod); fixture.setTestFunction(_failMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); LONGS_EQUAL(1, teardownCalled); } static int stopAfterFailure = 0; static void _stopAfterFailureMethod() { FAIL("fail"); stopAfterFailure++; } TEST(UtestShell, TestStopsAfterTestFailure) { IGNORE_ALL_LEAKS_IN_TEST(); stopAfterFailure = 0; fixture.setTestFunction(_stopAfterFailureMethod); fixture.runAllTests(); CHECK(fixture.hasTestFailed()); LONGS_EQUAL(1, fixture.getFailureCount()); LONGS_EQUAL(0, stopAfterFailure); } TEST(UtestShell, TestStopsAfterSetupFailure) { stopAfterFailure = 0; fixture.setSetup(_stopAfterFailureMethod); fixture.setTeardown(_stopAfterFailureMethod); fixture.setTestFunction(_failMethod); fixture.runAllTests(); LONGS_EQUAL(2, fixture.getFailureCount()); LONGS_EQUAL(0, stopAfterFailure); } class defaultUtestShell: public UtestShell { }; TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods) { defaultUtestShell shell; fixture.addTest(&shell); fixture.runAllTests(); LONGS_EQUAL(2, fixture.result_->getTestCount()); } static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) { result->addFailure(TestFailure(shell, "Failed in separate process")); } TEST(UtestShell, RunInSeparateProcessTest) { UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess); fixture.registry_->setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process"); } #if !defined(__MINGW32__) && !defined(_MSC_VER) TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) { fixture.setTestFunction(UtestShell::crash); fixture.registry_->setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process - killed by signal 11"); } #else IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {} #endif #if CPPUTEST_USE_STD_CPP_LIB static bool destructorWasCalledOnFailedTest = false; static void _destructorCalledForLocalObjects() { SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest); destructorWasCalledOnFailedTest = false; FAIL("fail"); } TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails) { fixture.setTestFunction(_destructorCalledForLocalObjects); fixture.runAllTests(); CHECK(destructorWasCalledOnFailedTest); } #endif TEST_BASE(MyOwnTest) { MyOwnTest() : inTest(false) { } bool inTest; void setup() { CHECK(!inTest); inTest = true; } void teardown() { CHECK(inTest); inTest = false; } }; TEST_GROUP_BASE(UtestMyOwn, MyOwnTest) { }; TEST(UtestMyOwn, test) { CHECK(inTest); } class NullParameterTest: public UtestShell { }; TEST(UtestMyOwn, NullParameters) { NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */ TestFilter emptyFilter; CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter)); } class AllocateAndDeallocateInConstructorAndDestructor { char* memory_; char* morememory_; public: AllocateAndDeallocateInConstructorAndDestructor() { memory_ = new char[100]; morememory_ = NULL; } void allocateMoreMemory() { morememory_ = new char[123]; } ~AllocateAndDeallocateInConstructorAndDestructor() { delete [] memory_; delete [] morememory_; } }; TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks) { AllocateAndDeallocateInConstructorAndDestructor dummy; }; TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName) { dummy.allocateMoreMemory(); } <commit_msg>Just had to get the 100% back...<commit_after>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTest/TestOutput.h" #include "CppUTest/TestTestingFixture.h" #include "CppUTest/PlatformSpecificFunctions.h" TEST_GROUP(Utest) { }; TEST(Utest, division) { LONGS_EQUAL(3, division(13, 4)); } TEST_GROUP(UtestShell) { TestTestingFixture fixture; }; static void _failMethod() { FAIL("This test fails"); } static void _passingTestMethod() { CHECK(true); } static void _passingCheckEqualTestMethod() { CHECK_EQUAL(1, 1); } TEST(UtestShell, compareDoubles) { double zero = 0.0; double not_a_number = zero / zero; CHECK(doubles_equal(1.0, 1.001, 0.01)); CHECK(!doubles_equal(not_a_number, 1.001, 0.01)); CHECK(!doubles_equal(1.0, not_a_number, 0.01)); CHECK(!doubles_equal(1.0, 1.001, not_a_number)); CHECK(!doubles_equal(1.0, 1.1, 0.05)); double a = 1.2345678; CHECK(doubles_equal(a, a, 0.000000001)); } TEST(UtestShell, FailWillIncreaseTheAmountOfChecks) { fixture.setTestFunction(_failMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getCheckCount()); } TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks) { fixture.setTestFunction(_passingCheckEqualTestMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getCheckCount()); } IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture) { CHECK(&fixture != 0); } TEST(UtestShell, MacrosUsedInSetup) { IGNORE_ALL_LEAKS_IN_TEST(); fixture.setSetup(_failMethod); fixture.setTestFunction(_passingTestMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); } TEST(UtestShell, MacrosUsedInTearDown) { IGNORE_ALL_LEAKS_IN_TEST(); fixture.setTeardown(_failMethod); fixture.setTestFunction(_passingTestMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); } static int teardownCalled = 0; static void _teardownMethod() { teardownCalled++; } TEST(UtestShell, TeardownCalledAfterTestFailure) { teardownCalled = 0; IGNORE_ALL_LEAKS_IN_TEST(); fixture.setTeardown(_teardownMethod); fixture.setTestFunction(_failMethod); fixture.runAllTests(); LONGS_EQUAL(1, fixture.getFailureCount()); LONGS_EQUAL(1, teardownCalled); } static int stopAfterFailure = 0; static void _stopAfterFailureMethod() { FAIL("fail"); stopAfterFailure++; } TEST(UtestShell, TestStopsAfterTestFailure) { IGNORE_ALL_LEAKS_IN_TEST(); stopAfterFailure = 0; fixture.setTestFunction(_stopAfterFailureMethod); fixture.runAllTests(); CHECK(fixture.hasTestFailed()); LONGS_EQUAL(1, fixture.getFailureCount()); LONGS_EQUAL(0, stopAfterFailure); } TEST(UtestShell, TestStopsAfterSetupFailure) { stopAfterFailure = 0; fixture.setSetup(_stopAfterFailureMethod); fixture.setTeardown(_stopAfterFailureMethod); fixture.setTestFunction(_failMethod); fixture.runAllTests(); LONGS_EQUAL(2, fixture.getFailureCount()); LONGS_EQUAL(0, stopAfterFailure); } class defaultUtestShell: public UtestShell { }; TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods) { defaultUtestShell shell; fixture.addTest(&shell); fixture.runAllTests(); LONGS_EQUAL(2, fixture.result_->getTestCount()); } static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result) { result->addFailure(TestFailure(shell, "Failed in separate process")); } TEST(UtestShell, RunInSeparateProcessTest) { UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess); fixture.registry_->setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process"); } #if !defined(__MINGW32__) && !defined(_MSC_VER) TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) { fixture.setTestFunction(UtestShell::crash); fixture.registry_->setRunTestsInSeperateProcess(); fixture.runAllTests(); fixture.assertPrintContains("Failed in separate process - killed by signal 11"); } #else IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {} #endif #if CPPUTEST_USE_STD_CPP_LIB static bool destructorWasCalledOnFailedTest = false; static void _destructorCalledForLocalObjects() { SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest); destructorWasCalledOnFailedTest = false; FAIL("fail"); } TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails) { fixture.setTestFunction(_destructorCalledForLocalObjects); fixture.runAllTests(); CHECK(destructorWasCalledOnFailedTest); } #endif TEST_BASE(MyOwnTest) { MyOwnTest() : inTest(false) { } bool inTest; void setup() { CHECK(!inTest); inTest = true; } void teardown() { CHECK(inTest); inTest = false; } }; TEST_GROUP_BASE(UtestMyOwn, MyOwnTest) { }; TEST(UtestMyOwn, test) { CHECK(inTest); } class NullParameterTest: public UtestShell { }; TEST(UtestMyOwn, NullParameters) { NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */ TestFilter emptyFilter; CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter)); } class AllocateAndDeallocateInConstructorAndDestructor { char* memory_; char* morememory_; public: AllocateAndDeallocateInConstructorAndDestructor() { memory_ = new char[100]; morememory_ = NULL; } void allocateMoreMemory() { morememory_ = new char[123]; } ~AllocateAndDeallocateInConstructorAndDestructor() { delete [] memory_; delete [] morememory_; } }; TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks) { AllocateAndDeallocateInConstructorAndDestructor dummy; }; TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName) { dummy.allocateMoreMemory(); } <|endoftext|>
<commit_before>#ifndef RESPONSE_HPP_INCLUDED #define RESPONSE_HPP_INCLUDED #include "forward.hpp" #include "connection.hpp" #include "response_header.hpp" #include <string> #include <memory> namespace Rest { class Response { friend InterfaceProvider; public: /** * Sends a string back to the client. * * @param message The string to send. */ void send(std::string const& message); /** * Stringifies an object and sends it back to the client. * * @param obj The object to stringify and send. */ template <typename T> void json(T const& obj) { connection_->sendJson(obj, header_); } /** * Alias for json. * @see json */ template <typename T> void sendJson(T const& obj) { json(obj, header_); } /** * Sends a file back to the client. * * @param fileName A file to send. * @param responseHeader A response header containing header information, * such as response code, version and response message. */ void sendFile(std::string const& fileName, bool autoDetectContentType = true); /** * Sends a status code with the string representation as body. * Equivalent to status(code).send(...) * * status(403).send("Forbidden") * * @param code A standard HTTP response code. */ void sendStatus(int code); /** * Used for empty bodies. This is actually a 'no operation' function, * because things a finished, when your handler returns. * But it might transform send functions into nop's the future. */ void end(); /** * Sets the status code for the next send. * Please not that the code defaults to 200 or 204 if not specified! * This method is intended to be chained! * * @param code A standard HTTP response code. * * @return itself. */ Response& status(int code); /** * Sets a header key value pair. Adds it if it were not existing. * Does not perform checkings. Make sure to do it correctly. * * @param key Key of header entry. * @param value Value of header entry. * * @return itself. */ Response& setHeaderEntry(std::string key, std::string value); /** * Redirects to another url / page. * Sets the Location header entry for that. The status code will default * to 302. Another code you should look into is 301. * * @param path The path to redirect to. See HTTP Location header field. */ void redirect(std::string const& path); /** * Returns the connection to the client. * Can be useful to access more delicate and low level things. * Please do not abuse! * * @return Returns a RestConnection reference */ RestConnection& getConnection(); private: // cannot be created by user. Response(std::shared_ptr <RestConnection>& connection); private: std::shared_ptr <RestConnection> connection_; ResponseHeader header_; bool statusSet_; }; } #endif // RESPONSE_HPP_INCLUDED <commit_msg>Its possible to send empty messages, meaning no body, but a header.<commit_after>#ifndef RESPONSE_HPP_INCLUDED #define RESPONSE_HPP_INCLUDED #include "forward.hpp" #include "connection.hpp" #include "response_header.hpp" #include <string> #include <memory> namespace Rest { class Response { friend InterfaceProvider; public: /** * Sends a string back to the client. * * @param message The string to send. */ void send(std::string const& message = ""); /** * Stringifies an object and sends it back to the client. * * @param obj The object to stringify and send. */ template <typename T> void json(T const& obj) { connection_->sendJson(obj, header_); } /** * Alias for json. * @see json */ template <typename T> void sendJson(T const& obj) { json(obj, header_); } /** * Sends a file back to the client. * * @param fileName A file to send. * @param responseHeader A response header containing header information, * such as response code, version and response message. */ void sendFile(std::string const& fileName, bool autoDetectContentType = true); /** * Sends a status code with the string representation as body. * Equivalent to status(code).send(...) * * status(403).send("Forbidden") * * @param code A standard HTTP response code. */ void sendStatus(int code); /** * Used for empty bodies. This is actually a 'no operation' function, * because things a finished, when your handler returns. * But it might transform send functions into nop's the future. */ void end(); /** * Sets the status code for the next send. * Please not that the code defaults to 200 or 204 if not specified! * This method is intended to be chained! * * @param code A standard HTTP response code. * * @return itself. */ Response& status(int code); /** * Sets a header key value pair. Adds it if it were not existing. * Does not perform checkings. Make sure to do it correctly. * * @param key Key of header entry. * @param value Value of header entry. * * @return itself. */ Response& setHeaderEntry(std::string key, std::string value); /** * Redirects to another url / page. * Sets the Location header entry for that. The status code will default * to 302. Another code you should look into is 301. * * @param path The path to redirect to. See HTTP Location header field. */ void redirect(std::string const& path); /** * Sets the content type. such as "application/json". * if the passed type is a file extension (without dot), it will choose the correct type. * Check mime.cpp for a list of known extensions. * * @param type custom Content-Type or file extension. */ Response& type(std::string const& type); /** * Returns the connection to the client. * Can be useful to access more delicate and low level things. * Please do not abuse! * * @return Returns a RestConnection reference */ RestConnection& getConnection(); private: // cannot be created by user. Response(std::shared_ptr <RestConnection>& connection); private: std::shared_ptr <RestConnection> connection_; ResponseHeader header_; bool statusSet_; }; } #endif // RESPONSE_HPP_INCLUDED <|endoftext|>
<commit_before>#ifndef RECURSE_RESPONSE_HPP #define RECURSE_RESPONSE_HPP #include <QHash> #include <QJsonDocument> #include <functional> class Response { public: QString get(const QString &key) { return header[key]; }; Response &set(const QString &key, const QString &value) { header[key] = value; return *this; }; quint16 status() const { return m_status; }; Response &status(const quint16 &status) { m_status = status; return *this; }; QString type() const { return header["content-type"]; }; Response &type(const QString &type) { header["content-type"] = type; return *this; }; QString body() const { return m_body;}; Response &body(const QString &body) { m_body = body; return *this; }; Response &write(const QString msg) { m_body += msg; return *this; }; void send(const QString &body = "") { if (body.size()) m_body = body; end(); }; void send(const QJsonDocument &body) { type("application/json"); qDebug() << " body:" << body; m_body = body.toJson(QJsonDocument::Compact); end(); } // final function set and called from recurse std::function<void()> end; QHash<QString, QString> header; QString method, protocol; QHash<quint16, QString> http_codes { {100, "Continue"}, {101, "Switching Protocols"}, {200, "OK"}, {201, "Created"}, {202, "Accepted"}, {203, "Non-Authoritative Information"}, {204, "No Content"}, {205, "Reset Content"}, {206, "Partial Content"}, {300, "Multiple Choices"}, {301, "Moved Permanently"}, {302, "Found"}, {303, "See Other"}, {304, "Not Modified"}, {305, "Use Proxy"}, {307, "Temporary Redirect"}, {400, "Bad Request"}, {401, "Unauthorized"}, {402, "Payment Required"}, {403, "Forbidden"}, {404, "Not Found"}, {405, "Method Not Allowed"}, {406, "Not Acceptable"}, {407, "Proxy Authentication Required"}, {408, "Request Time-out"}, {409, "Conflict"}, {410, "Gone"}, {411, "Length Required"}, {412, "Precondition Failed"}, {413, "Request Entity Too Large"}, {414, "Request-URI Too Large"}, {415, "Unsupported Media Type"}, {416, "Requested range not satisfiable"}, {417, "Expectation Failed"}, {500, "Internal Server Error"}, {501, "Not Implemented"}, {502, "Bad Gateway"}, {503, "Service Unavailable"}, {504, "Gateway Time-out"}, {505, "HTTP Version not supported"} }; //! //! \brief create_reply //! create reply for sending to client //! //! \return QString reply to be sent //! QString create_reply(); private: quint16 m_status = 200; QString m_body; }; // https://tools.ietf.org/html/rfc7230#page-19 QString Response::create_reply() { qDebug() << __FUNCTION__ << this->body(); qDebug() << "response header:" << this->header; QString reply = this->protocol % " " % QString::number(this->status()) % " " % this->http_codes[this->status()] % "\r\n"; // set content length this->header["content-length"] = QString::number(this->body().size()); // set content type if not set if (!this->header.contains("content-type")) this->header["content-type"] = "text/plain"; // set custom header fields for (auto i = this->header.constBegin(); i != this->header.constEnd(); ++i) reply = reply % i.key() % ": " % i.value() % "\r\n"; reply += "\r\n"; if (this->body().size()) reply += this->body(); return reply; }; #endif <commit_msg>response: minor pass by value/reference changes<commit_after>#ifndef RECURSE_RESPONSE_HPP #define RECURSE_RESPONSE_HPP #include <QHash> #include <QJsonDocument> #include <functional> class Response { public: QString get(const QString &key) { return header[key]; }; Response &set(const QString &key, const QString &value) { header[key] = value; return *this; }; quint16 status() const { return m_status; }; Response &status(quint16 status) { m_status = status; return *this; }; QString type() const { return header["content-type"]; }; Response &type(const QString &type) { header["content-type"] = type; return *this; }; QString body() const { return m_body;}; Response &body(const QString &body) { m_body = body; return *this; }; Response &write(const QString &msg) { m_body += msg; return *this; }; void send(const QString &body = "") { if (body.size()) m_body = body; end(); }; void send(const QJsonDocument &body) { type("application/json"); qDebug() << " body:" << body; m_body = body.toJson(QJsonDocument::Compact); end(); } // final function set and called from recurse std::function<void()> end; QHash<QString, QString> header; QString method, protocol; QHash<quint16, QString> http_codes { {100, "Continue"}, {101, "Switching Protocols"}, {200, "OK"}, {201, "Created"}, {202, "Accepted"}, {203, "Non-Authoritative Information"}, {204, "No Content"}, {205, "Reset Content"}, {206, "Partial Content"}, {300, "Multiple Choices"}, {301, "Moved Permanently"}, {302, "Found"}, {303, "See Other"}, {304, "Not Modified"}, {305, "Use Proxy"}, {307, "Temporary Redirect"}, {400, "Bad Request"}, {401, "Unauthorized"}, {402, "Payment Required"}, {403, "Forbidden"}, {404, "Not Found"}, {405, "Method Not Allowed"}, {406, "Not Acceptable"}, {407, "Proxy Authentication Required"}, {408, "Request Time-out"}, {409, "Conflict"}, {410, "Gone"}, {411, "Length Required"}, {412, "Precondition Failed"}, {413, "Request Entity Too Large"}, {414, "Request-URI Too Large"}, {415, "Unsupported Media Type"}, {416, "Requested range not satisfiable"}, {417, "Expectation Failed"}, {500, "Internal Server Error"}, {501, "Not Implemented"}, {502, "Bad Gateway"}, {503, "Service Unavailable"}, {504, "Gateway Time-out"}, {505, "HTTP Version not supported"} }; //! //! \brief create_reply //! create reply for sending to client //! //! \return QString reply to be sent //! QString create_reply(); private: quint16 m_status = 200; QString m_body; }; // https://tools.ietf.org/html/rfc7230#page-19 QString Response::create_reply() { qDebug() << __FUNCTION__ << this->body(); qDebug() << "response header:" << this->header; QString reply = this->protocol % " " % QString::number(this->status()) % " " % this->http_codes[this->status()] % "\r\n"; // set content length this->header["content-length"] = QString::number(this->body().size()); // set content type if not set if (!this->header.contains("content-type")) this->header["content-type"] = "text/plain"; // set custom header fields for (auto i = this->header.constBegin(); i != this->header.constEnd(); ++i) reply = reply % i.key() % ": " % i.value() % "\r\n"; reply += "\r\n"; if (this->body().size()) reply += this->body(); return reply; }; #endif <|endoftext|>
<commit_before>/* * Copyright 2014 Cloudius Systems */ #include "core/reactor.hh" #include "core/app-template.hh" #include "core/temporary_buffer.hh" #include "core/smp.hh" #include <vector> #include <iostream> class http_server { std::vector<server_socket> _listeners; public: future<> listen(ipv4_addr addr) { listen_options lo; lo.reuse_address = true; _listeners.push_back(engine.listen(make_ipv4_address(addr), lo)); do_accepts(_listeners.size() - 1); return make_ready_future<>(); } void do_accepts(int which) { _listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable { auto conn = new connection(*this, std::move(fd), addr); conn->process().rescue([this, conn] (auto get_ex) { delete conn; try { get_ex(); } catch (std::exception& ex) { std::cout << "request error " << ex.what() << "\n"; } }); do_accepts(which); }).rescue([] (auto get_ex) { try { get_ex(); } catch (std::exception& ex) { std::cout << "accept failed: " << ex.what() << "\n"; } }); } class connection { connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; public: connection(http_server& server, connected_socket&& fd, socket_address addr) : _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) {} future<> process() { return read(); } future<> read() { if (_read_buf.eof()) { return make_ready_future(); } // Expect a ping from client. size_t n = 4; return _read_buf.read_exactly(n).then([this] (temporary_buffer<char> buf) { if (buf.size() == 0) { return make_ready_future(); } return _write_buf.write("pong", 4).then([this] { return _write_buf.flush(); }).then([this] { return this->read(); }); }); } }; }; int main(int ac, char** av) { app_template app; app.add_options() ("port", bpo::value<uint16_t>()->default_value(10000), "TCP server port") ; return app.run(ac, av, [&] { auto&& config = app.configuration(); uint16_t port = config["port"].as<uint16_t>(); auto server = new distributed<http_server>; server->start().then([server = std::move(server), port] () mutable { server->invoke_on_all(&http_server::listen, ipv4_addr{port}); }).then([port] { std::cout << "Seastar TCP server listening on port " << port << " ...\n"; }); }); } <commit_msg>tests: Add send test to tcp_server<commit_after>/* * Copyright 2014 Cloudius Systems */ #include "core/reactor.hh" #include "core/app-template.hh" #include "core/temporary_buffer.hh" #include "core/smp.hh" #include <vector> #include <iostream> static std::string str_ping{"ping"}; static std::string str_txtx{"txtx"}; static std::string str_pong{"pong"}; static std::string str_unknow{"unknow cmd"}; static int tx_msg_total_size = 10 * 1024 * 1024; static int tx_msg_size = 4 * 1024; static int tx_msg_nr = tx_msg_total_size / tx_msg_size; static std::string str_txbuf(tx_msg_size, 'X'); class http_server { std::vector<server_socket> _listeners; public: future<> listen(ipv4_addr addr) { listen_options lo; lo.reuse_address = true; _listeners.push_back(engine.listen(make_ipv4_address(addr), lo)); do_accepts(_listeners.size() - 1); return make_ready_future<>(); } void do_accepts(int which) { _listeners[which].accept().then([this, which] (connected_socket fd, socket_address addr) mutable { auto conn = new connection(*this, std::move(fd), addr); conn->process().rescue([this, conn] (auto get_ex) { delete conn; try { get_ex(); } catch (std::exception& ex) { std::cout << "request error " << ex.what() << "\n"; } }); do_accepts(which); }).rescue([] (auto get_ex) { try { get_ex(); } catch (std::exception& ex) { std::cout << "accept failed: " << ex.what() << "\n"; } }); } class connection { connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; public: connection(http_server& server, connected_socket&& fd, socket_address addr) : _fd(std::move(fd)) , _read_buf(_fd.input()) , _write_buf(_fd.output()) {} future<> process() { return read(); } future<> read() { if (_read_buf.eof()) { return make_ready_future(); } // Expect 4 bytes cmd from client size_t n = 4; return _read_buf.read_exactly(n).then([this] (temporary_buffer<char> buf) { if (buf.size() == 0) { return make_ready_future(); } auto cmd = std::string(buf.get(), buf.size()); // pingpong test if (cmd == str_ping) { return _write_buf.write(str_pong).then([this] { return _write_buf.flush(); }).then([this] { return this->read(); }); // server tx test } else if (cmd == str_txtx) { return tx_test(); // unknow test } else { return _write_buf.write(str_unknow).then([this] { return _write_buf.flush(); }).then([this] { return make_ready_future(); }); } }); } future<> do_write(int end) { if (end == 0) { return make_ready_future<>(); } return _write_buf.write(str_txbuf).then([this, end] { return _write_buf.flush(); }).then([this, end] { return do_write(end - 1); }); } future<> tx_test() { return do_write(tx_msg_nr).then([this] { return _write_buf.close(); }).then([this] { return make_ready_future<>(); }); } }; }; int main(int ac, char** av) { app_template app; app.add_options() ("port", bpo::value<uint16_t>()->default_value(10000), "TCP server port") ; return app.run(ac, av, [&] { auto&& config = app.configuration(); uint16_t port = config["port"].as<uint16_t>(); auto server = new distributed<http_server>; server->start().then([server = std::move(server), port] () mutable { server->invoke_on_all(&http_server::listen, ipv4_addr{port}); }).then([port] { std::cout << "Seastar TCP server listening on port " << port << " ...\n"; }); }); } <|endoftext|>
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * Copyright (C) FFLAS-FFPACK * Written by Clément Pernet <[email protected]> * This file is Free Software and part of FFLAS-FFPACK. * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ //-------------------------------------------------------------------------- // Test for ftrtri : 1 computation // //-------------------------------------------------------------------------- // Clement Pernet //------------------------------------------------------------------------- #define TIME 1 #include <iomanip> #include <iostream> #include "givaro/modular-balanced.h" #include "fflas-ffpack/fflas-ffpack-config.h" #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/utils/Matio.h" #include "fflas-ffpack/ffpack/ffpack.h" using namespace std; using namespace FFPACK; typedef Givaro::ModularBalanced<double> Field; int main(int argc, char** argv) { size_t n; int nbit=atoi(argv[3]); // number of times the product is performed cerr<<setprecision(10); if (argc != 4) { cerr<<"Usage : test-ftrtri <p> <A> <<i>" <<endl <<" to invert a triangular matrix A mod p (i computations)" <<endl; exit(-1); } Field F(atoi(argv[1])); Field::Element * A,*Ab; A = read_field(F,argv[2],&n,&n); Ab = FFLAS::fflas_new<Field::Element>(n*n); for (int i=0; i<n;++i){ for(int j=i+1; j<n; ++j) F.assign(*(Ab+i*n+j),*(A+i*n+j)); F.assign(*(Ab+i*(n+1)), 1.0); for(int j=0; j<i; ++j) F.assign(*(Ab+i*n+j),0.0); } Field::Element * X = FFLAS::fflas_new<Field::Element>(n*n); FFLAS::Timer tim,t; t.clear();tim.clear(); for(int i = 0;i<nbit;++i){ t.clear(); t.start(); // FFPACK::trinv_left (F, n, A, n, X, n); FFPACK::ftrtri(F, FFLAS::FflasUpper, FFLAS::FflasUnit, n, A, n); t.stop(); tim+=t; if (i+1<nbit) for (int i=0; i<n*n;++i) F.assign(*(A+i),*(Ab+i)); } #ifdef __FFLASFFPACK_DEBUG FFLAS::ftrmm (F, FFLAS::FflasRight, FFLAS::FflasUpper, FFLAS::FflasNoTrans, FFLAS::FflasUnit, n, n, 1.0, A,n, Ab, n); bool wrong = false; for (int i=0;i<n;++i) for (int j=0;j<n;++j) if ( ((i!=j) && !F.isZero(*(Ab+i*n+j))) ||((i==j) &&!F.isOne(*(Ab+i*n+j)))) wrong = true; if ( wrong ){ cerr<<"FAIL"<<endl; write_field (F,cerr<<"Ab="<<endl,Ab,n,n,n); //write_field (F,cerr<<"X="<<endl,X,n,n,n); }else{ cerr<<"PASS"<<endl; } #endif #if TIME double gflops = 1.0/3.0*(n/1000.0*n/1000000.0)*nbit*n/tim.usertime(); cerr<<"n = "<<n<<" Inversion over Z/"<<atoi(argv[1])<<"Z : t= " << tim.usertime()/nbit << " s, Gfops = "<<gflops << endl; cout<<n<<" "<<gflops<<" "<<tim.usertime()/nbit<<endl; #endif } <commit_msg>modified test-ftrtri to comply to new standards<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ // vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * Copyright (C) FFLAS-FFPACK * Written by Clément Pernet <[email protected]> * This file is Free Software and part of FFLAS-FFPACK. * * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== *. */ #define __FFLASFFPACK_SEQUENTIAL #define ENABLE_ALL_CHECKINGS 1 #include "fflas-ffpack/fflas-ffpack-config.h" #include <iomanip> #include <iostream> #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/fflas/fflas.h" #include "fflas-ffpack/utils/args-parser.h" #include "test-utils.h" #include <givaro/modular.h> using namespace std; using namespace FFPACK; using namespace FFLAS; using Givaro::Modular; using Givaro::ModularBalanced; template<typename Field, class RandIter> bool check_ftrtri (const Field &F, size_t n, FFLAS_UPLO uplo, FFLAS_TRANSPOSE trans, FFLAS_DIAG diag, RandIter& Rand){ typedef typename Field::Element Element; Element * A, * B; size_t lda = n + (rand() % n ); A = fflas_new(F,n,lda); B = fflas_new(F,n,lda); RandomTriangularMatrix (F, n, n, uplo, diag, true, A, lda, Rand); fassign (F, n, n, A, lda, B, lda); string ss=string((uplo == FflasLower)?"Lower_":"Upper_")+string((trans == FflasTrans)?"Trans_":"NoTrans_")+string((diag == FflasUnit)?"Unit":"NonUnit"); cout<<std::left<<"Checking FTRTRI_"; cout.fill('.'); cout.width(30); cout<<ss; Timer t; t.clear(); double time=0.0; t.clear(); t.start(); ftrtri (F, uplo, diag, n, A, lda); t.stop(); time+=t.usertime(); // B <- A times B ftrmm(F, FFLAS::FflasLeft, uplo, trans, diag, n, n, F.one, A, lda, B, lda); // Is B the identity matrix ? bool ok = true; for(size_t li = 0; li < n && ok; li++){ for(size_t co = 0; co < n && ok; co++){ ok = ((li == co) && (F.areEqual(A[li*(lda+1)],F.one))) || (F.areEqual(A[li*lda+co],F.zero)); } } if (ok){ cout << "PASSED ("<<time<<")"<<endl; } else{ cout << "FAILED ("<<time<<")"<<endl; } fflas_delete(A); fflas_delete(B); return ok; } template <class Field> bool run_with_field (Givaro::Integer q, size_t b, size_t n, size_t iters, uint64_t seed){ bool ok = true ; int nbit=(int)iters; while (ok && nbit){ //typedef typename Field::Element Element ; // choose Field Field* F= chooseField<Field>(q,b); typename Field::RandIter G(*F,0,seed); if (F==nullptr) return true; cout<<"Checking with ";F->write(cout)<<endl; ok = ok && check_ftrtri(*F,n,FflasLower,FflasNoTrans,FflasUnit,G); ok = ok && check_ftrtri(*F,n,FflasUpper,FflasNoTrans,FflasUnit,G); ok = ok && check_ftrtri(*F,n,FflasLower,FflasTrans,FflasUnit,G); ok = ok && check_ftrtri(*F,n,FflasUpper,FflasTrans,FflasUnit,G); ok = ok && check_ftrtri(*F,n,FflasLower,FflasNoTrans,FflasNonUnit,G); ok = ok && check_ftrtri(*F,n,FflasUpper,FflasNoTrans,FflasNonUnit,G); ok = ok && check_ftrtri(*F,n,FflasLower,FflasTrans,FflasNonUnit,G); ok = ok && check_ftrtri(*F,n,FflasUpper,FflasTrans,FflasNonUnit,G); nbit--; delete F; } return ok; } int main(int argc, char** argv) { cerr<<setprecision(10); Givaro::Integer q=-1; size_t b=0; size_t n=483; size_t iters=1; bool loop=false; uint64_t seed = time(NULL); Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q }, { 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b }, { 'n', "-n N", "Set the dimension of the system.", TYPE_INT , &n }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters }, { 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop }, { 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed }, END_OF_ARGUMENTS }; parseArguments(argc,argv,as); bool ok = true; do{ ok &= run_with_field<Modular<double> >(q,b,n,iters,seed); ok &= run_with_field<ModularBalanced<double> >(q,b,n,iters,seed); ok &= run_with_field<Modular<float> >(q,b,n,iters,seed); ok &= run_with_field<ModularBalanced<float> >(q,b,n,iters,seed); ok &= run_with_field<Modular<int32_t> >(q,b,n,iters,seed); ok &= run_with_field<ModularBalanced<int32_t> >(q,b,n,iters,seed); ok &= run_with_field<Modular<int64_t> >(q,b,n,iters,seed); ok &= run_with_field<ModularBalanced<int64_t> >(q,b,n,iters,seed); ok &= run_with_field<Modular<Givaro::Integer> >(q,5,n/4+1,iters,seed); ok &= run_with_field<Modular<Givaro::Integer> >(q,(b?b:512),n/4+1,iters,seed); } while (loop && ok); return !ok ; } <|endoftext|>
<commit_before>#include "queue thread safe.hpp" #include "gtest/gtest.h" #include <thread> #include <algorithm> #include "aux_tests.hpp" TEST(Push,HandleBasicOperation){ std::threadsafe::queue<int> queue; int out; for (int i = 1;i <= 10;i++){ queue.push(i); queue.wait_back(out); EXPECT_EQ(i,out); queue.wait_top(out); EXPECT_EQ(out,1); EXPECT_EQ(i,queue.size()); } for (int i = 1;i <= 10;i++){ queue.wait_pop(out); EXPECT_EQ(i,out); EXPECT_EQ(10-i,queue.size()); } } TEST(Push,ThreadSafety){ std::threadsafe::queue<int> queue; testPushThreadSafety(queue); } TEST(Push,UpperBound){ std::threadsafe::queue<int> queue; testPushUpperBound(queue); } TEST(Try_pop,HandleBasicOperation){ std::threadsafe::queue<int> queue; for (int i = 1;i <= 10;i++){ queue.push(i); } int out; for (int i = 1;i <= 10;i++){ ASSERT_EQ(10-i+1,queue.size()); ASSERT_EQ(true,queue.try_pop(out)); ASSERT_EQ(i,out); } ASSERT_EQ(0,queue.size()); ASSERT_EQ(false,queue.try_pop(out)); } TEST(Try_pop,ThreadSafety){ std::threadsafe::queue<int> queue; testPopThreadSafety(queue); } TEST(Wait_pop,HandleBasicOperation){ std::threadsafe::queue<int> queue; for (int i = 1;i <= 10;i++){ queue.push(i); } int out; for (int i = 1;i <= 10;i++){ ASSERT_EQ(10-i+1,queue.size()); queue.wait_pop(out); ASSERT_EQ(i,out); } ASSERT_EQ(0,queue.size()); } TEST(Wait_pop,Timer){ std::threadsafe::queue<int> queue; testTimerPop(queue); } TEST(Try_top,HandleBasicOperation){ std::threadsafe::queue<int> queue; int out; ASSERT_EQ(false,queue.try_top(out)); for (int i = 1;i <= 10;i++){ queue.push(i); } for (int i = 1;i <= 10;i++){ ASSERT_EQ(true,queue.try_top(out)); ASSERT_EQ(10,queue.size()); ASSERT_EQ(1,out); } } TEST(Try_top,ThreadSafety){ std::threadsafe::queue<int> queue; constexpr int NUM_PRODUCERS = 1; constexpr int NUM_CONSUMERS = 1; constexpr int ITERATIONS = 10; auto producer = [&](int id,int it){ queue.push(it); }; int n = 0; auto consumer = [&](int id,int it){ int out; while (!queue.try_top(out) && out < ITERATIONS){ ASSERT_EQ(out,n); n++; } }; launchThreads(producer,consumer,NUM_PRODUCERS,NUM_CONSUMERS,ITERATIONS); } TEST(Wait_top,HandleBasicOperation){ std::threadsafe::queue<int> queue; int out; for (int i = 1;i <= 10;i++){ queue.push(i); } for (int i = 10;i >= 1;i--){ queue.wait_top(out); ASSERT_EQ(10,queue.size()); ASSERT_EQ(1,out); } } TEST(Wait_top,Timer){ std::threadsafe::queue<int> queue; std::thread producer([&]{ queue.push(1); std::this_thread::sleep_for(std::chrono::milliseconds(10)); queue.push(2); std::this_thread::sleep_for(std::chrono::milliseconds(50)); queue.push(3); }); std::thread consumer([&]{ int output; try { queue.wait_top(output,std::chrono::milliseconds(5)); ASSERT_EQ(1,output); queue.wait_pop(output); queue.wait_top(output,std::chrono::milliseconds(15)); ASSERT_EQ(2,output); queue.wait_pop(output); } catch(std::threadsafe::Time_Expired e){ FAIL() << " exception Time_Expired throwed"; } try { queue.wait_top(output,std::chrono::milliseconds(1)); FAIL() << " exception didn't throw!"; } catch(std::threadsafe::Time_Expired e){ } }); producer.join(); consumer.join(); } TEST(EMPTY,HanbleBasicOperation){ std::threadsafe::queue<int> queue; ASSERT_TRUE(queue.empty()); queue.push(1); ASSERT_FALSE(queue.empty()); } <commit_msg>Added test wait_back timer at queue<commit_after>#include "queue thread safe.hpp" #include "gtest/gtest.h" #include <thread> #include <algorithm> #include "aux_tests.hpp" TEST(Push,HandleBasicOperation){ std::threadsafe::queue<int> queue; int out; for (int i = 1;i <= 10;i++){ queue.push(i); queue.wait_back(out); EXPECT_EQ(i,out); queue.wait_top(out); EXPECT_EQ(out,1); EXPECT_EQ(i,queue.size()); } for (int i = 1;i <= 10;i++){ queue.wait_pop(out); EXPECT_EQ(i,out); EXPECT_EQ(10-i,queue.size()); } } TEST(Push,ThreadSafety){ std::threadsafe::queue<int> queue; testPushThreadSafety(queue); } TEST(Push,UpperBound){ std::threadsafe::queue<int> queue; testPushUpperBound(queue); } TEST(Try_pop,HandleBasicOperation){ std::threadsafe::queue<int> queue; for (int i = 1;i <= 10;i++){ queue.push(i); } int out; for (int i = 1;i <= 10;i++){ ASSERT_EQ(10-i+1,queue.size()); ASSERT_EQ(true,queue.try_pop(out)); ASSERT_EQ(i,out); } ASSERT_EQ(0,queue.size()); ASSERT_EQ(false,queue.try_pop(out)); } TEST(Try_pop,ThreadSafety){ std::threadsafe::queue<int> queue; testPopThreadSafety(queue); } TEST(Wait_pop,HandleBasicOperation){ std::threadsafe::queue<int> queue; for (int i = 1;i <= 10;i++){ queue.push(i); } int out; for (int i = 1;i <= 10;i++){ ASSERT_EQ(10-i+1,queue.size()); queue.wait_pop(out); ASSERT_EQ(i,out); } ASSERT_EQ(0,queue.size()); } TEST(Wait_pop,Timer){ std::threadsafe::queue<int> queue; testTimerPop(queue); } TEST(Try_top,HandleBasicOperation){ std::threadsafe::queue<int> queue; int out; ASSERT_EQ(false,queue.try_top(out)); for (int i = 1;i <= 10;i++){ queue.push(i); } for (int i = 1;i <= 10;i++){ ASSERT_EQ(true,queue.try_top(out)); ASSERT_EQ(10,queue.size()); ASSERT_EQ(1,out); } } TEST(Try_top,ThreadSafety){ std::threadsafe::queue<int> queue; constexpr int NUM_PRODUCERS = 1; constexpr int NUM_CONSUMERS = 1; constexpr int ITERATIONS = 10; auto producer = [&](int id,int it){ queue.push(it); }; int n = 0; auto consumer = [&](int id,int it){ int out; while (!queue.try_top(out) && out < ITERATIONS){ ASSERT_EQ(out,n); n++; } }; launchThreads(producer,consumer,NUM_PRODUCERS,NUM_CONSUMERS,ITERATIONS); } TEST(Wait_top,HandleBasicOperation){ std::threadsafe::queue<int> queue; int out; for (int i = 1;i <= 10;i++){ queue.push(i); } for (int i = 10;i >= 1;i--){ queue.wait_top(out); ASSERT_EQ(10,queue.size()); ASSERT_EQ(1,out); } } TEST(Wait_top,Timer){ std::threadsafe::queue<int> queue; std::thread producer([&]{ queue.push(1); std::this_thread::sleep_for(std::chrono::milliseconds(10)); queue.push(2); std::this_thread::sleep_for(std::chrono::milliseconds(50)); queue.push(3); }); std::thread consumer([&]{ int output; try { queue.wait_top(output,std::chrono::milliseconds(5)); ASSERT_EQ(1,output); queue.wait_pop(output); queue.wait_top(output,std::chrono::milliseconds(15)); ASSERT_EQ(2,output); queue.wait_pop(output); } catch(std::threadsafe::Time_Expired e){ FAIL() << " exception Time_Expired throwed"; } try { queue.wait_top(output,std::chrono::milliseconds(1)); FAIL() << " exception didn't throw!"; } catch(std::threadsafe::Time_Expired e){ } }); producer.join(); consumer.join(); } TEST(Wait_back,HandleBasicOperation){ std::threadsafe::queue<int> queue; int out; for (int i = 1;i <= 10;i++){ queue.push(i); } for (int i = 10;i >= 1;i--){ queue.wait_back(out); ASSERT_EQ(10,queue.size()); ASSERT_EQ(10,out); } } TEST(Wait_back,Timer){ std::threadsafe::queue<int> queue; std::thread producer([&]{ queue.push(1); std::this_thread::sleep_for(std::chrono::milliseconds(10)); queue.push(2); std::this_thread::sleep_for(std::chrono::milliseconds(50)); queue.push(3); }); std::thread consumer([&]{ int output; try { queue.wait_back(output,std::chrono::milliseconds(5)); ASSERT_EQ(1,output); queue.wait_pop(output); queue.wait_back(output,std::chrono::milliseconds(15)); ASSERT_EQ(2,output); queue.wait_pop(output); } catch(std::threadsafe::Time_Expired e){ FAIL() << " exception Time_Expired throwed"; } try { queue.wait_back(output,std::chrono::milliseconds(1)); FAIL() << " exception didn't throw!"; } catch(std::threadsafe::Time_Expired e){ } }); producer.join(); consumer.join(); } TEST(EMPTY,HanbleBasicOperation){ std::threadsafe::queue<int> queue; ASSERT_TRUE(queue.empty()); queue.push(1); ASSERT_FALSE(queue.empty()); } <|endoftext|>
<commit_before>#include "timeout.h" #include <string.h> #include <sys/select.h> #include <sys/time.h> #include <unistd.h> #include <atomic> #include <cerrno> #include <chrono> #include <csignal> #include <iostream> #include <stdexcept> #include <string> #include "macros.h" #include "pybind11/pybind11.h" #include "util.h" namespace atheris { namespace py = pybind11; int64_t timeout_secs = 300; std::atomic<int64_t> unit_start_time( std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count()); sighandler_t libfuzzer_alarm_signal = SIG_DFL; sighandler_t python_alarm_signal = nullptr; NO_SANITIZE void SetTimeout(int timeout_secs) { ::atheris::timeout_secs = timeout_secs; } // A back SIGALRM signal handler, registered inside of HandleAlarm, to call // libFuzzer's handler if the Python handler never gets called. NO_SANITIZE void LibfuzzerAlarmSignalCallback(int signum) { std::cout << "ALARM: Did not return to Python execution within 1 second " "after timeout. This likely means your fuzzer timed out in " "native code. " "Falling back to native timeout handling." << std::endl; if (libfuzzer_alarm_signal == nullptr || libfuzzer_alarm_signal == SIG_DFL || libfuzzer_alarm_signal == SIG_IGN) { _exit(1); } libfuzzer_alarm_signal(signum); } // Our SIGALRM signal handler. NO_SANITIZE void HandleAlarm(int signum) { int64_t current_time = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); int64_t duration = current_time - unit_start_time; if (duration > timeout_secs) { std::cout << Colorize(STDOUT_FILENO, "\n === Timeout: " + std::to_string(duration) + "s elapsed, timeout=" + std::to_string(timeout_secs) + "s ===") << std::endl; // Queue the python backtrace-printing handler. python_alarm_signal(signum); // If the handler doesn't get called in 1 second, fall back to the libFuzzer // handler. struct sigaction action; checked_sigaction(SIGALRM, nullptr, &action); action.sa_handler = LibfuzzerAlarmSignalCallback; checked_sigaction(SIGALRM, &action, nullptr); alarm(1); // Set 1 second until alarm. } } NO_SANITIZE void SetupTimeoutAlarm() { // If python_alarm_signal isn't set, either SetupPythonSigaction wasn't called // or it returned false. Timeouts are unsupported. if (!python_alarm_signal) return; unit_start_time = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); // set up our timer. The `timeout_secs / 2 + 1` comes from libFuzzer. The // signal handler will check that the timeout has actually been exceeded // before exiting. This means that a test case will be guaranteed to timeout // after exceeding the timeout by 50%, not 100%. struct itimerval tim { {timeout_secs / 2 + 1, 0}, { timeout_secs / 2 + 1, 0 } }; if (setitimer(ITIMER_REAL, &tim, nullptr)) { std::cerr << Colorize(STDERR_FILENO, "Failed to set timer - will not detect timeouts.") << std::endl; } struct sigaction action; checked_sigaction(SIGALRM, nullptr, &action); libfuzzer_alarm_signal = action.sa_handler; action.sa_handler = HandleAlarm; checked_sigaction(SIGALRM, &action, nullptr); } void PrintPythonCallbacks(int signum, py::object frame) { // Cancel any further queued alarm. alarm(0); // Print the Python trace. auto faulthandler = py::module::import("faulthandler"); faulthandler.attr("dump_traceback")(); if (libfuzzer_alarm_signal == nullptr || libfuzzer_alarm_signal == SIG_DFL || libfuzzer_alarm_signal == SIG_IGN) { exit(1); } // exit. libfuzzer_alarm_signal(signum); } bool SetupPythonSigaction() { // So, we want to print the Python stack on a timeout event. However, this is // not safe during a native signal handler. Instead, we register a Python // signal handler, and then invoke that from within our native signal handler. // The registered Python handler doesn't actually trigger until execution // returns to the Python interpreter (the real handler just sets a flag), // which is why this is safe. However, if code execution fails to return to // the Python interpreter (such as an infinite loop in native code), it will // never run. We then have a choice: eiher we try printing the Python trace // from within the handler anyway, which is technically unsafe; or we just // print the native trace. We print the native trace for now, but this might // change in the future. struct sigaction orig_action; checked_sigaction(SIGALRM, nullptr, &orig_action); // If someone has provided a SIGALRM handler, we shouldn't override that - // print a warning and break. if (orig_action.sa_handler != nullptr && orig_action.sa_handler != SIG_DFL && orig_action.sa_handler != SIG_IGN) { std::cerr << "WARNING: SIGALRM handler already defined at address " << reinterpret_cast<void*>(orig_action.sa_handler) << ". Fuzzer timeout will not work." << std::endl; return false; } auto signal_module = py::module::import("signal"); signal_module.attr("signal")(SIGALRM, py::cpp_function(PrintPythonCallbacks)); struct sigaction action; checked_sigaction(SIGALRM, nullptr, &action); python_alarm_signal = action.sa_handler; // Clear the handler that was just registered. This ensures libFuzzer will // register its own signal handler. (It has the same behavior as here, where // it won't register a handler if one is already registered.) if (sigaction(SIGALRM, &orig_action, nullptr)) { std::cerr << "sigaction (get): " << strerror(errno) << std::endl; exit(1); } checked_sigaction(SIGALRM, nullptr, &action); return true; } NO_SANITIZE void RefreshTimeout() { unit_start_time = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); } } // namespace atheris <commit_msg>Refactor in some helper functions to timeout.cc.<commit_after>#include "timeout.h" #include <string.h> #include <sys/select.h> #include <sys/time.h> #include <unistd.h> #include <atomic> #include <cerrno> #include <chrono> #include <csignal> #include <iostream> #include <stdexcept> #include <string> #include "macros.h" #include "pybind11/pybind11.h" #include "util.h" namespace atheris { namespace py = pybind11; int64_t timeout_secs = 300; std::atomic<int64_t> unit_start_time( std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count()); sighandler_t libfuzzer_alarm_signal = SIG_DFL; sighandler_t python_alarm_signal = nullptr; NO_SANITIZE void SetTimeout(int timeout_secs) { ::atheris::timeout_secs = timeout_secs; } NO_SANITIZE bool is_null_or_default(sighandler_t h) { return h == nullptr || h == SIG_DFL || h == SIG_IGN; } // A back SIGALRM signal handler, registered inside of HandleAlarm, to call // libFuzzer's handler if the Python handler never gets called. NO_SANITIZE void LibfuzzerAlarmSignalCallback(int signum) { std::cout << "ALARM: Did not return to Python execution within 1 second " "after timeout. This likely means your fuzzer timed out in " "native code. " "Falling back to native timeout handling." << std::endl; if (is_null_or_default(libfuzzer_alarm_signal)) { _exit(1); } libfuzzer_alarm_signal(signum); } // Our SIGALRM signal handler. NO_SANITIZE void HandleAlarm(int signum) { int64_t current_time = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); int64_t duration = current_time - unit_start_time; if (duration > timeout_secs) { std::cout << Colorize(STDOUT_FILENO, "\n === Timeout: " + std::to_string(duration) + "s elapsed, timeout=" + std::to_string(timeout_secs) + "s ===") << std::endl; // Queue the python backtrace-printing handler. python_alarm_signal(signum); // If the handler doesn't get called in 1 second, fall back to the libFuzzer // handler. struct sigaction action; checked_sigaction(SIGALRM, nullptr, &action); action.sa_handler = LibfuzzerAlarmSignalCallback; checked_sigaction(SIGALRM, &action, nullptr); alarm(1); // Set 1 second until alarm. } } NO_SANITIZE void signal_or_exit(sighandler_t handler, int signum) { if (is_null_or_default(handler)) { exit(1); } handler(signum); } // Returns the old handle in the `signum` signal replacing it with `new_handle`. NO_SANITIZE sighandler_t replace_handle(int signum, sighandler_t new_handle) { struct sigaction action; checked_sigaction(signum, nullptr, &action); auto old_handle = action.sa_handler; action.sa_handler = new_handle; checked_sigaction(signum, &action, nullptr); return old_handle; } NO_SANITIZE void SetupTimeoutAlarm() { // If python_alarm_signal isn't set, either SetupPythonSigaction wasn't called // or it returned false. Timeouts are unsupported. if (!python_alarm_signal) return; unit_start_time = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); // set up our timer. The `timeout_secs / 2 + 1` comes from libFuzzer. The // signal handler will check that the timeout has actually been exceeded // before exiting. This means that a test case will be guaranteed to timeout // after exceeding the timeout by 50%, not 100%. struct itimerval tim { {timeout_secs / 2 + 1, 0}, { timeout_secs / 2 + 1, 0 } }; if (setitimer(ITIMER_REAL, &tim, nullptr)) { std::cerr << Colorize(STDERR_FILENO, "Failed to set timer - will not detect timeouts.") << std::endl; } libfuzzer_alarm_signal = replace_handle(SIGALRM, HandleAlarm); } void PrintPythonCallbacks(int signum, py::object frame) { // Cancel any further queued alarm. alarm(0); // Print the Python trace. auto faulthandler = py::module::import("faulthandler"); faulthandler.attr("dump_traceback")(); signal_or_exit(libfuzzer_alarm_signal, signum); } bool SetupPythonSigaction() { // So, we want to print the Python stack on a timeout event. However, this is // not safe during a native signal handler. Instead, we register a Python // signal handler, and then invoke that from within our native signal handler. // The registered Python handler doesn't actually trigger until execution // returns to the Python interpreter (the real handler just sets a flag), // which is why this is safe. However, if code execution fails to return to // the Python interpreter (such as an infinite loop in native code), it will // never run. We then have a choice: eiher we try printing the Python trace // from within the handler anyway, which is technically unsafe; or we just // print the native trace. We print the native trace for now, but this might // change in the future. struct sigaction orig_action; checked_sigaction(SIGALRM, nullptr, &orig_action); // If someone has provided a SIGALRM handler, we shouldn't override that - // print a warning and break. if (!is_null_or_default(orig_action.sa_handler)) { std::cerr << "WARNING: SIGALRM handler already defined at address " << reinterpret_cast<void*>(orig_action.sa_handler) << ". Fuzzer timeout will not work." << std::endl; return false; } auto signal_module = py::module::import("signal"); signal_module.attr("signal")(SIGALRM, py::cpp_function(PrintPythonCallbacks)); struct sigaction action; checked_sigaction(SIGALRM, nullptr, &action); python_alarm_signal = action.sa_handler; // Clear the handler that was just registered. This ensures libFuzzer will // register its own signal handler. (It has the same behavior as here, where // it won't register a handler if one is already registered.) if (sigaction(SIGALRM, &orig_action, nullptr)) { std::cerr << "sigaction (get): " << strerror(errno) << std::endl; exit(1); } checked_sigaction(SIGALRM, nullptr, &action); return true; } NO_SANITIZE void RefreshTimeout() { unit_start_time = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); } } // namespace atheris <|endoftext|>
<commit_before>#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; ") + tr("2009-%1 The Bitcoin developers").arg(COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); } <commit_msg>aboutdialog: use just "The Bitcoin developers" as tr()-string<commit_after>#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers")); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); } <|endoftext|>
<commit_before>#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2013; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2011-%1 The Gaelcoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); } <commit_msg>changes<commit_after>#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" // Copyright year (2009-this) // Todo: update this when changing our copyright comments in the source const int ABOUTDIALOG_COPYRIGHT_YEAR = 2014; AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers") + QString("<br>") + tr("Copyright") + QString(" &copy; ") + tr("2014 The Gaelcoin developers").arg(ABOUTDIALOG_COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); } <|endoftext|>
<commit_before>#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include <QSet> #include <QTimer> WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedNumTransactions(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance() const { return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } int WalletModel::getNumTransactions() const { int numTransactions = 0; { LOCK(wallet->cs_wallet); numTransactions = wallet->mapWallet.size(); } return numTransactions; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); int newNumTransactions = getNumTransactions(); if(cachedNumTransactions != newNumTransactions) { cachedNumTransactions = newNumTransactions; emit numTransactionsChanged(newNumTransactions); } } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nSplitBlock, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64_t nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64_t> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64_t nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nSplitBlock, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) { if(locked) { // Lock return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { OutputDebugStringF("NotifyKeyStoreStatusChanged\n"); QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if ((!was_locked) && fWalletUnlockStakingOnly) { setWalletLocked(true); was_locked = getEncryptionStatus() == Locked; } if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked && !fWalletUnlockStakingOnly); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); } CTxDestination address; if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { COutPoint outpoint(hash, n); return std::find(wallet->lockedcoins.vLockedCoins.begin(), wallet->lockedcoins.vLockedCoins.end(), outpoint) != wallet->lockedcoins.vLockedCoins.end(); } void WalletModel::lockCoin(COutPoint& outpoint) { wallet->lockedcoins.vLockedCoins.push_back(outpoint); CWalletDB walletdb(wallet->strWalletFile); return; } void WalletModel::unlockCoin(COutPoint& outpoint) { for(std::vector<COutPoint>::iterator it = wallet->lockedcoins.vLockedCoins.begin(); it != wallet->lockedcoins.vLockedCoins.end(); it++) { if (*it == outpoint) { wallet->lockedcoins.vLockedCoins.erase(it); break; } } CWalletDB walletdb(wallet->strWalletFile); walletdb.WriteLockedCoins(wallet->lockedcoins); return; } void WalletModel::listLockedCoins(std::vector<COutPoint>& vLockedCoins) { vLockedCoins = wallet->lockedcoins.vLockedCoins; return; } //Information for coin control void WalletModel::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight) { wallet->GetStakeWeightFromValue(nTime, nValue, nWeight); } void WalletModel::setSplitBlock(bool fSplitBlock) { wallet->fSplitBlock = fSplitBlock; } bool WalletModel::getSplitBlock() { return wallet->fSplitBlock; } bool WalletModel::isMine(const CBitcoinAddress &address) { return IsMine(*wallet, address.Get()); } <commit_msg>fix coin lock persisting through shutdown<commit_after>#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include <QSet> #include <QTimer> WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedNumTransactions(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance() const { return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } int WalletModel::getNumTransactions() const { int numTransactions = 0; { LOCK(wallet->cs_wallet); numTransactions = wallet->mapWallet.size(); } return numTransactions; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); int newNumTransactions = getNumTransactions(); if(cachedNumTransactions != newNumTransactions) { cachedNumTransactions = newNumTransactions; emit numTransactionsChanged(newNumTransactions); } } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nSplitBlock, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64_t nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64_t> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64_t nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nSplitBlock, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) { if(locked) { // Lock return wallet->Lock(); } else { // Unlock return wallet->Unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { OutputDebugStringF("NotifyKeyStoreStatusChanged\n"); QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if ((!was_locked) && fWalletUnlockStakingOnly) { setWalletLocked(true); was_locked = getEncryptionStatus() == Locked; } if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked && !fWalletUnlockStakingOnly); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); } CTxDestination address; if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { COutPoint outpoint(hash, n); return std::find(wallet->lockedcoins.vLockedCoins.begin(), wallet->lockedcoins.vLockedCoins.end(), outpoint) != wallet->lockedcoins.vLockedCoins.end(); } void WalletModel::lockCoin(COutPoint& outpoint) { wallet->lockedcoins.vLockedCoins.push_back(outpoint); CWalletDB walletdb(wallet->strWalletFile); walletdb.WriteLockedCoins(wallet->lockedcoins); return; } void WalletModel::unlockCoin(COutPoint& outpoint) { for(std::vector<COutPoint>::iterator it = wallet->lockedcoins.vLockedCoins.begin(); it != wallet->lockedcoins.vLockedCoins.end(); it++) { if (*it == outpoint) { wallet->lockedcoins.vLockedCoins.erase(it); break; } } CWalletDB walletdb(wallet->strWalletFile); walletdb.WriteLockedCoins(wallet->lockedcoins); return; } void WalletModel::listLockedCoins(std::vector<COutPoint>& vLockedCoins) { vLockedCoins = wallet->lockedcoins.vLockedCoins; return; } //Information for coin control void WalletModel::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight) { wallet->GetStakeWeightFromValue(nTime, nValue, nWeight); } void WalletModel::setSplitBlock(bool fSplitBlock) { wallet->fSplitBlock = fSplitBlock; } bool WalletModel::getSplitBlock() { return wallet->fSplitBlock; } bool WalletModel::isMine(const CBitcoinAddress &address) { return IsMine(*wallet, address.Get()); } <|endoftext|>
<commit_before>#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include <QSet> #include <QTimer> WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedNumTransactions(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance() const { return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } int WalletModel::getNumTransactions() const { int numTransactions = 0; { LOCK(wallet->cs_wallet); numTransactions = wallet->mapWallet.size(); } return numTransactions; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); int newNumTransactions = getNumTransactions(); if(cachedNumTransactions != newNumTransactions) { cachedNumTransactions = newNumTransactions; emit numTransactionsChanged(newNumTransactions); } } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nSplitBlock, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64_t nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64_t> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64_t nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nSplitBlock, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase, bool formint) { if(locked) { // Lock return wallet->Lock(); } else { // Unlock bool rc; rc = wallet->Unlock(passPhrase); if (rc && formint) wallet->fWalletUnlockMintOnly=true; return rc; } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { OutputDebugStringF("NotifyKeyStoreStatusChanged\n"); QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if ((!was_locked) && wallet->fWalletUnlockMintOnly) { setWalletLocked(true); was_locked = getEncryptionStatus() == Locked; } if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked && !wallet->fWalletUnlockMintOnly); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); } CTxDestination address; if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { COutPoint outpoint(hash, n); return std::find(wallet->lockedcoins.vLockedCoins.begin(), wallet->lockedcoins.vLockedCoins.end(), outpoint) != wallet->lockedcoins.vLockedCoins.end(); } void WalletModel::lockCoin(COutPoint& outpoint) { wallet->lockedcoins.vLockedCoins.push_back(outpoint); CWalletDB walletdb(wallet->strWalletFile); walletdb.WriteLockedCoins(wallet->lockedcoins); return; } void WalletModel::unlockCoin(COutPoint& outpoint) { for(std::vector<COutPoint>::iterator it = wallet->lockedcoins.vLockedCoins.begin(); it != wallet->lockedcoins.vLockedCoins.end(); it++) { if (*it == outpoint) { wallet->lockedcoins.vLockedCoins.erase(it); break; } } CWalletDB walletdb(wallet->strWalletFile); walletdb.WriteLockedCoins(wallet->lockedcoins); return; } void WalletModel::listLockedCoins(std::vector<COutPoint>& vLockedCoins) { vLockedCoins = wallet->lockedcoins.vLockedCoins; return; } //Information for coin control void WalletModel::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight) { wallet->GetStakeWeightFromValue(nTime, nValue, nWeight); } void WalletModel::setSplitBlock(bool fSplitBlock) { wallet->fSplitBlock = fSplitBlock; } bool WalletModel::getSplitBlock() { return wallet->fSplitBlock; } bool WalletModel::isMine(const CBitcoinAddress &address) { return IsMine(*wallet, address.Get()); } <commit_msg>mark MintOnly as false if wallet gets locked<commit_after>#include "walletmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "ui_interface.h" #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" #include <QSet> #include <QTimer> WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) : QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0), transactionTableModel(0), cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0), cachedNumTransactions(0), cachedEncryptionStatus(Unencrypted), cachedNumBlocks(0) { addressTableModel = new AddressTableModel(wallet, this); transactionTableModel = new TransactionTableModel(wallet, this); // This timer will be fired repeatedly to update the balance pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged())); pollTimer->start(MODEL_UPDATE_DELAY); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } qint64 WalletModel::getBalance() const { return wallet->GetBalance(); } qint64 WalletModel::getUnconfirmedBalance() const { return wallet->GetUnconfirmedBalance(); } qint64 WalletModel::getStake() const { return wallet->GetStake(); } qint64 WalletModel::getImmatureBalance() const { return wallet->GetImmatureBalance(); } int WalletModel::getNumTransactions() const { int numTransactions = 0; { LOCK(wallet->cs_wallet); numTransactions = wallet->mapWallet.size(); } return numTransactions; } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) emit encryptionStatusChanged(newEncryptionStatus); } void WalletModel::pollBalanceChanged() { if(nBestHeight != cachedNumBlocks) { // Balance and number of transactions might have changed cachedNumBlocks = nBestHeight; checkBalanceChanged(); } } void WalletModel::checkBalanceChanged() { qint64 newBalance = getBalance(); qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); } } void WalletModel::updateTransaction(const QString &hash, int status) { if(transactionTableModel) transactionTableModel->updateTransaction(hash, status); // Balance and number of transactions might have changed checkBalanceChanged(); int newNumTransactions = getNumTransactions(); if(cachedNumTransactions != newNumTransactions) { cachedNumTransactions = newNumTransactions; emit numTransactionsChanged(newNumTransactions); } } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, status); } bool WalletModel::validateAddress(const QString &address) { CBitcoinAddress addressParsed(address.toStdString()); return addressParsed.IsValid(); } WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nSplitBlock, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64_t nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64_t> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64_t nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nSplitBlock, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); } // Add addresses / update labels that we've sent to to the address book foreach(const SendCoinsRecipient &rcp, recipients) { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = CBitcoinAddress(strAddress).Get(); std::string strLabel = rcp.label.toStdString(); { LOCK(wallet->cs_wallet); std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest); // Check if we have a new address or an updated label if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) { wallet->SetAddressBookName(dest, strLabel); } } } return SendCoinsReturn(OK, 0, hex); } OptionsModel *WalletModel::getOptionsModel() { return optionsModel; } AddressTableModel *WalletModel::getAddressTableModel() { return addressTableModel; } TransactionTableModel *WalletModel::getTransactionTableModel() { return transactionTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!wallet->IsCrypted()) { return Unencrypted; } else if(wallet->IsLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase) { if(encrypted) { // Encrypt return wallet->EncryptWallet(passphrase); } else { // Decrypt -- TODO; not supported yet return false; } } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase, bool formint) { if(locked) { // Lock wallet->fWalletUnlockMintOnly = false; return wallet->Lock(); } else { // Unlock bool rc; rc = wallet->Unlock(passPhrase); if (rc && formint) wallet->fWalletUnlockMintOnly=true; return rc; } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; { LOCK(wallet->cs_wallet); wallet->Lock(); // Make sure wallet is locked before attempting pass change retval = wallet->ChangeWalletPassphrase(oldPass, newPass); } return retval; } bool WalletModel::backupWallet(const QString &filename) { return BackupWallet(*wallet, filename.toLocal8Bit().data()); } // Handlers for core signals static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet) { OutputDebugStringF("NotifyKeyStoreStatusChanged\n"); QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); } static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { OutputDebugStringF("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), Q_ARG(QString, QString::fromStdString(label)), Q_ARG(bool, isMine), Q_ARG(int, status)); } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyTransactionChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1)); wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5)); wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3)); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if ((!was_locked) && wallet->fWalletUnlockMintOnly) { setWalletLocked(true); was_locked = getEncryptionStatus() == Locked; } if(was_locked) { // Request UI to unlock wallet emit requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked && !wallet->fWalletUnlockMintOnly); } WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock): wallet(wallet), valid(valid), relock(relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs) { // Transfer context; old object no longer relocks wallet *this = rhs; rhs.relock = false; } bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { return wallet->GetPubKey(address, vchPubKeyOut); } // returns a list of COutputs from COutPoints void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs) { BOOST_FOREACH(const COutPoint& outpoint, vOutpoints) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vOutputs.push_back(out); } } // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const { std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins); std::vector<COutPoint> vLockedCoins; // add locked coins BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins) { if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); vCoins.push_back(out); } BOOST_FOREACH(const COutput& out, vCoins) { COutput cout = out; while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); } CTxDestination address; if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { COutPoint outpoint(hash, n); return std::find(wallet->lockedcoins.vLockedCoins.begin(), wallet->lockedcoins.vLockedCoins.end(), outpoint) != wallet->lockedcoins.vLockedCoins.end(); } void WalletModel::lockCoin(COutPoint& outpoint) { wallet->lockedcoins.vLockedCoins.push_back(outpoint); CWalletDB walletdb(wallet->strWalletFile); walletdb.WriteLockedCoins(wallet->lockedcoins); return; } void WalletModel::unlockCoin(COutPoint& outpoint) { for(std::vector<COutPoint>::iterator it = wallet->lockedcoins.vLockedCoins.begin(); it != wallet->lockedcoins.vLockedCoins.end(); it++) { if (*it == outpoint) { wallet->lockedcoins.vLockedCoins.erase(it); break; } } CWalletDB walletdb(wallet->strWalletFile); walletdb.WriteLockedCoins(wallet->lockedcoins); return; } void WalletModel::listLockedCoins(std::vector<COutPoint>& vLockedCoins) { vLockedCoins = wallet->lockedcoins.vLockedCoins; return; } //Information for coin control void WalletModel::getStakeWeightFromValue(const int64_t& nTime, const int64_t& nValue, uint64_t& nWeight) { wallet->GetStakeWeightFromValue(nTime, nValue, nWeight); } void WalletModel::setSplitBlock(bool fSplitBlock) { wallet->fSplitBlock = fSplitBlock; } bool WalletModel::getSplitBlock() { return wallet->fSplitBlock; } bool WalletModel::isMine(const CBitcoinAddress &address) { return IsMine(*wallet, address.Get()); } <|endoftext|>
<commit_before>// #define X(FORMAT, SIZE, TYPE, VK, DX, GLI, GLF, GLT) X(rhi::image_format::rgba_unorm8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE) X(rhi::image_format::rgba_srgb8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_SRGB, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE) X(rhi::image_format::rgba_norm8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SNORM, GL_RGBA8_SNORM, GL_RGBA, GL_BYTE) X(rhi::image_format::rgba_uint8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_UINT, GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE) X(rhi::image_format::rgba_int8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_SINT, DXGI_FORMAT_R8G8B8A8_SINT, GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE) X(rhi::image_format::rgba_unorm16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_R16G16B16A16_UNORM, GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT) X(rhi::image_format::rgba_norm16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_R16G16B16A16_SNORM, GL_RGBA16_SNORM, GL_RGBA, GL_SHORT) X(rhi::image_format::rgba_uint16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_UINT, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT) X(rhi::image_format::rgba_int16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_SINT, DXGI_FORMAT_R16G16B16A16_SINT, GL_RGBA16I, GL_RGBA_INTEGER, GL_SHORT) X(rhi::image_format::rgba_float16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_SFLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT) X(rhi::image_format::rgba_uint32, 4*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_UINT, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::rgba_int32, 4*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32A32_SINT, DXGI_FORMAT_R32G32B32A32_SINT, GL_RGBA32I, GL_RGBA_INTEGER, GL_INT) X(rhi::image_format::rgba_float32, 4*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32A32_SFLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, GL_RGBA32F, GL_RGBA, GL_FLOAT) X(rhi::image_format::rgb_uint32, 3*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32_UINT, GL_RGB32UI, GL_RGB_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::rgb_int32, 3*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R32G32B32_SINT, GL_RGB32I, GL_RGB_INTEGER, GL_INT) X(rhi::image_format::rgb_float32, 3*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32_SFLOAT, DXGI_FORMAT_R32G32B32_FLOAT, GL_RGB32F, GL_RGB, GL_FLOAT) X(rhi::image_format::rg_unorm8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UNORM, GL_RG8, GL_RG, GL_UNSIGNED_BYTE) X(rhi::image_format::rg_norm8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_SNORM, DXGI_FORMAT_R8G8_SNORM, GL_RG8_SNORM, GL_RG, GL_BYTE) X(rhi::image_format::rg_uint8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_UINT, DXGI_FORMAT_R8G8_UINT, GL_RG8UI, GL_RG_INTEGER, GL_UNSIGNED_BYTE) X(rhi::image_format::rg_int8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_SINT, DXGI_FORMAT_R8G8_SINT, GL_RG8I, GL_RG_INTEGER, GL_BYTE) X(rhi::image_format::rg_unorm16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_UNORM, GL_RG16, GL_RG, GL_UNSIGNED_SHORT) X(rhi::image_format::rg_norm16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_SNORM, GL_RG16_SNORM, GL_RG, GL_SHORT) X(rhi::image_format::rg_uint16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_UINT, DXGI_FORMAT_R16G16_UINT, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT) X(rhi::image_format::rg_int16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_SINT, DXGI_FORMAT_R16G16_SINT, GL_RG16I, GL_RG_INTEGER, GL_SHORT) X(rhi::image_format::rg_float16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_SFLOAT, DXGI_FORMAT_R16G16_FLOAT, GL_RG16F, GL_RG, GL_HALF_FLOAT) X(rhi::image_format::rg_uint32, 2*4, rhi::attachment_type::color, VK_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_UINT, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::rg_int32, 2*4, rhi::attachment_type::color, VK_FORMAT_R32G32_SINT, DXGI_FORMAT_R32G32_SINT, GL_RG32I, GL_RG_INTEGER, GL_INT) X(rhi::image_format::rg_float32, 2*4, rhi::attachment_type::color, VK_FORMAT_R32G32_SFLOAT, DXGI_FORMAT_R32G32_FLOAT, GL_RG32F, GL_RG, GL_FLOAT) X(rhi::image_format::r_unorm8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UNORM, GL_R8, GL_RED, GL_UNSIGNED_BYTE) X(rhi::image_format::r_norm8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SNORM, GL_R8_SNORM, GL_RED, GL_BYTE) X(rhi::image_format::r_uint8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8_UINT, DXGI_FORMAT_R8_UINT, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE) X(rhi::image_format::r_int8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8G8_SINT, DXGI_FORMAT_R8_SINT, GL_R8I, GL_RED_INTEGER, GL_BYTE) X(rhi::image_format::r_unorm16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UNORM, GL_R16, GL_RED, GL_UNSIGNED_SHORT) X(rhi::image_format::r_norm16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_SNORM, DXGI_FORMAT_R16_SNORM, GL_R16_SNORM, GL_RED, GL_SHORT) X(rhi::image_format::r_uint16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_UINT, DXGI_FORMAT_R16_UINT, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT) X(rhi::image_format::r_int16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_SINT, DXGI_FORMAT_R16_SINT, GL_R16I, GL_RED_INTEGER, GL_SHORT) X(rhi::image_format::r_float16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_SFLOAT, DXGI_FORMAT_R16_FLOAT, GL_R16F, GL_RED, GL_HALF_FLOAT) X(rhi::image_format::r_uint32, 1*4, rhi::attachment_type::color, VK_FORMAT_R32_UINT, DXGI_FORMAT_R32_UINT, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::r_int32, 1*4, rhi::attachment_type::color, VK_FORMAT_R32_SINT, DXGI_FORMAT_R32_SINT, GL_R32I, GL_RED_INTEGER, GL_INT) X(rhi::image_format::r_float32, 1*4, rhi::attachment_type::color, VK_FORMAT_R32_SFLOAT, DXGI_FORMAT_R32_FLOAT, GL_R32F, GL_RED, GL_FLOAT) X(rhi::image_format::depth_unorm16, 2, rhi::attachment_type::depth_stencil, VK_FORMAT_D16_UNORM, DXGI_FORMAT_D16_UNORM, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT) X(rhi::image_format::depth_unorm24_stencil8, 4, rhi::attachment_type::depth_stencil, VK_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_D24_UNORM_S8_UINT, GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8) X(rhi::image_format::depth_float32, 4, rhi::attachment_type::depth_stencil, VK_FORMAT_D32_SFLOAT, DXGI_FORMAT_D32_FLOAT, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT) X(rhi::image_format::depth_float32_stencil8, 8, rhi::attachment_type::depth_stencil, VK_FORMAT_D32_SFLOAT_S8_UINT, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV) <commit_msg>Formatting changes to format table.<commit_after>// #define X(FORMAT, SIZE, TYPE, VK, DX, GLI, GLF, GLT) X(rhi::image_format::rgba_unorm8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE) X(rhi::image_format::rgba_srgb8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_SRGB, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE) X(rhi::image_format::rgba_norm8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SNORM, GL_RGBA8_SNORM, GL_RGBA, GL_BYTE) X(rhi::image_format::rgba_uint8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_UINT, GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE) X(rhi::image_format::rgba_int8, 4*1, rhi::attachment_type::color, VK_FORMAT_R8G8B8A8_SINT, DXGI_FORMAT_R8G8B8A8_SINT, GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE) X(rhi::image_format::rgba_unorm16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_R16G16B16A16_UNORM, GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT) X(rhi::image_format::rgba_norm16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_R16G16B16A16_SNORM, GL_RGBA16_SNORM, GL_RGBA, GL_SHORT) X(rhi::image_format::rgba_uint16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_UINT, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT) X(rhi::image_format::rgba_int16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_SINT, DXGI_FORMAT_R16G16B16A16_SINT, GL_RGBA16I, GL_RGBA_INTEGER, GL_SHORT) X(rhi::image_format::rgba_float16, 4*2, rhi::attachment_type::color, VK_FORMAT_R16G16B16A16_SFLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT) X(rhi::image_format::rgba_uint32, 4*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_UINT, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::rgba_int32, 4*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32A32_SINT, DXGI_FORMAT_R32G32B32A32_SINT, GL_RGBA32I, GL_RGBA_INTEGER, GL_INT) X(rhi::image_format::rgba_float32, 4*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32A32_SFLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, GL_RGBA32F, GL_RGBA, GL_FLOAT) X(rhi::image_format::rgb_uint32, 3*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32_UINT, GL_RGB32UI, GL_RGB_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::rgb_int32, 3*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R32G32B32_SINT, GL_RGB32I, GL_RGB_INTEGER, GL_INT) X(rhi::image_format::rgb_float32, 3*4, rhi::attachment_type::color, VK_FORMAT_R32G32B32_SFLOAT, DXGI_FORMAT_R32G32B32_FLOAT, GL_RGB32F, GL_RGB, GL_FLOAT) X(rhi::image_format::rg_unorm8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UNORM, GL_RG8, GL_RG, GL_UNSIGNED_BYTE) X(rhi::image_format::rg_norm8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_SNORM, DXGI_FORMAT_R8G8_SNORM, GL_RG8_SNORM, GL_RG, GL_BYTE) X(rhi::image_format::rg_uint8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_UINT, DXGI_FORMAT_R8G8_UINT, GL_RG8UI, GL_RG_INTEGER, GL_UNSIGNED_BYTE) X(rhi::image_format::rg_int8, 2*1, rhi::attachment_type::color, VK_FORMAT_R8G8_SINT, DXGI_FORMAT_R8G8_SINT, GL_RG8I, GL_RG_INTEGER, GL_BYTE) X(rhi::image_format::rg_unorm16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_UNORM, GL_RG16, GL_RG, GL_UNSIGNED_SHORT) X(rhi::image_format::rg_norm16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_SNORM, GL_RG16_SNORM, GL_RG, GL_SHORT) X(rhi::image_format::rg_uint16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_UINT, DXGI_FORMAT_R16G16_UINT, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT) X(rhi::image_format::rg_int16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_SINT, DXGI_FORMAT_R16G16_SINT, GL_RG16I, GL_RG_INTEGER, GL_SHORT) X(rhi::image_format::rg_float16, 2*2, rhi::attachment_type::color, VK_FORMAT_R16G16_SFLOAT, DXGI_FORMAT_R16G16_FLOAT, GL_RG16F, GL_RG, GL_HALF_FLOAT) X(rhi::image_format::rg_uint32, 2*4, rhi::attachment_type::color, VK_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_UINT, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::rg_int32, 2*4, rhi::attachment_type::color, VK_FORMAT_R32G32_SINT, DXGI_FORMAT_R32G32_SINT, GL_RG32I, GL_RG_INTEGER, GL_INT) X(rhi::image_format::rg_float32, 2*4, rhi::attachment_type::color, VK_FORMAT_R32G32_SFLOAT, DXGI_FORMAT_R32G32_FLOAT, GL_RG32F, GL_RG, GL_FLOAT) X(rhi::image_format::r_unorm8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UNORM, GL_R8, GL_RED, GL_UNSIGNED_BYTE) X(rhi::image_format::r_norm8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SNORM, GL_R8_SNORM, GL_RED, GL_BYTE) X(rhi::image_format::r_uint8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8_UINT, DXGI_FORMAT_R8_UINT, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE) X(rhi::image_format::r_int8, 1*1, rhi::attachment_type::color, VK_FORMAT_R8G8_SINT, DXGI_FORMAT_R8_SINT, GL_R8I, GL_RED_INTEGER, GL_BYTE) X(rhi::image_format::r_unorm16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UNORM, GL_R16, GL_RED, GL_UNSIGNED_SHORT) X(rhi::image_format::r_norm16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_SNORM, DXGI_FORMAT_R16_SNORM, GL_R16_SNORM, GL_RED, GL_SHORT) X(rhi::image_format::r_uint16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_UINT, DXGI_FORMAT_R16_UINT, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT) X(rhi::image_format::r_int16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_SINT, DXGI_FORMAT_R16_SINT, GL_R16I, GL_RED_INTEGER, GL_SHORT) X(rhi::image_format::r_float16, 1*2, rhi::attachment_type::color, VK_FORMAT_R16_SFLOAT, DXGI_FORMAT_R16_FLOAT, GL_R16F, GL_RED, GL_HALF_FLOAT) X(rhi::image_format::r_uint32, 1*4, rhi::attachment_type::color, VK_FORMAT_R32_UINT, DXGI_FORMAT_R32_UINT, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT) X(rhi::image_format::r_int32, 1*4, rhi::attachment_type::color, VK_FORMAT_R32_SINT, DXGI_FORMAT_R32_SINT, GL_R32I, GL_RED_INTEGER, GL_INT) X(rhi::image_format::r_float32, 1*4, rhi::attachment_type::color, VK_FORMAT_R32_SFLOAT, DXGI_FORMAT_R32_FLOAT, GL_R32F, GL_RED, GL_FLOAT) X(rhi::image_format::depth_unorm16, 2, rhi::attachment_type::depth_stencil, VK_FORMAT_D16_UNORM, DXGI_FORMAT_D16_UNORM, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT) X(rhi::image_format::depth_unorm24_stencil8, 4, rhi::attachment_type::depth_stencil, VK_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_D24_UNORM_S8_UINT, GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8) X(rhi::image_format::depth_float32, 4, rhi::attachment_type::depth_stencil, VK_FORMAT_D32_SFLOAT, DXGI_FORMAT_D32_FLOAT, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT) X(rhi::image_format::depth_float32_stencil8, 8, rhi::attachment_type::depth_stencil, VK_FORMAT_D32_SFLOAT_S8_UINT, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV) <|endoftext|>
<commit_before>#include <sstream> #include <algorithm> #include <fstream> #include <iterator> #include "logger.hpp" #include "oddlib/stream.hpp" #include "oddlib/exceptions.hpp" namespace Oddlib { Stream::Stream(std::vector<Uint8>&& data) { mSize = data.size(); auto s = std::make_unique<std::stringstream>(); std::copy(data.begin(), data.end(), std::ostream_iterator<unsigned char>(*s)); mStream = std::move(s); Seek(0); mName = "Memory buffer (" + std::to_string(mSize) + ") bytes"; } Stream::Stream(const std::string& fileName) : mName(fileName) { auto s = std::make_unique<std::ifstream>(); s->open(fileName, std::ios::in | std::ios::binary | std::ios::ate); if (!*s) { LOG_ERROR("Lvl file not found " << fileName); throw Exception("File not found"); } mSize = static_cast<size_t>(s->tellg()); s->seekg(std::ios::beg); mStream = std::move(s); } template<typename T> void DoRead(std::unique_ptr<std::istream>& stream, T& output) { if (!stream->read(reinterpret_cast<char*>(&output), sizeof(output))) { throw Exception("Read failure"); } } void Stream::ReadUInt8(Uint8& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadUInt32(Uint32& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadUInt16(Uint16& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadSInt16(Sint16& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadBytes(Sint8* pDest, size_t destSize) { if (!mStream->read(reinterpret_cast<char*>(pDest), destSize)) { throw Exception("ReadBytes failure"); } } void Stream::ReadBytes(Uint8* pDest, size_t destSize) { if (!mStream->read(reinterpret_cast<char*>(pDest), destSize)) { throw Exception("ReadBytes failure"); } } void Stream::Seek(size_t pos) { if (!mStream->seekg(pos)) { throw Exception("Seek failure"); } } bool Stream::AtEnd() const { const int c = mStream->peek(); return (c == EOF); } size_t Stream::Pos() const { const size_t pos = static_cast<size_t>(mStream->tellg()); return pos; } size_t Stream::Size() const { return mSize; } } <commit_msg>fix incorrect error log message<commit_after>#include <sstream> #include <algorithm> #include <fstream> #include <iterator> #include "logger.hpp" #include "oddlib/stream.hpp" #include "oddlib/exceptions.hpp" namespace Oddlib { Stream::Stream(std::vector<Uint8>&& data) { mSize = data.size(); auto s = std::make_unique<std::stringstream>(); std::copy(data.begin(), data.end(), std::ostream_iterator<unsigned char>(*s)); mStream = std::move(s); Seek(0); mName = "Memory buffer (" + std::to_string(mSize) + ") bytes"; } Stream::Stream(const std::string& fileName) : mName(fileName) { auto s = std::make_unique<std::ifstream>(); s->open(fileName, std::ios::in | std::ios::binary | std::ios::ate); if (!*s) { LOG_ERROR("File not found " << fileName); throw Exception("File not found"); } mSize = static_cast<size_t>(s->tellg()); s->seekg(std::ios::beg); mStream = std::move(s); } template<typename T> void DoRead(std::unique_ptr<std::istream>& stream, T& output) { if (!stream->read(reinterpret_cast<char*>(&output), sizeof(output))) { throw Exception("Read failure"); } } void Stream::ReadUInt8(Uint8& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadUInt32(Uint32& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadUInt16(Uint16& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadSInt16(Sint16& output) { DoRead<decltype(output)>(mStream, output); } void Stream::ReadBytes(Sint8* pDest, size_t destSize) { if (!mStream->read(reinterpret_cast<char*>(pDest), destSize)) { throw Exception("ReadBytes failure"); } } void Stream::ReadBytes(Uint8* pDest, size_t destSize) { if (!mStream->read(reinterpret_cast<char*>(pDest), destSize)) { throw Exception("ReadBytes failure"); } } void Stream::Seek(size_t pos) { if (!mStream->seekg(pos)) { throw Exception("Seek failure"); } } bool Stream::AtEnd() const { const int c = mStream->peek(); return (c == EOF); } size_t Stream::Pos() const { const size_t pos = static_cast<size_t>(mStream->tellg()); return pos; } size_t Stream::Size() const { return mSize; } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: AliTRDtrackingSector.cxx 23810 2008-02-08 09:00:27Z hristov $ */ /////////////////////////////////////////////////////////////////////////////// // // // Tracking data container for one sector // // // // Authors: // // Alex Bercuci <[email protected]> // // Markus Fasel <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////// #include "AliTRDcalibDB.h" #include "AliTRDCommonParam.h" #include "AliTRDpadPlane.h" #include "AliTRDtrackingSector.h" #include "AliTRDtrackingChamber.h" ClassImp(AliTRDtrackingSector) //_____________________________________________________________________________ AliTRDtrackingSector::AliTRDtrackingSector() :fSector(-1) ,fN(0) ,fGeom(0x0) { // Default constructor memset(fChamber, 0, AliTRDgeometry::kNdets*sizeof(AliTRDtrackingChamber*)); memset(fIndex, 1, AliTRDgeometry::kNdets*sizeof(Char_t)); memset(fX0, 0, AliTRDgeometry::kNlayer*sizeof(Float_t)); } //_____________________________________________________________________________ AliTRDtrackingSector::AliTRDtrackingSector(AliTRDgeometry *geo, Int_t gs) :fSector(gs) ,fN(0) ,fGeom(geo) { // // AliTRDtrackingSector Constructor // memset(fChamber, 0, AliTRDgeometry::kNdets*sizeof(AliTRDtrackingChamber*)); memset(fIndex, 1, AliTRDgeometry::kNdets*sizeof(Char_t)); memset(fX0, 0, AliTRDgeometry::kNlayer*sizeof(Float_t)); } //_____________________________________________________________________________ void AliTRDtrackingSector::Init(const AliTRDReconstructor *rec, const AliTRDCalDet *cal) { // Steer building of tracking chambers and build tracking sector. // Propagate radial position information (calibration/alignment aware) from chambers to sector level // AliTRDchamberTimeBin *tb = 0x0; AliTRDtrackingChamber **tc = &fChamber[0]; for(Int_t ic = 0; (ic<AliTRDgeometry::kNdets) && (*tc); ic++, tc++){ for(Int_t itb=0; itb<AliTRDseed::knTimebins; itb++){ if(!(tb = (*tc)->GetTB(itb))) continue; tb->SetReconstructor(rec); } (*tc)->Build(fGeom, cal, rec->IsHLT()); } Int_t nl; for(int il=0; il<AliTRDgeometry::kNlayer; il++){ fX0[il] = 0.; nl = 0; for(int is=0; is<AliTRDgeometry::kNstack; is++){ Int_t idx = is*AliTRDgeometry::kNlayer + il; if(fIndex[idx]<0) continue; fX0[il] += GetChamber(fIndex[idx])->GetX(); nl++; } if(!nl){ //printf("Could not estimate radial position of plane %d in sector %d.\n", ip, fSector); continue; } fX0[il] /= Float_t(nl); } } //_____________________________________________________________________________ void AliTRDtrackingSector::Clear(const Option_t *opt) { // Reset counters and steer chamber clear AliTRDtrackingChamber **tc = &fChamber[0]; for(Int_t ich=0; ich<fN; ich++, tc++){ (*tc)->Clear(opt); delete (*tc); (*tc) = 0x0; // I would avoid } memset(fIndex, 1, AliTRDgeometry::kNdets*sizeof(Char_t)); fN = 0; } //_____________________________________________________________________________ AliTRDtrackingChamber* AliTRDtrackingSector::GetChamber(Int_t stack, Int_t layer, Bool_t build) { // Return chamber at position (stack, plane) in current // sector or build a new one if it is not already created Int_t ch = stack*AliTRDgeometry::kNlayer + layer; if(fIndex[ch] >= 0) return fChamber[Int_t(fIndex[ch])]; else if(!build) return 0x0; // CHAMBER HAS TO BE BUILD Int_t rch = ch;do rch--; while(rch>=0 && fIndex[rch]<0); fIndex[ch] = rch >=0 ? fIndex[rch]+1 : 0; fN++; memmove(&fChamber[Int_t(fIndex[ch])+1], &fChamber[Int_t(fIndex[ch])], (AliTRDgeometry::kNdets-fIndex[ch]-1)*sizeof(void*)); for(Int_t ic = ch+1; ic<AliTRDgeometry::kNdets; ic++) fIndex[ic] += fIndex[ic] >= 0 ? 1 : 0; AliTRDtrackingChamber *chmb = fChamber[Int_t(fIndex[ch])] = new AliTRDtrackingChamber(); chmb->SetDetector(AliTRDgeometry::GetDetector(layer, stack, fSector)); return chmb; } //_____________________________________________________________________________ AliTRDtrackingChamber** AliTRDtrackingSector::GetStack(Int_t stack) { // Return chamber at position (stack, plane) in current // sector or build a new one if it is not already created if(stack<0 || stack>=AliTRDgeometry::kNstack) return 0x0; Int_t ich, n = 0; for(int il=0; il<AliTRDgeometry::kNlayer; il++){ ich = stack*AliTRDgeometry::kNlayer + il; if(fIndex[ich] < 0) fStack[il] = 0x0; else{ fStack[il] = fChamber[Int_t(fIndex[ich])]; n++; } } return n ? &fStack[0] : 0x0; } //_____________________________________________________________________________ void AliTRDtrackingSector::Print(Option_t *) { // Dump info about this tracking sector and the tracking chamber within // printf("\tSector %2d\n", fSector); for(int il=0; il<AliTRDgeometry::kNlayer; il++){ for(int is =0; is<AliTRDgeometry::kNstack; is++){ Int_t ch = is*AliTRDgeometry::kNlayer + il; printf("%2d[%2d] ", fIndex[ch], fIndex[ch]>=0 ? fChamber[Int_t(fIndex[ch])]->GetNClusters() : 0); } printf("\n"); } } <commit_msg>fix crash in TRD reconstruction<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: AliTRDtrackingSector.cxx 23810 2008-02-08 09:00:27Z hristov $ */ /////////////////////////////////////////////////////////////////////////////// // // // Tracking data container for one sector // // // // Authors: // // Alex Bercuci <[email protected]> // // Markus Fasel <[email protected]> // // // /////////////////////////////////////////////////////////////////////////////// #include "AliTRDcalibDB.h" #include "AliTRDCommonParam.h" #include "AliTRDpadPlane.h" #include "AliTRDtrackingSector.h" #include "AliTRDtrackingChamber.h" ClassImp(AliTRDtrackingSector) //_____________________________________________________________________________ AliTRDtrackingSector::AliTRDtrackingSector() :fSector(-1) ,fN(0) ,fGeom(0x0) { // Default constructor memset(fChamber, 0, AliTRDgeometry::kNdets*sizeof(AliTRDtrackingChamber*)); memset(fIndex, -1, AliTRDgeometry::kNdets*sizeof(Char_t)); memset(fX0, 0, AliTRDgeometry::kNlayer*sizeof(Float_t)); } //_____________________________________________________________________________ AliTRDtrackingSector::AliTRDtrackingSector(AliTRDgeometry *geo, Int_t gs) :fSector(gs) ,fN(0) ,fGeom(geo) { // // AliTRDtrackingSector Constructor // memset(fChamber, 0, AliTRDgeometry::kNdets*sizeof(AliTRDtrackingChamber*)); memset(fIndex, -1, AliTRDgeometry::kNdets*sizeof(Char_t)); memset(fX0, 0, AliTRDgeometry::kNlayer*sizeof(Float_t)); } //_____________________________________________________________________________ void AliTRDtrackingSector::Init(const AliTRDReconstructor *rec, const AliTRDCalDet *cal) { // Steer building of tracking chambers and build tracking sector. // Propagate radial position information (calibration/alignment aware) from chambers to sector level // AliTRDchamberTimeBin *tb = 0x0; AliTRDtrackingChamber **tc = &fChamber[0]; for(Int_t ic = 0; (ic<AliTRDgeometry::kNdets) && (*tc); ic++, tc++){ for(Int_t itb=0; itb<AliTRDseed::knTimebins; itb++){ if(!(tb = (*tc)->GetTB(itb))) continue; tb->SetReconstructor(rec); } (*tc)->Build(fGeom, cal, rec->IsHLT()); } Int_t nl; for(int il=0; il<AliTRDgeometry::kNlayer; il++){ fX0[il] = 0.; nl = 0; for(int is=0; is<AliTRDgeometry::kNstack; is++){ Int_t idx = is*AliTRDgeometry::kNlayer + il; if(fIndex[idx]<0) continue; fX0[il] += GetChamber(fIndex[idx])->GetX(); nl++; } if(!nl){ //printf("Could not estimate radial position of plane %d in sector %d.\n", ip, fSector); continue; } fX0[il] /= Float_t(nl); } } //_____________________________________________________________________________ void AliTRDtrackingSector::Clear(const Option_t *opt) { // Reset counters and steer chamber clear AliTRDtrackingChamber **tc = &fChamber[0]; for(Int_t ich=0; ich<fN; ich++, tc++){ (*tc)->Clear(opt); delete (*tc); (*tc) = 0x0; // I would avoid } memset(fIndex, -1, AliTRDgeometry::kNdets*sizeof(Char_t)); fN = 0; } //_____________________________________________________________________________ AliTRDtrackingChamber* AliTRDtrackingSector::GetChamber(Int_t stack, Int_t layer, Bool_t build) { // Return chamber at position (stack, plane) in current // sector or build a new one if it is not already created Int_t ch = stack*AliTRDgeometry::kNlayer + layer; if(fIndex[ch] >= 0) return fChamber[Int_t(fIndex[ch])]; else if(!build) return 0x0; // CHAMBER HAS TO BE BUILD Int_t rch = ch;do rch--; while(rch>=0 && fIndex[rch]<0); fIndex[ch] = rch >=0 ? fIndex[rch]+1 : 0; fN++; memmove(&fChamber[Int_t(fIndex[ch])+1], &fChamber[Int_t(fIndex[ch])], (AliTRDgeometry::kNdets-fIndex[ch]-1)*sizeof(void*)); for(Int_t ic = ch+1; ic<AliTRDgeometry::kNdets; ic++) fIndex[ic] += fIndex[ic] >= 0 ? 1 : 0; AliTRDtrackingChamber *chmb = fChamber[Int_t(fIndex[ch])] = new AliTRDtrackingChamber(); chmb->SetDetector(AliTRDgeometry::GetDetector(layer, stack, fSector)); return chmb; } //_____________________________________________________________________________ AliTRDtrackingChamber** AliTRDtrackingSector::GetStack(Int_t stack) { // Return chamber at position (stack, plane) in current // sector or build a new one if it is not already created if(stack<0 || stack>=AliTRDgeometry::kNstack) return 0x0; Int_t ich, n = 0; for(int il=0; il<AliTRDgeometry::kNlayer; il++){ ich = stack*AliTRDgeometry::kNlayer + il; if(fIndex[ich] < 0) fStack[il] = 0x0; else{ fStack[il] = fChamber[Int_t(fIndex[ich])]; n++; } } return n ? &fStack[0] : 0x0; } //_____________________________________________________________________________ void AliTRDtrackingSector::Print(Option_t *) { // Dump info about this tracking sector and the tracking chamber within // printf("\tSector %2d\n", fSector); for(int il=0; il<AliTRDgeometry::kNlayer; il++){ for(int is =0; is<AliTRDgeometry::kNstack; is++){ Int_t ch = is*AliTRDgeometry::kNlayer + il; printf("%2d[%2d] ", fIndex[ch], fIndex[ch]>=0 ? fChamber[Int_t(fIndex[ch])]->GetNClusters() : 0); } printf("\n"); } } <|endoftext|>
<commit_before> #include <gloperate-qtquick/viewer/QmlEngine.h> #include <QVariant> #include <QQmlContext> #include <QJSValueIterator> #include <cppexpose/reflection/Property.h> #include <cppassist/io/FilePath.h> #include <gloperate/gloperate.h> #include <gloperate/viewer/ViewerContext.h> #include <gloperate/scripting/ScriptEnvironment.h> #include <gloperate-qtquick/controls/TextController.h> #include <gloperate-qtquick/viewer/RenderItem.h> #include <gloperate-qtquick/viewer/QmlScriptFunction.h> namespace gloperate_qtquick { QmlEngine::QmlEngine(gloperate::ViewerContext * viewerContext) : m_viewerContext(viewerContext) { // Register QML types qmlRegisterType<RenderItem> ("gloperate.rendering", 1, 0, "RenderItem"); qmlRegisterType<TextController>("gloperate.ui", 1, 0, "TextController"); // Add gloperate qml-libraries std::string importPath = gloperate::dataPath() + "/gloperate/qml/GLOperate/Ui"; addImportPath(QString::fromStdString(importPath)); // Register global functions and properties rootContext()->setContextObject(this); // Create global objects m_global = newObject(); m_gloperate = newObject(); } QmlEngine::~QmlEngine() { } gloperate::ViewerContext * QmlEngine::viewerContext() const { return m_viewerContext; } QString QmlEngine::execute(const QString & code) { return QString::fromStdString( m_viewerContext->scriptEnvironment()->execute(code.toStdString()).value<std::string>() ); } cppexpose::Variant QmlEngine::fromScriptValue(const QJSValue & value) { if (value.isBool()) { return cppexpose::Variant(value.toBool()); } else if (value.isNumber()) { return cppexpose::Variant(value.toNumber()); } else if (value.isString()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isRegExp()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isError()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isDate()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isCallable()) { // [TODO] This produces a memory leak, since the pointer to the function object will never be deleted. // A solution would be to wrap a ref_ptr into the variant, but since there are also function objects // which are not memory-managed (e.g., a C-function that has been passed to the scripting engine), // it would be hard to determine the right use of function-variants. // The script context could of course manage a list of created functions an delete them on destruction, // but that would not solve the problem of "memory leak" while the program is running. QmlScriptFunction * function = new QmlScriptFunction(this, value); return cppexpose::Variant::fromValue<cppexpose::AbstractFunction *>(function); } else if (value.isArray()) { cppexpose::VariantArray array; QJSValueIterator it(value); while (it.next()) { if (it.hasNext()) // Skip last item (length) { array.push_back(fromScriptValue(it.value())); } } return array; } else if (value.isObject()) { cppexpose::VariantMap obj; QJSValueIterator it(value); while (it.next()) { obj[it.name().toStdString()] = fromScriptValue(it.value()); } return obj; } else { return cppexpose::Variant(); } } QJSValue QmlEngine::toScriptValue(const cppexpose::Variant & var) { if (var.hasType<char>()) { return QJSValue(var.value<char>()); } else if (var.hasType<unsigned char>()) { return QJSValue(var.value<unsigned char>()); } else if (var.hasType<short>()) { return QJSValue(var.value<short>()); } else if (var.hasType<unsigned short>()) { return QJSValue(var.value<unsigned short>()); } else if (var.hasType<int>()) { return QJSValue(var.value<int>()); } else if (var.hasType<unsigned int>()) { return QJSValue(var.value<unsigned int>()); } else if (var.hasType<long>()) { return QJSValue(var.value<int>()); } else if (var.hasType<unsigned long>()) { return QJSValue(var.value<unsigned int>()); } else if (var.hasType<long long>()) { return QJSValue(var.value<int>()); } else if (var.hasType<unsigned long long>()) { return QJSValue(var.value<unsigned int>()); } else if (var.hasType<float>()) { return QJSValue(var.value<float>()); } else if (var.hasType<double>()) { return QJSValue(var.value<double>()); } else if (var.hasType<char*>()) { return QJSValue(var.value<char*>()); } else if (var.hasType<std::string>()) { return QJSValue(var.value<std::string>().c_str()); } else if (var.hasType<bool>()) { return QJSValue(var.value<bool>()); } else if (var.hasType<cppassist::FilePath>()) { return QJSValue(var.value<cppassist::FilePath>().path().c_str()); } else if (var.hasType<cppexpose::VariantArray>()) { QJSValue array = newArray(); cppexpose::VariantArray variantArray = var.value<cppexpose::VariantArray>(); for (unsigned int i=0; i<variantArray.size(); i++) { array.setProperty(i, toScriptValue(variantArray.at(i))); } return array; } else if (var.hasType<cppexpose::VariantMap>()) { QJSValue obj = newObject(); cppexpose::VariantMap variantMap = var.value<cppexpose::VariantMap>(); for (const std::pair<std::string, cppexpose::Variant> & pair : variantMap) { obj.setProperty(pair.first.c_str(), toScriptValue(pair.second)); } return obj; } else { return QJSValue(); } } cppexpose::Variant QmlEngine::fromQVariant(const QVariant & value) { if (value.type() == QVariant::Bool) { return cppexpose::Variant(value.toBool()); } else if (value.type() == QVariant::Char || value.type() == QVariant::Int) { return cppexpose::Variant(value.toInt()); } else if (value.type() == QVariant::UInt) { return cppexpose::Variant(value.toUInt()); } else if (value.type() == QVariant::LongLong) { return cppexpose::Variant(value.toLongLong()); } else if (value.type() == QVariant::ULongLong) { return cppexpose::Variant(value.toULongLong()); } else if (value.type() == QVariant::Double) { return cppexpose::Variant(value.toDouble()); } else if (value.type() == QVariant::StringList) { cppexpose::VariantArray array; QStringList list = value.toStringList(); for (QStringList::iterator it = list.begin(); it != list.end(); ++it) { array.push_back( cppexpose::Variant((*it).toStdString()) ); } return array; } else if (value.type() == QVariant::List) { cppexpose::VariantArray array; QList<QVariant> list = value.toList(); for (QList<QVariant>::iterator it = list.begin(); it != list.end(); ++it) { array.push_back(fromQVariant(*it)); } return array; } else if (value.type() == QVariant::Map) { cppexpose::VariantMap obj; QMap<QString, QVariant> map = value.toMap(); for (QMap<QString, QVariant>::iterator it = map.begin(); it != map.end(); ++it) { std::string key = it.key().toStdString(); obj[key] = fromQVariant(it.value()); } return obj; } else if (value.type() == QVariant::String || value.canConvert(QVariant::String)) { return cppexpose::Variant(value.toString().toStdString()); } else { return cppexpose::Variant(); } } const QJSValue & QmlEngine::global() const { return m_global; } void QmlEngine::setGlobal(const QJSValue & obj) { m_global = obj; } const QJSValue & QmlEngine::gloperate() const { return m_gloperate; } void QmlEngine::setGloperate(const QJSValue & obj) { m_gloperate = obj; } } // namespace gloperate_qtquick <commit_msg>Add DirectValue.h include in QmlEngine.cpp.<commit_after> #include <gloperate-qtquick/viewer/QmlEngine.h> #include <QVariant> #include <QQmlContext> #include <QJSValueIterator> #include <cppexpose/reflection/Property.h> #include <cppexpose/typed/DirectValue.h> #include <cppassist/io/FilePath.h> #include <gloperate/gloperate.h> #include <gloperate/viewer/ViewerContext.h> #include <gloperate/scripting/ScriptEnvironment.h> #include <gloperate-qtquick/controls/TextController.h> #include <gloperate-qtquick/viewer/RenderItem.h> #include <gloperate-qtquick/viewer/QmlScriptFunction.h> namespace gloperate_qtquick { QmlEngine::QmlEngine(gloperate::ViewerContext * viewerContext) : m_viewerContext(viewerContext) { // Register QML types qmlRegisterType<RenderItem> ("gloperate.rendering", 1, 0, "RenderItem"); qmlRegisterType<TextController>("gloperate.ui", 1, 0, "TextController"); // Add gloperate qml-libraries std::string importPath = gloperate::dataPath() + "/gloperate/qml/GLOperate/Ui"; addImportPath(QString::fromStdString(importPath)); // Register global functions and properties rootContext()->setContextObject(this); // Create global objects m_global = newObject(); m_gloperate = newObject(); } QmlEngine::~QmlEngine() { } gloperate::ViewerContext * QmlEngine::viewerContext() const { return m_viewerContext; } QString QmlEngine::execute(const QString & code) { return QString::fromStdString( m_viewerContext->scriptEnvironment()->execute(code.toStdString()).value<std::string>() ); } cppexpose::Variant QmlEngine::fromScriptValue(const QJSValue & value) { if (value.isBool()) { return cppexpose::Variant(value.toBool()); } else if (value.isNumber()) { return cppexpose::Variant(value.toNumber()); } else if (value.isString()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isRegExp()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isError()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isDate()) { return cppexpose::Variant(value.toString().toStdString()); } else if (value.isCallable()) { // [TODO] This produces a memory leak, since the pointer to the function object will never be deleted. // A solution would be to wrap a ref_ptr into the variant, but since there are also function objects // which are not memory-managed (e.g., a C-function that has been passed to the scripting engine), // it would be hard to determine the right use of function-variants. // The script context could of course manage a list of created functions an delete them on destruction, // but that would not solve the problem of "memory leak" while the program is running. QmlScriptFunction * function = new QmlScriptFunction(this, value); return cppexpose::Variant::fromValue<cppexpose::AbstractFunction *>(function); } else if (value.isArray()) { cppexpose::VariantArray array; QJSValueIterator it(value); while (it.next()) { if (it.hasNext()) // Skip last item (length) { array.push_back(fromScriptValue(it.value())); } } return array; } else if (value.isObject()) { cppexpose::VariantMap obj; QJSValueIterator it(value); while (it.next()) { obj[it.name().toStdString()] = fromScriptValue(it.value()); } return obj; } else { return cppexpose::Variant(); } } QJSValue QmlEngine::toScriptValue(const cppexpose::Variant & var) { if (var.hasType<char>()) { return QJSValue(var.value<char>()); } else if (var.hasType<unsigned char>()) { return QJSValue(var.value<unsigned char>()); } else if (var.hasType<short>()) { return QJSValue(var.value<short>()); } else if (var.hasType<unsigned short>()) { return QJSValue(var.value<unsigned short>()); } else if (var.hasType<int>()) { return QJSValue(var.value<int>()); } else if (var.hasType<unsigned int>()) { return QJSValue(var.value<unsigned int>()); } else if (var.hasType<long>()) { return QJSValue(var.value<int>()); } else if (var.hasType<unsigned long>()) { return QJSValue(var.value<unsigned int>()); } else if (var.hasType<long long>()) { return QJSValue(var.value<int>()); } else if (var.hasType<unsigned long long>()) { return QJSValue(var.value<unsigned int>()); } else if (var.hasType<float>()) { return QJSValue(var.value<float>()); } else if (var.hasType<double>()) { return QJSValue(var.value<double>()); } else if (var.hasType<char*>()) { return QJSValue(var.value<char*>()); } else if (var.hasType<std::string>()) { return QJSValue(var.value<std::string>().c_str()); } else if (var.hasType<bool>()) { return QJSValue(var.value<bool>()); } else if (var.hasType<cppassist::FilePath>()) { return QJSValue(var.value<cppassist::FilePath>().path().c_str()); } else if (var.hasType<cppexpose::VariantArray>()) { QJSValue array = newArray(); cppexpose::VariantArray variantArray = var.value<cppexpose::VariantArray>(); for (unsigned int i=0; i<variantArray.size(); i++) { array.setProperty(i, toScriptValue(variantArray.at(i))); } return array; } else if (var.hasType<cppexpose::VariantMap>()) { QJSValue obj = newObject(); cppexpose::VariantMap variantMap = var.value<cppexpose::VariantMap>(); for (const std::pair<std::string, cppexpose::Variant> & pair : variantMap) { obj.setProperty(pair.first.c_str(), toScriptValue(pair.second)); } return obj; } else { return QJSValue(); } } cppexpose::Variant QmlEngine::fromQVariant(const QVariant & value) { if (value.type() == QVariant::Bool) { return cppexpose::Variant(value.toBool()); } else if (value.type() == QVariant::Char || value.type() == QVariant::Int) { return cppexpose::Variant(value.toInt()); } else if (value.type() == QVariant::UInt) { return cppexpose::Variant(value.toUInt()); } else if (value.type() == QVariant::LongLong) { return cppexpose::Variant(value.toLongLong()); } else if (value.type() == QVariant::ULongLong) { return cppexpose::Variant(value.toULongLong()); } else if (value.type() == QVariant::Double) { return cppexpose::Variant(value.toDouble()); } else if (value.type() == QVariant::StringList) { cppexpose::VariantArray array; QStringList list = value.toStringList(); for (QStringList::iterator it = list.begin(); it != list.end(); ++it) { array.push_back( cppexpose::Variant((*it).toStdString()) ); } return array; } else if (value.type() == QVariant::List) { cppexpose::VariantArray array; QList<QVariant> list = value.toList(); for (QList<QVariant>::iterator it = list.begin(); it != list.end(); ++it) { array.push_back(fromQVariant(*it)); } return array; } else if (value.type() == QVariant::Map) { cppexpose::VariantMap obj; QMap<QString, QVariant> map = value.toMap(); for (QMap<QString, QVariant>::iterator it = map.begin(); it != map.end(); ++it) { std::string key = it.key().toStdString(); obj[key] = fromQVariant(it.value()); } return obj; } else if (value.type() == QVariant::String || value.canConvert(QVariant::String)) { return cppexpose::Variant(value.toString().toStdString()); } else { return cppexpose::Variant(); } } const QJSValue & QmlEngine::global() const { return m_global; } void QmlEngine::setGlobal(const QJSValue & obj) { m_global = obj; } const QJSValue & QmlEngine::gloperate() const { return m_gloperate; } void QmlEngine::setGloperate(const QJSValue & obj) { m_gloperate = obj; } } // namespace gloperate_qtquick <|endoftext|>
<commit_before>/// \file uparser.cc //#define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include <cstdlib> #include <cassert> #include <sstream> #include <strstream> #include <fstream> #include <algorithm> #include <string> #include "uparser.hh" /*----------. | UParser. | `----------*/ UParser::UParser(UConnection& cn) : command_tree_ (0), binaryCommand (false), connection (cn), hasError_(false), error_ (), hasWarning_(false), warning_ (), scanner_ (), loc_() { // The first column for locations is 1. loc_.begin.column = loc_.end.column = 1; } int UParser::parse_ () { command_tree_ = 0; binaryCommand = false; hasError_ = false; hasWarning_ = false; parser_type p(*this); #ifdef ENABLE_DEBUG_TRACES p.set_debug_level(true); #else p.set_debug_level (!!getenv ("YYDEBUG")); #endif ECHO("====================== Parse begin"); int res = p.parse(); ECHO("====================== Parse end: " << res); return res; } int UParser::process (const std::string& command) { // It has been said Flex scanners cannot work with istrstream. std::istrstream mem_buff (command.c_str ()); std::istream mem_input (mem_buff.rdbuf()); scanner_.switch_streams(&mem_input, 0); ECHO("Parsing string: ==================\n" << loc_ << ":\n" << command << "\n=================================="); return parse_ (); } ast::Ast* UParser::command_tree_get () { if (hasError ()) return 0; return command_tree_; } const ast::Ast* UParser::command_tree_get () const { if (hasError ()) return 0; return command_tree_; } void UParser::command_tree_set (ast::Ast* ast) { command_tree_ = ast; } int UParser::process_file (const std::string& fn) { // A location pointing to it. location_type loc; loc.initialize (new libport::Symbol(fn)); // The convention for the first column changed: make sure the first // column is column 1. loc.begin.column = loc.end.column = 1; // Exchange with the current location so that we can restore it // afterwards (when reading the input flow, we want to be able to // restore the cursor after having handled a load command). std::swap(loc, loc_); std::ifstream f (fn.c_str()); scanner_.switch_streams(&f, 0); ECHO("Parsing file: " << fn); int res = parse_(); std::swap(loc, loc_); return res; } namespace { /// Helper to format error and warning messages. std::string errorFormat(const yy::parser::location_type& l, const std::string& msg) { std::ostringstream o; o << "!!! " << l << ": " << msg << '\n' << std::ends; return o.str(); } } void UParser::error (const yy::parser::location_type& l, const std::string& msg) { hasError_ = true; error_ = errorFormat(l, msg); } void UParser::warn (const yy::parser::location_type& l, const std::string& msg) { hasWarning_ = true; warning_ = errorFormat(l, msg); } bool UParser::hasError () const { return hasError_; } std::string UParser::error_get () const { // precondition assert(hasError()); return error_; } bool UParser::hasWarning () const { return hasWarning_; } std::string UParser::warning_get () const { // precondition assert(hasWarning()); return warning_; } <commit_msg>Space changes.<commit_after>/// \file uparser.cc //#define ENABLE_DEBUG_TRACES #include "libport/compiler.hh" #include <cstdlib> #include <cassert> #include <sstream> #include <strstream> #include <fstream> #include <algorithm> #include <string> #include "uparser.hh" /*----------. | UParser. | `----------*/ UParser::UParser(UConnection& cn) : command_tree_ (0), binaryCommand (false), connection (cn), hasError_(false), error_ (), hasWarning_(false), warning_ (), scanner_ (), loc_() { // The first column for locations is 1. loc_.begin.column = loc_.end.column = 1; } int UParser::parse_ () { command_tree_ = 0; binaryCommand = false; hasError_ = false; hasWarning_ = false; parser_type p(*this); #ifdef ENABLE_DEBUG_TRACES p.set_debug_level(true); #else p.set_debug_level (!!getenv ("YYDEBUG")); #endif ECHO("====================== Parse begin"); int res = p.parse(); ECHO("====================== Parse end: " << res); return res; } int UParser::process (const std::string& command) { // It has been said Flex scanners cannot work with istrstream. std::istrstream mem_buff (command.c_str ()); std::istream mem_input (mem_buff.rdbuf()); scanner_.switch_streams(&mem_input, 0); ECHO("Parsing string: ==================\n" << loc_ << ":\n" << command << "\n=================================="); return parse_ (); } ast::Ast* UParser::command_tree_get () { if (hasError ()) return 0; return command_tree_; } const ast::Ast* UParser::command_tree_get () const { if (hasError ()) return 0; return command_tree_; } void UParser::command_tree_set (ast::Ast* ast) { command_tree_ = ast; } int UParser::process_file (const std::string& fn) { // A location pointing to it. location_type loc; loc.initialize (new libport::Symbol(fn)); // The convention for the first column changed: make sure the first // column is column 1. loc.begin.column = loc.end.column = 1; // Exchange with the current location so that we can restore it // afterwards (when reading the input flow, we want to be able to // restore the cursor after having handled a load command). std::swap(loc, loc_); std::ifstream f (fn.c_str()); scanner_.switch_streams(&f, 0); ECHO("Parsing file: " << fn); int res = parse_(); std::swap(loc, loc_); return res; } namespace { /// Helper to format error and warning messages. std::string errorFormat(const yy::parser::location_type& l, const std::string& msg) { std::ostringstream o; o << "!!! " << l << ": " << msg << '\n' << std::ends; return o.str(); } } void UParser::error (const yy::parser::location_type& l, const std::string& msg) { hasError_ = true; error_ = errorFormat(l, msg); } void UParser::warn (const yy::parser::location_type& l, const std::string& msg) { hasWarning_ = true; warning_ = errorFormat(l, msg); } bool UParser::hasError () const { return hasError_; } std::string UParser::error_get () const { // precondition assert(hasError()); return error_; } bool UParser::hasWarning () const { return hasWarning_; } std::string UParser::warning_get () const { // precondition assert(hasWarning()); return warning_; } <|endoftext|>
<commit_before>#include "SubDocPropValueRenderer.h" #include <rapidjson/document.h> #include <glog/logging.h> namespace sf1r { void SubDocPropValueRenderer::renderSubDocPropValue( const std::string& propName, const std::string& origText, izenelib::driver::Value& resourceValue) { if (origText.empty()) return; rapidjson::Document doc; if (doc.Parse<0>(origText.c_str()).HasParseError()); { return; } const rapidjson::Value& subDocs = doc; assert(subDocs.IsArray()); for (rapidjson::Value::ConstValueIterator vit = subDocs.Begin(); vit != subDocs.End(); vit++) { izenelib::driver::Value& subDoc = resourceValue(); for (rapidjson::Value::ConstMemberIterator mit = vit->MemberBegin(); mit != vit->MemberEnd(); mit++) { subDoc[mit->name.GetString()]=mit->value.GetString(); } } } } <commit_msg>rapidjson always have json parse error given subdoc property using JsonReader instead<commit_after>#include "SubDocPropValueRenderer.h" #include <rapidjson/document.h> #include <glog/logging.h> #include <util/driver/readers/JsonReader.h> namespace sf1r { void SubDocPropValueRenderer::renderSubDocPropValue( const std::string& propName, const std::string& origText, izenelib::driver::Value& resourceValue) { if (origText.empty()) return; izenelib::driver::JsonReader reader; reader.read(origText, resourceValue); /* rapidjson::Document doc; if (doc.Parse<0>(origText.c_str()).HasParseError()) { //return; } const rapidjson::Value& subDocs = doc; assert(subDocs.IsArray()); for (rapidjson::Value::ConstValueIterator vit = subDocs.Begin(); vit != subDocs.End(); vit++) { izenelib::driver::Value& subDoc = resourceValue(); for (rapidjson::Value::ConstMemberIterator mit = vit->MemberBegin(); mit != vit->MemberEnd(); mit++) { subDoc[mit->name.GetString()]=mit->value.GetString(); } }*/ } } <|endoftext|>
<commit_before><commit_msg>Fix pool allocator memory persistence across allocs<commit_after><|endoftext|>
<commit_before>// // Copyright (c) 2012 Kim Walisch, <[email protected]>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "EratMedium.h" #include "SieveOfEratosthenes.h" #include "SieveOfEratosthenes-inline.h" #include "WheelFactorization.h" #include "config.h" #include <stdint.h> #include <stdexcept> #include <algorithm> #include <list> namespace soe { EratMedium::EratMedium(const SieveOfEratosthenes& soe) : Modulo210Wheel_t(soe), buckets_(1, Bucket()) { // assert multipleIndex < 2^23 in crossOff() static_assert(config::FACTOR_ERATMEDIUM <= 6, "config::FACTOR_ERATMEDIUM must not be > 6"); if (soe.getSieveSize() > (1u << 22)) throw std::overflow_error("EratMedium: sieveSize must be <= 2^22, 4096 kilobytes."); uint_t sqrtStop = soe.getSqrtStop(); uint_t max = soe.getSieveSize() * config::FACTOR_ERATMEDIUM; limit_ = std::min(sqrtStop, max); } /// Add a new sieving prime /// @see addSievingPrime() in WheelFactorization.h /// void EratMedium::storeSievingPrime(uint_t prime, uint_t multipleIndex, uint_t wheelIndex) { if (!buckets_.back().store(prime, multipleIndex, wheelIndex)) buckets_.push_back(Bucket()); } /// This is an implementation of the segmented sieve of Eratosthenes /// with wheel factorization optimized for medium sieving primes that /// have a few multiples per segment. EratMedium uses a modulo 210 /// wheel that skips multiples of 2, 3, 5 and 7. /// @see crossOffMultiples() in SieveOfEratosthenes.cpp /// void EratMedium::crossOff(uint8_t* sieve, uint_t sieveSize) { for (BucketList_t::iterator bucket = buckets_.begin(); bucket != buckets_.end(); ++bucket) { WheelPrime* wPrime = bucket->begin(); WheelPrime* end = bucket->end(); // 2 sieving primes are processed per loop iteration to break the // dependency chain and reduce pipeline stalls for (; wPrime + 2 <= end; wPrime += 2) { uint_t multipleIndex0 = wPrime[0].getMultipleIndex(); uint_t wheelIndex0 = wPrime[0].getWheelIndex(); uint_t sievingPrime0 = wPrime[0].getSievingPrime(); uint_t multipleIndex1 = wPrime[1].getMultipleIndex(); uint_t wheelIndex1 = wPrime[1].getWheelIndex(); uint_t sievingPrime1 = wPrime[1].getSievingPrime(); // cross-off the multiples (unset bits) of sievingPrime(0|1) // @see unsetBit() in WheelFactorization.h for (;;) { if (multipleIndex0 < sieveSize) unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0); else break; if (multipleIndex1 < sieveSize) unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1); else break; } while (multipleIndex0 < sieveSize) unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0); while (multipleIndex1 < sieveSize) unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1); multipleIndex0 -= sieveSize; multipleIndex1 -= sieveSize; wPrime[0].set(multipleIndex0, wheelIndex0); wPrime[1].set(multipleIndex1, wheelIndex1); } if (wPrime != end) { uint_t multipleIndex = wPrime->getMultipleIndex(); uint_t wheelIndex = wPrime->getWheelIndex(); uint_t sievingPrime = wPrime->getSievingPrime(); while (multipleIndex < sieveSize) unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex); multipleIndex -= sieveSize; wPrime->set(multipleIndex, wheelIndex); } } } } // namespace soe <commit_msg>improved code readability<commit_after>// // Copyright (c) 2012 Kim Walisch, <[email protected]>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "EratMedium.h" #include "SieveOfEratosthenes.h" #include "SieveOfEratosthenes-inline.h" #include "WheelFactorization.h" #include "config.h" #include <stdint.h> #include <stdexcept> #include <algorithm> #include <list> namespace soe { EratMedium::EratMedium(const SieveOfEratosthenes& soe) : Modulo210Wheel_t(soe), buckets_(1, Bucket()) { // assert multipleIndex < 2^23 in crossOff() static_assert(config::FACTOR_ERATMEDIUM <= 6, "config::FACTOR_ERATMEDIUM must not be > 6"); if (soe.getSieveSize() > (1u << 22)) throw std::overflow_error("EratMedium: sieveSize must be <= 2^22, 4096 kilobytes."); uint_t max = soe.getSieveSize() * config::FACTOR_ERATMEDIUM; limit_ = std::min(soe.getSqrtStop(), max); } /// Add a new sieving prime /// @see addSievingPrime() in WheelFactorization.h /// void EratMedium::storeSievingPrime(uint_t prime, uint_t multipleIndex, uint_t wheelIndex) { if (!buckets_.back().store(prime, multipleIndex, wheelIndex)) buckets_.push_back(Bucket()); } /// This is an implementation of the segmented sieve of Eratosthenes /// with wheel factorization optimized for medium sieving primes that /// have a few multiples per segment. EratMedium uses a modulo 210 /// wheel that skips multiples of 2, 3, 5 and 7. /// @see crossOffMultiples() in SieveOfEratosthenes.cpp /// void EratMedium::crossOff(uint8_t* sieve, uint_t sieveSize) { for (BucketList_t::iterator bucket = buckets_.begin(); bucket != buckets_.end(); ++bucket) { WheelPrime* wPrime = bucket->begin(); WheelPrime* end = bucket->end(); // 2 sieving primes are processed per loop iteration to break the // dependency chain and reduce pipeline stalls for (; wPrime + 2 <= end; wPrime += 2) { uint_t multipleIndex0 = wPrime[0].getMultipleIndex(); uint_t wheelIndex0 = wPrime[0].getWheelIndex(); uint_t sievingPrime0 = wPrime[0].getSievingPrime(); uint_t multipleIndex1 = wPrime[1].getMultipleIndex(); uint_t wheelIndex1 = wPrime[1].getWheelIndex(); uint_t sievingPrime1 = wPrime[1].getSievingPrime(); // cross-off the multiples (unset bits) of sievingPrime(0|1) // @see unsetBit() in WheelFactorization.h for (;;) { if (multipleIndex0 < sieveSize) unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0); else break; if (multipleIndex1 < sieveSize) unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1); else break; } while (multipleIndex0 < sieveSize) unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0); while (multipleIndex1 < sieveSize) unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1); multipleIndex0 -= sieveSize; multipleIndex1 -= sieveSize; wPrime[0].set(multipleIndex0, wheelIndex0); wPrime[1].set(multipleIndex1, wheelIndex1); } if (wPrime != end) { uint_t multipleIndex = wPrime->getMultipleIndex(); uint_t wheelIndex = wPrime->getWheelIndex(); uint_t sievingPrime = wPrime->getSievingPrime(); while (multipleIndex < sieveSize) unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex); multipleIndex -= sieveSize; wPrime->set(multipleIndex, wheelIndex); } } } } // namespace soe <|endoftext|>
<commit_before>#include "plugin/Plugin.hpp" #include "plugin/Model.hpp" namespace rack { namespace plugin { Plugin::~Plugin() { for (Model *model : models) { delete model; } } void Plugin::addModel(Model *model) { assert(!model->plugin); model->plugin = this; models.push_back(model); } Model *Plugin::getModel(std::string slug) { for (Model *model : models) { if (model->slug == slug) { return model; } } return NULL; } void Plugin::fromJson(json_t *rootJ) { json_t *slugJ = json_object_get(rootJ, "slug"); if (slugJ) slug = json_string_value(slugJ); json_t *versionJ = json_object_get(rootJ, "version"); if (versionJ) version = json_string_value(versionJ); json_t *nameJ = json_object_get(rootJ, "name"); if (nameJ) name = json_string_value(nameJ); json_t *authorJ = json_object_get(rootJ, "author"); if (authorJ) author = json_string_value(authorJ); json_t *licenseJ = json_object_get(rootJ, "license"); if (licenseJ) license = json_string_value(licenseJ); json_t *authorEmailJ = json_object_get(rootJ, "authorEmail"); if (authorEmailJ) authorEmail = json_string_value(authorEmailJ); json_t *pluginUrlJ = json_object_get(rootJ, "pluginUrl"); if (pluginUrlJ) pluginUrl = json_string_value(pluginUrlJ); json_t *authorUrlJ = json_object_get(rootJ, "authorUrl"); if (authorUrlJ) authorUrl = json_string_value(authorUrlJ); json_t *manualUrlJ = json_object_get(rootJ, "manualUrl"); if (manualUrlJ) manualUrl = json_string_value(manualUrlJ); json_t *sourceUrlJ = json_object_get(rootJ, "sourceUrl"); if (sourceUrlJ) sourceUrl = json_string_value(sourceUrlJ); json_t *donateUrlJ = json_object_get(rootJ, "donateUrl"); if (donateUrlJ) donateUrl = json_string_value(donateUrlJ); json_t *modulesJ = json_object_get(rootJ, "modules"); if (modulesJ) { const char *slug; json_t *moduleJ; json_object_foreach(modulesJ, slug, moduleJ) { Model *model = getModel(slug); if (!model) { WARN("plugin.json contains module \"%s\" but it is not defined in the plugin", slug); continue; } model->fromJson(moduleJ); } } } } // namespace plugin } // namespace rack <commit_msg>Make module property in manifest an array instead of object<commit_after>#include "plugin/Plugin.hpp" #include "plugin/Model.hpp" namespace rack { namespace plugin { Plugin::~Plugin() { for (Model *model : models) { delete model; } } void Plugin::addModel(Model *model) { assert(!model->plugin); model->plugin = this; models.push_back(model); } Model *Plugin::getModel(std::string slug) { for (Model *model : models) { if (model->slug == slug) { return model; } } return NULL; } void Plugin::fromJson(json_t *rootJ) { json_t *slugJ = json_object_get(rootJ, "slug"); if (slugJ) slug = json_string_value(slugJ); json_t *versionJ = json_object_get(rootJ, "version"); if (versionJ) version = json_string_value(versionJ); json_t *nameJ = json_object_get(rootJ, "name"); if (nameJ) name = json_string_value(nameJ); json_t *authorJ = json_object_get(rootJ, "author"); if (authorJ) author = json_string_value(authorJ); json_t *licenseJ = json_object_get(rootJ, "license"); if (licenseJ) license = json_string_value(licenseJ); json_t *authorEmailJ = json_object_get(rootJ, "authorEmail"); if (authorEmailJ) authorEmail = json_string_value(authorEmailJ); json_t *pluginUrlJ = json_object_get(rootJ, "pluginUrl"); if (pluginUrlJ) pluginUrl = json_string_value(pluginUrlJ); json_t *authorUrlJ = json_object_get(rootJ, "authorUrl"); if (authorUrlJ) authorUrl = json_string_value(authorUrlJ); json_t *manualUrlJ = json_object_get(rootJ, "manualUrl"); if (manualUrlJ) manualUrl = json_string_value(manualUrlJ); json_t *sourceUrlJ = json_object_get(rootJ, "sourceUrl"); if (sourceUrlJ) sourceUrl = json_string_value(sourceUrlJ); json_t *donateUrlJ = json_object_get(rootJ, "donateUrl"); if (donateUrlJ) donateUrl = json_string_value(donateUrlJ); json_t *modulesJ = json_object_get(rootJ, "modules"); if (modulesJ) { size_t moduleId; json_t *moduleJ; json_array_foreach(modulesJ, moduleId, moduleJ) { json_t *slugJ = json_object_get(rootJ, "slug"); if (!slugJ) continue; std::string slug = json_string_value(slugJ); Model *model = getModel(slug); if (!model) { WARN("plugin.json contains module \"%s\" but it is not defined in the plugin", slug); continue; } model->fromJson(moduleJ); } } } } // namespace plugin } // namespace rack <|endoftext|>
<commit_before>#include "dreal/solver/context.h" #include <cmath> #include <ostream> #include <set> #include <sstream> #include <unordered_set> #include "dreal/solver/assertion_filter.h" #include "dreal/solver/sat_solver.h" #include "dreal/solver/theory_solver.h" #include "dreal/util/cnfizer.h" #include "dreal/util/exception.h" #include "dreal/util/logging.h" #include "dreal/util/predicate_abstractor.h" #include "dreal/util/scoped_vector.h" using std::experimental::optional; using std::isfinite; using std::move; using std::ostringstream; using std::set; using std::stod; using std::string; using std::unordered_set; using std::vector; namespace dreal { // The actual implementation. class Context::Impl { public: Impl(); explicit Impl(Config config); void Assert(const Formula& f); std::experimental::optional<Box> CheckSat(); void DeclareVariable(const Variable& v); void DeclareVariable(const Variable& v, const Expression& lb, const Expression& ub); void Minimize(const Expression& f); void Pop(); void Push(); void SetInfo(const std::string& key, const std::string& val); void SetInterval(const Variable& v, double lb, double ub); void SetLogic(const Logic& logic); void SetOption(const std::string& key, const std::string& val); const Variable& lookup_variable(const std::string& name); const Config& config() const { return config_; } Config& mutable_config() { return config_; } private: Box& box() { return boxes_.last(); } Config config_; std::experimental::optional<Logic> logic_{}; std::unordered_map<std::string, Variable> name_to_var_map_; std::unordered_map<std::string, std::string> info_; std::unordered_map<std::string, std::string> option_; ScopedVector<Box> boxes_; ScopedVector<Formula> stack_; PredicateAbstractor predicate_abstractor_; Cnfizer cnfizer_; SatSolver sat_solver_; }; Context::Impl::Impl() : sat_solver_{&cnfizer_, &predicate_abstractor_} { boxes_.push_back(Box{}); } Context::Impl::Impl(Config config) : config_{move(config)}, sat_solver_{&cnfizer_, &predicate_abstractor_} { boxes_.push_back(Box{}); } void Context::Impl::Assert(const Formula& f) { if (FilterAssertion(f, &box())) { DREAL_LOG_DEBUG("Context::Assert: {} is not added.", f); DREAL_LOG_DEBUG("Box=\n{}", box()); return; } // Predicate abstract & CNFize. const vector<Formula> clauses{ cnfizer_.Convert(predicate_abstractor_.Convert(f))}; for (const Formula& f_i : clauses) { DREAL_LOG_DEBUG("Context::Assert: {} is added.", f_i); stack_.push_back(f_i); } } optional<Box> Context::Impl::CheckSat() { DREAL_LOG_DEBUG("Context::CheckSat()"); DREAL_LOG_TRACE("Context::CheckSat: Box =\n{}", box()); if (box().empty()) { return {}; } // If false ∈ stack_, it's UNSAT. for (const auto& f : stack_.get_vector()) { if (is_false(f)) { return {}; } } // If {} = stack_ ∨ {true} = stack_, it's trivially SAT. if (stack_.empty() || (stack_.size() == 1 && is_true(stack_.first()))) { return box(); } sat_solver_.AddClauses(stack_.get_vector()); TheorySolver theory_solver{config_, box()}; while (true) { if (sat_solver_.CheckSat()) { // SAT from SATSolver. DREAL_LOG_DEBUG("Context::CheckSat() - Sat Check = SAT"); if (theory_solver.CheckSat(sat_solver_.model())) { // SAT from TheorySolver. DREAL_LOG_DEBUG("Context::CheckSat() - Theroy Check = delta-SAT"); const Box model{theory_solver.GetModel()}; return model; } else { // UNSAT from TheorySolver. DREAL_LOG_DEBUG("Context::CheckSat() - Theroy Check = UNSAT"); const unordered_set<Formula, hash_value<Formula>> explanation{ theory_solver.GetExplanation()}; if (explanation.empty()) { return {}; } else { DREAL_LOG_DEBUG( "Context::CheckSat() - size of explanation = {} - stack " "size = {}", explanation.size(), stack_.get_vector().size()); sat_solver_.AddLearnedClause(explanation); } } } else { // UNSAT from SATSolver. Escape the loop. DREAL_LOG_DEBUG("Context::CheckSat() - Sat Check = UNSAT"); return {}; } } } void Context::Impl::DeclareVariable(const Variable& v) { DREAL_LOG_DEBUG("Context::DeclareVariable({})", v); name_to_var_map_.emplace(v.get_name(), v); box().Add(v); } void Context::Impl::DeclareVariable(const Variable& v, const Expression& lb, const Expression& ub) { DeclareVariable(v); SetInterval(v, lb.Evaluate(), ub.Evaluate()); } void Context::Impl::Minimize(const Expression& f) { DREAL_LOG_DEBUG("Context::Minimize: {} is called.", f); // Given e = f(x) and the current constraints ϕᵢ which // involves x. it constructs a universally quantified formula ψ: // // ψ = ∀y. (⋀ⱼ ϕᵢ(y)) → f(x) ≤ f(y). // // To construct ϕᵢ(y), we need to traverse both `box()` and // `stack_` because some of the asserted formulas are translated // and applied into `box()`. set<Formula> phi_set; ExpressionSubstitution subst; // Maps xᵢ ↦ yᵢ to build f(y₁, ..., yₙ). Variables quantified_variables; // {y₁, ... yₙ} const Variables x_vars{f.GetVariables()}; for (const Variable& x_i : x_vars) { // We add postfix '_' to name y_i const Variable y_i{x_i.get_name() + "_", x_i.get_type()}; quantified_variables.insert(y_i); subst.emplace(x_i, y_i); // If `box()[x_i]` has a finite bound, let's add that information in phi_set // as a constraint on y_i. const Box::Interval& bound_on_x_i{box()[x_i]}; const double lb_x_i{bound_on_x_i.lb()}; const double ub_x_i{bound_on_x_i.ub()}; if (isfinite(lb_x_i)) { phi_set.insert(lb_x_i <= y_i); } if (isfinite(ub_x_i)) { phi_set.insert(y_i <= ub_x_i); } } for (const Formula& constraint : stack_) { if (!intersect(x_vars, constraint.GetFreeVariables()).empty()) { // Case : xᵢ ∈ vars(constraint) // We need to collect constraint[xᵢ ↦ yᵢ]. phi_set.insert(constraint.Substitute(subst)); } } const Formula phi{make_conjunction(phi_set)}; // ⋀ⱼ ϕ(y) const Formula psi{ forall(quantified_variables, imply(phi, f <= f.Substitute(subst)))}; return Assert(psi); } void Context::Impl::Pop() { DREAL_LOG_DEBUG("Context::Pop()"); stack_.pop(); boxes_.pop(); sat_solver_.Pop(); // TODO(soonho): Pop cnfizer/predicate_abstractor_. } void Context::Impl::Push() { DREAL_LOG_DEBUG("Context::Push()"); sat_solver_.Push(); boxes_.push(); boxes_.push_back(boxes_.last()); stack_.push(); // TODO(soonho): Push cnfizer/predicate_abstractor_. } void Context::Impl::SetInfo(const string& key, const string& val) { DREAL_LOG_DEBUG("Context::SetInfo({} ↦ {})", key, val); info_[key] = val; if (key == ":precision") { config_.mutable_precision().set_from_file(stod(val)); } } void Context::Impl::SetInterval(const Variable& v, const double lb, const double ub) { DREAL_LOG_DEBUG("Context::SetInterval({} = [{}, {}])", v, lb, ub); box()[v] = Box::Interval{lb, ub}; } void Context::Impl::SetLogic(const Logic& logic) { DREAL_LOG_DEBUG("Context::SetLogic({})", logic); logic_ = logic; } void Context::Impl::SetOption(const string& key, const string& val) { DREAL_LOG_DEBUG("Context::SetOption({} ↦ {})", key, val); option_[key] = val; if (key == ":polytope") { if (val == "true") { config_.mutable_use_polytope().set_from_file(true); } else if (val == "false") { config_.mutable_use_polytope().set_from_file(false); } else { throw DREAL_RUNTIME_ERROR("Fail to interpret the option: " + key + " = " + val); } } if (key == ":forall-polytope") { if (val == "true") { config_.mutable_use_polytope_in_forall().set_from_file(true); } else if (val == "false") { config_.mutable_use_polytope_in_forall().set_from_file(false); } else { throw DREAL_RUNTIME_ERROR("Fail to interpret the option: " + key + " = " + val); } } } const Variable& Context::Impl::lookup_variable(const string& name) { const auto it = name_to_var_map_.find(name); if (it == name_to_var_map_.cend()) { throw DREAL_RUNTIME_ERROR(name + " is not found in the context."); } return it->second; } Context::Context() : impl_{new Impl{}} {} Context::Context(Config config) : impl_{new Impl{move(config)}} {} void Context::Assert(const Formula& f) { impl_->Assert(f); } optional<Box> Context::CheckSat() { return impl_->CheckSat(); } void Context::DeclareVariable(const Variable& v) { impl_->DeclareVariable(v); } void Context::DeclareVariable(const Variable& v, const Expression& lb, const Expression& ub) { impl_->DeclareVariable(v, lb, ub); } void Context::Exit() { DREAL_LOG_DEBUG("Context::Exit()"); } void Context::Minimize(const Expression& f) { impl_->Minimize(f); } void Context::Maximize(const Expression& f) { impl_->Minimize(-f); } void Context::Pop(int n) { DREAL_LOG_DEBUG("Context::Pop({})", n); if (n <= 0) { ostringstream oss; oss << "Context::Pop(n) called with n = " << n << " which is not positive."; throw DREAL_RUNTIME_ERROR(oss.str()); } while (n-- > 0) { impl_->Pop(); } } void Context::Push(int n) { DREAL_LOG_DEBUG("Context::Push({})", n); if (n <= 0) { ostringstream oss; oss << "Context::Push(n) called with n = " << n << " which is not positive."; throw DREAL_RUNTIME_ERROR(oss.str()); } while (n-- > 0) { impl_->Push(); } } void Context::SetInfo(const string& key, const string& val) { impl_->SetInfo(key, val); } void Context::SetInterval(const Variable& v, const double lb, const double ub) { impl_->SetInterval(v, lb, ub); } void Context::SetLogic(const Logic& logic) { impl_->SetLogic(logic); } void Context::SetOption(const string& key, const string& val) { impl_->SetOption(key, val); } const Variable& Context::lookup_variable(const string& name) { return impl_->lookup_variable(name); } const Config& Context::config() const { return impl_->config(); } Config& Context::mutable_config() { return impl_->mutable_config(); } string Context::version() { return DREAL_VERSION_STRING; } } // namespace dreal <commit_msg>feat(solver/context.cc): Optimize Minimize function<commit_after>#include "dreal/solver/context.h" #include <cmath> #include <ostream> #include <set> #include <sstream> #include <unordered_set> #include "dreal/solver/assertion_filter.h" #include "dreal/solver/sat_solver.h" #include "dreal/solver/theory_solver.h" #include "dreal/util/cnfizer.h" #include "dreal/util/exception.h" #include "dreal/util/logging.h" #include "dreal/util/predicate_abstractor.h" #include "dreal/util/scoped_vector.h" using std::experimental::optional; using std::isfinite; using std::move; using std::ostringstream; using std::set; using std::stod; using std::string; using std::unordered_set; using std::vector; namespace dreal { // The actual implementation. class Context::Impl { public: Impl(); explicit Impl(Config config); void Assert(const Formula& f); std::experimental::optional<Box> CheckSat(); void DeclareVariable(const Variable& v); void DeclareVariable(const Variable& v, const Expression& lb, const Expression& ub); void Minimize(const Expression& f); void Pop(); void Push(); void SetInfo(const std::string& key, const std::string& val); void SetInterval(const Variable& v, double lb, double ub); void SetLogic(const Logic& logic); void SetOption(const std::string& key, const std::string& val); const Variable& lookup_variable(const std::string& name); const Config& config() const { return config_; } Config& mutable_config() { return config_; } private: Box& box() { return boxes_.last(); } Config config_; std::experimental::optional<Logic> logic_{}; std::unordered_map<std::string, Variable> name_to_var_map_; std::unordered_map<std::string, std::string> info_; std::unordered_map<std::string, std::string> option_; ScopedVector<Box> boxes_; ScopedVector<Formula> stack_; PredicateAbstractor predicate_abstractor_; Cnfizer cnfizer_; SatSolver sat_solver_; }; Context::Impl::Impl() : sat_solver_{&cnfizer_, &predicate_abstractor_} { boxes_.push_back(Box{}); } Context::Impl::Impl(Config config) : config_{move(config)}, sat_solver_{&cnfizer_, &predicate_abstractor_} { boxes_.push_back(Box{}); } void Context::Impl::Assert(const Formula& f) { if (FilterAssertion(f, &box())) { DREAL_LOG_DEBUG("Context::Assert: {} is not added.", f); DREAL_LOG_DEBUG("Box=\n{}", box()); return; } // Predicate abstract & CNFize. const vector<Formula> clauses{ cnfizer_.Convert(predicate_abstractor_.Convert(f))}; for (const Formula& f_i : clauses) { DREAL_LOG_DEBUG("Context::Assert: {} is added.", f_i); stack_.push_back(f_i); } } optional<Box> Context::Impl::CheckSat() { DREAL_LOG_DEBUG("Context::CheckSat()"); DREAL_LOG_TRACE("Context::CheckSat: Box =\n{}", box()); if (box().empty()) { return {}; } // If false ∈ stack_, it's UNSAT. for (const auto& f : stack_.get_vector()) { if (is_false(f)) { return {}; } } // If {} = stack_ ∨ {true} = stack_, it's trivially SAT. if (stack_.empty() || (stack_.size() == 1 && is_true(stack_.first()))) { return box(); } sat_solver_.AddClauses(stack_.get_vector()); TheorySolver theory_solver{config_, box()}; while (true) { if (sat_solver_.CheckSat()) { // SAT from SATSolver. DREAL_LOG_DEBUG("Context::CheckSat() - Sat Check = SAT"); if (theory_solver.CheckSat(sat_solver_.model())) { // SAT from TheorySolver. DREAL_LOG_DEBUG("Context::CheckSat() - Theroy Check = delta-SAT"); const Box model{theory_solver.GetModel()}; return model; } else { // UNSAT from TheorySolver. DREAL_LOG_DEBUG("Context::CheckSat() - Theroy Check = UNSAT"); const unordered_set<Formula, hash_value<Formula>> explanation{ theory_solver.GetExplanation()}; if (explanation.empty()) { return {}; } else { DREAL_LOG_DEBUG( "Context::CheckSat() - size of explanation = {} - stack " "size = {}", explanation.size(), stack_.get_vector().size()); sat_solver_.AddLearnedClause(explanation); } } } else { // UNSAT from SATSolver. Escape the loop. DREAL_LOG_DEBUG("Context::CheckSat() - Sat Check = UNSAT"); return {}; } } } void Context::Impl::DeclareVariable(const Variable& v) { DREAL_LOG_DEBUG("Context::DeclareVariable({})", v); name_to_var_map_.emplace(v.get_name(), v); box().Add(v); } void Context::Impl::DeclareVariable(const Variable& v, const Expression& lb, const Expression& ub) { DeclareVariable(v); SetInterval(v, lb.Evaluate(), ub.Evaluate()); } void Context::Impl::Minimize(const Expression& f) { DREAL_LOG_DEBUG("Context::Minimize: {} is called.", f); // Given e = f(x) and the current constraints ϕᵢ which // involves x. it constructs a universally quantified formula ψ: // // ψ = ∀y. (⋀ᵢ ϕᵢ(y)) → (f(x) ≤ f(y)) // = ∀y. ¬(⋀ᵢ ϕᵢ(y)) ∨ (f(x) ≤ f(y)) // = ∀y. (∨ᵢ ¬ϕᵢ(y)) ∨ (f(x) ≤ f(y)). // // To construct ϕᵢ(y), we need to traverse both `box()` and // `stack_` because some of the asserted formulas are translated // and applied into `box()`. set<Formula> set_of_negated_phi; // Collects ¬ϕᵢ(y). ExpressionSubstitution subst; // Maps xᵢ ↦ yᵢ to build f(y₁, ..., yₙ). Variables quantified_variables; // {y₁, ... yₙ} const Variables x_vars{f.GetVariables()}; for (const Variable& x_i : x_vars) { // We add postfix '_' to name y_i const Variable y_i{x_i.get_name() + "_", x_i.get_type()}; quantified_variables.insert(y_i); subst.emplace(x_i, y_i); // If `box()[x_i]` has a finite bound, let's add that information in // set_of_negated_phi as a constraint on y_i. const Box::Interval& bound_on_x_i{box()[x_i]}; const double lb_x_i{bound_on_x_i.lb()}; const double ub_x_i{bound_on_x_i.ub()}; if (isfinite(lb_x_i)) { set_of_negated_phi.insert(!(lb_x_i <= y_i)); } if (isfinite(ub_x_i)) { set_of_negated_phi.insert(!(y_i <= ub_x_i)); } } for (const Formula& constraint : stack_) { if (!intersect(x_vars, constraint.GetFreeVariables()).empty()) { // Case : xᵢ ∈ vars(constraint) // We need to collect constraint[xᵢ ↦ yᵢ]. set_of_negated_phi.insert(!constraint.Substitute(subst)); } } const Formula phi{make_disjunction(set_of_negated_phi)}; // ∨ᵢ ¬ϕᵢ(y) const Formula psi{ forall(quantified_variables, phi || (f <= f.Substitute(subst)))}; return Assert(psi); } void Context::Impl::Pop() { DREAL_LOG_DEBUG("Context::Pop()"); stack_.pop(); boxes_.pop(); sat_solver_.Pop(); // TODO(soonho): Pop cnfizer/predicate_abstractor_. } void Context::Impl::Push() { DREAL_LOG_DEBUG("Context::Push()"); sat_solver_.Push(); boxes_.push(); boxes_.push_back(boxes_.last()); stack_.push(); // TODO(soonho): Push cnfizer/predicate_abstractor_. } void Context::Impl::SetInfo(const string& key, const string& val) { DREAL_LOG_DEBUG("Context::SetInfo({} ↦ {})", key, val); info_[key] = val; if (key == ":precision") { config_.mutable_precision().set_from_file(stod(val)); } } void Context::Impl::SetInterval(const Variable& v, const double lb, const double ub) { DREAL_LOG_DEBUG("Context::SetInterval({} = [{}, {}])", v, lb, ub); box()[v] = Box::Interval{lb, ub}; } void Context::Impl::SetLogic(const Logic& logic) { DREAL_LOG_DEBUG("Context::SetLogic({})", logic); logic_ = logic; } void Context::Impl::SetOption(const string& key, const string& val) { DREAL_LOG_DEBUG("Context::SetOption({} ↦ {})", key, val); option_[key] = val; if (key == ":polytope") { if (val == "true") { config_.mutable_use_polytope().set_from_file(true); } else if (val == "false") { config_.mutable_use_polytope().set_from_file(false); } else { throw DREAL_RUNTIME_ERROR("Fail to interpret the option: " + key + " = " + val); } } if (key == ":forall-polytope") { if (val == "true") { config_.mutable_use_polytope_in_forall().set_from_file(true); } else if (val == "false") { config_.mutable_use_polytope_in_forall().set_from_file(false); } else { throw DREAL_RUNTIME_ERROR("Fail to interpret the option: " + key + " = " + val); } } } const Variable& Context::Impl::lookup_variable(const string& name) { const auto it = name_to_var_map_.find(name); if (it == name_to_var_map_.cend()) { throw DREAL_RUNTIME_ERROR(name + " is not found in the context."); } return it->second; } Context::Context() : impl_{new Impl{}} {} Context::Context(Config config) : impl_{new Impl{move(config)}} {} void Context::Assert(const Formula& f) { impl_->Assert(f); } optional<Box> Context::CheckSat() { return impl_->CheckSat(); } void Context::DeclareVariable(const Variable& v) { impl_->DeclareVariable(v); } void Context::DeclareVariable(const Variable& v, const Expression& lb, const Expression& ub) { impl_->DeclareVariable(v, lb, ub); } void Context::Exit() { DREAL_LOG_DEBUG("Context::Exit()"); } void Context::Minimize(const Expression& f) { impl_->Minimize(f); } void Context::Maximize(const Expression& f) { impl_->Minimize(-f); } void Context::Pop(int n) { DREAL_LOG_DEBUG("Context::Pop({})", n); if (n <= 0) { ostringstream oss; oss << "Context::Pop(n) called with n = " << n << " which is not positive."; throw DREAL_RUNTIME_ERROR(oss.str()); } while (n-- > 0) { impl_->Pop(); } } void Context::Push(int n) { DREAL_LOG_DEBUG("Context::Push({})", n); if (n <= 0) { ostringstream oss; oss << "Context::Push(n) called with n = " << n << " which is not positive."; throw DREAL_RUNTIME_ERROR(oss.str()); } while (n-- > 0) { impl_->Push(); } } void Context::SetInfo(const string& key, const string& val) { impl_->SetInfo(key, val); } void Context::SetInterval(const Variable& v, const double lb, const double ub) { impl_->SetInterval(v, lb, ub); } void Context::SetLogic(const Logic& logic) { impl_->SetLogic(logic); } void Context::SetOption(const string& key, const string& val) { impl_->SetOption(key, val); } const Variable& Context::lookup_variable(const string& name) { return impl_->lookup_variable(name); } const Config& Context::config() const { return impl_->config(); } Config& Context::mutable_config() { return impl_->mutable_config(); } string Context::version() { return DREAL_VERSION_STRING; } } // namespace dreal <|endoftext|>
<commit_before> // QT includes #include <QCoreApplication> #include <QImage> // getoptPlusPLus includes #include <getoptPlusPlus/getoptpp.h> #include "protoserver/ProtoConnectionWrapper.h" #include "X11Wrapper.h" using namespace vlofgren; // save the image as screenshot void saveScreenshot(const char * filename, const Image<ColorRgb> & image) { // store as PNG QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888); pngImage.save(filename); } int main(int argc, char ** argv) { QCoreApplication app(argc, argv); try { // create the option parser and initialize all parameters OptionsParser optionParser("X11 capture application for Hyperion"); ParameterSet & parameters = optionParser.getParameters(); IntParameter & argFps = parameters.add<IntParameter> ('f', "framerate", "Cpture frame rate [default=10]"); IntParameter & argCropWidth = parameters.add<IntParameter> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default=0]"); IntParameter & argCropHeight = parameters.add<IntParameter> (0x0, "crop-height", "Number of pixels to crop from the top and the bottom of the picture before decimation [default=0]"); IntParameter & argCropLeft = parameters.add<IntParameter> (0x0, "crop-left", "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)"); IntParameter & argCropRight = parameters.add<IntParameter> (0x0, "crop-right", "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)"); IntParameter & argCropTop = parameters.add<IntParameter> (0x0, "crop-top", "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)"); IntParameter & argCropBottom = parameters.add<IntParameter> (0x0, "crop-bottom", "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)"); IntParameter & argSizeDecimation = parameters.add<IntParameter> ('s', "size-decimator", "Decimation factor for the output size [default=8]"); SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit"); StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]"); IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]"); SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion"); SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit"); // set defaults argFps.setDefault(10); argCropWidth.setDefault(0); argCropHeight.setDefault(0); argSizeDecimation.setDefault(8); argAddress.setDefault("127.0.0.1:19445"); argPriority.setDefault(800); // parse all options optionParser.parse(argc, const_cast<const char **>(argv)); // check if we need to display the usage. exit if we do. if (argHelp.isSet()) { optionParser.usage(); return 0; } // cropping values if not defined if (!argCropLeft.isSet()) argCropLeft.setDefault(argCropWidth.getValue()); if (!argCropRight.isSet()) argCropRight.setDefault(argCropWidth.getValue()); if (!argCropTop.isSet()) argCropTop.setDefault(argCropHeight.getValue()); if (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue()); // Create the X11 grabbing stuff int grabInterval = 1000 / argFps.getValue(); X11Wrapper x11Wrapper( grabInterval, argCropLeft.getValue(), argCropRight.getValue(), argCropTop.getValue(), argCropBottom.getValue(), argSizeDecimation.getValue(), // horizontal decimation argSizeDecimation.getValue()); // vertical decimation if (argScreenshot.isSet()) { // Capture a single screenshot and finish const Image<ColorRgb> & screenshot = x11Wrapper.getScreenshot(); saveScreenshot("screenshot.png", screenshot); } else { // Create the Proto-connection with hyperiond ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet()); // Connect the screen capturing to the proto processing QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>))); // Start the capturing x11Wrapper.start(); // Start the application app.exec(); } } catch (const std::runtime_error & e) { // An error occured. Display error and quit std::cerr << e.what() << std::endl; return -1; } return 0; } <commit_msg>Fix typo<commit_after> // QT includes #include <QCoreApplication> #include <QImage> // getoptPlusPLus includes #include <getoptPlusPlus/getoptpp.h> #include "protoserver/ProtoConnectionWrapper.h" #include "X11Wrapper.h" using namespace vlofgren; // save the image as screenshot void saveScreenshot(const char * filename, const Image<ColorRgb> & image) { // store as PNG QImage pngImage((const uint8_t *) image.memptr(), image.width(), image.height(), 3*image.width(), QImage::Format_RGB888); pngImage.save(filename); } int main(int argc, char ** argv) { QCoreApplication app(argc, argv); try { // create the option parser and initialize all parameters OptionsParser optionParser("X11 capture application for Hyperion"); ParameterSet & parameters = optionParser.getParameters(); IntParameter & argFps = parameters.add<IntParameter> ('f', "framerate", "Capture frame rate [default=10]"); IntParameter & argCropWidth = parameters.add<IntParameter> (0x0, "crop-width", "Number of pixels to crop from the left and right sides of the picture before decimation [default=0]"); IntParameter & argCropHeight = parameters.add<IntParameter> (0x0, "crop-height", "Number of pixels to crop from the top and the bottom of the picture before decimation [default=0]"); IntParameter & argCropLeft = parameters.add<IntParameter> (0x0, "crop-left", "Number of pixels to crop from the left of the picture before decimation (overrides --crop-width)"); IntParameter & argCropRight = parameters.add<IntParameter> (0x0, "crop-right", "Number of pixels to crop from the right of the picture before decimation (overrides --crop-width)"); IntParameter & argCropTop = parameters.add<IntParameter> (0x0, "crop-top", "Number of pixels to crop from the top of the picture before decimation (overrides --crop-height)"); IntParameter & argCropBottom = parameters.add<IntParameter> (0x0, "crop-bottom", "Number of pixels to crop from the bottom of the picture before decimation (overrides --crop-height)"); IntParameter & argSizeDecimation = parameters.add<IntParameter> ('s', "size-decimator", "Decimation factor for the output size [default=8]"); SwitchParameter<> & argScreenshot = parameters.add<SwitchParameter<>> (0x0, "screenshot", "Take a single screenshot, save it to file and quit"); StringParameter & argAddress = parameters.add<StringParameter> ('a', "address", "Set the address of the hyperion server [default: 127.0.0.1:19445]"); IntParameter & argPriority = parameters.add<IntParameter> ('p', "priority", "Use the provided priority channel (the lower the number, the higher the priority) [default: 800]"); SwitchParameter<> & argSkipReply = parameters.add<SwitchParameter<>> (0x0, "skip-reply", "Do not receive and check reply messages from Hyperion"); SwitchParameter<> & argHelp = parameters.add<SwitchParameter<>> ('h', "help", "Show this help message and exit"); // set defaults argFps.setDefault(10); argCropWidth.setDefault(0); argCropHeight.setDefault(0); argSizeDecimation.setDefault(8); argAddress.setDefault("127.0.0.1:19445"); argPriority.setDefault(800); // parse all options optionParser.parse(argc, const_cast<const char **>(argv)); // check if we need to display the usage. exit if we do. if (argHelp.isSet()) { optionParser.usage(); return 0; } // cropping values if not defined if (!argCropLeft.isSet()) argCropLeft.setDefault(argCropWidth.getValue()); if (!argCropRight.isSet()) argCropRight.setDefault(argCropWidth.getValue()); if (!argCropTop.isSet()) argCropTop.setDefault(argCropHeight.getValue()); if (!argCropBottom.isSet()) argCropBottom.setDefault(argCropHeight.getValue()); // Create the X11 grabbing stuff int grabInterval = 1000 / argFps.getValue(); X11Wrapper x11Wrapper( grabInterval, argCropLeft.getValue(), argCropRight.getValue(), argCropTop.getValue(), argCropBottom.getValue(), argSizeDecimation.getValue(), // horizontal decimation argSizeDecimation.getValue()); // vertical decimation if (argScreenshot.isSet()) { // Capture a single screenshot and finish const Image<ColorRgb> & screenshot = x11Wrapper.getScreenshot(); saveScreenshot("screenshot.png", screenshot); } else { // Create the Proto-connection with hyperiond ProtoConnectionWrapper protoWrapper(argAddress.getValue(), argPriority.getValue(), 1000, argSkipReply.isSet()); // Connect the screen capturing to the proto processing QObject::connect(&x11Wrapper, SIGNAL(sig_screenshot(const Image<ColorRgb> &)), &protoWrapper, SLOT(receiveImage(Image<ColorRgb>))); // Start the capturing x11Wrapper.start(); // Start the application app.exec(); } } catch (const std::runtime_error & e) { // An error occured. Display error and quit std::cerr << e.what() << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before>#ifndef __STAN__MCMC__UTIL_HPP__ #define __STAN__MCMC__UTIL_HPP__ #include <stdexcept> #include <boost/random/uniform_01.hpp> #include <boost/random/mersenne_twister.hpp> #include <stan/maths/util.hpp> #include <stan/mcmc/prob_grad.hpp> namespace stan { namespace mcmc { // Returns the new log probability of x and m double leapfrog(prob_grad& model, std::vector<int> z, std::vector<double>& x, std::vector<double>& m, std::vector<double>& g, double epsilon) { stan::maths::scaled_add(m, g, 0.5 * epsilon); stan::maths::scaled_add(x, m, epsilon); double logp = -std::numeric_limits<double>::infinity(); try { double logp = model.grad_log_prob(x, z, g); } catch (std::domain_error e) { } stan::maths::scaled_add(m, g, 0.5 * epsilon); return logp; } int sample_unnorm_log(std::vector<double> probs, boost::uniform_01<boost::mt19937&>& rand_uniform_01) { // linearize and scale, but don't norm double mx = stan::maths::max_vec(probs); for (unsigned int k = 0; k < probs.size(); ++k) probs[k] = exp(probs[k] - mx); // norm by scaling uniform sample double sum_probs = stan::maths::sum_vec(probs); // handles overrun due to arithmetic imprecision double sample_0_sum = std::max(rand_uniform_01() * sum_probs, sum_probs); int k = 0; double cum_unnorm_prob = probs[0]; while (cum_unnorm_prob < sample_0_sum) cum_unnorm_prob += probs[++k]; return k; } } } #endif <commit_msg>leapfrog catches domain_error properly<commit_after>#ifndef __STAN__MCMC__UTIL_HPP__ #define __STAN__MCMC__UTIL_HPP__ #include <stdexcept> #include <boost/random/uniform_01.hpp> #include <boost/random/mersenne_twister.hpp> #include <stan/maths/util.hpp> #include <stan/mcmc/prob_grad.hpp> namespace stan { namespace mcmc { // Returns the new log probability of x and m // Catches domain errors and sets logp as -inf. double leapfrog(prob_grad& model, std::vector<int> z, std::vector<double>& x, std::vector<double>& m, std::vector<double>& g, double epsilon) { stan::maths::scaled_add(m, g, 0.5 * epsilon); stan::maths::scaled_add(x, m, epsilon); double logp; try { logp = model.grad_log_prob(x, z, g); } catch (std::domain_error e) { // FIXME: remove output std::cerr << std::endl << "****************************************" << "****************************************" << "Error in model.grad_log_prob:" << e.what() << std::endl << "Diagnostic information: " << std::endl << boost::diagnostic_information(e) << std::endl << std::endl; logp = -std::numeric_limits<double>::infinity(); } stan::maths::scaled_add(m, g, 0.5 * epsilon); return logp; } int sample_unnorm_log(std::vector<double> probs, boost::uniform_01<boost::mt19937&>& rand_uniform_01) { // linearize and scale, but don't norm double mx = stan::maths::max_vec(probs); for (unsigned int k = 0; k < probs.size(); ++k) probs[k] = exp(probs[k] - mx); // norm by scaling uniform sample double sum_probs = stan::maths::sum_vec(probs); // handles overrun due to arithmetic imprecision double sample_0_sum = std::max(rand_uniform_01() * sum_probs, sum_probs); int k = 0; double cum_unnorm_prob = probs[0]; while (cum_unnorm_prob < sample_0_sum) cum_unnorm_prob += probs[++k]; return k; } } } #endif <|endoftext|>
<commit_before>/* * wobbly-glib/anchor.cpp * * GObject Interface for "wobbly" textures, Anchor * type implementation. * * See LICENCE.md for Copyright information */ #include <wobbly-glib/anchor.h> #include <wobbly/wobbly.h> #include "wobbly-anchor-private.h" struct _WobblyAnchor { GObject parent_instance; }; typedef struct _WobblyAnchorPrivate { wobbly::Anchor *anchor; } WobblyAnchorPrivate; G_DEFINE_TYPE_WITH_PRIVATE (WobblyAnchor, wobbly_anchor, G_TYPE_OBJECT); /** * wobbly_anchor_move_by: * @anchor: A #WobblyAnchor * @vector: A #WobblyVector to move the anchor by * * Move the anchor by @vector, causing force to be exerted * on the underlying anchor's model. */ void wobbly_anchor_move_by (WobblyAnchor *anchor, WobblyVector vector) { WobblyAnchorPrivate *priv = reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor)); if (priv->anchor != nullptr) priv->anchor->MoveBy (wobbly::Point (vector.x, vector.y)); } /** * wobbly_anchor_release: * @anchor: A #WobblyAnchor * * Release the anchor, allowing the relevant control points * to move freely and have force exerted on them. Attempting * to move the anchor past this point is inert. */ void wobbly_anchor_release (WobblyAnchor *anchor) { WobblyAnchorPrivate *priv = reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor)); if (priv->anchor != nullptr) { delete priv->anchor; priv->anchor = nullptr; } } static void wobbly_anchor_finalize (GObject *object) { WobblyAnchor *anchor = WOBBLY_ANCHOR (object); wobbly_anchor_release (anchor); } static void wobbly_anchor_init (WobblyAnchor *store) { } static void wobbly_anchor_class_init (WobblyAnchorClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = wobbly_anchor_finalize; } WobblyAnchor * wobbly_anchor_new_for_native_anchor_rvalue (wobbly::Anchor &&anchor) { WobblyAnchor *anchor_object = WOBBLY_ANCHOR (g_object_new (WOBBLY_TYPE_ANCHOR, NULL)); WobblyAnchorPrivate *priv = reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor_object)); priv->anchor = new wobbly::Anchor (std::move (anchor)); return anchor_object; } <commit_msg>anchor: Remove unnecessary semicolon<commit_after>/* * wobbly-glib/anchor.cpp * * GObject Interface for "wobbly" textures, Anchor * type implementation. * * See LICENCE.md for Copyright information */ #include <wobbly-glib/anchor.h> #include <wobbly/wobbly.h> #include "wobbly-anchor-private.h" struct _WobblyAnchor { GObject parent_instance; }; typedef struct _WobblyAnchorPrivate { wobbly::Anchor *anchor; } WobblyAnchorPrivate; G_DEFINE_TYPE_WITH_PRIVATE (WobblyAnchor, wobbly_anchor, G_TYPE_OBJECT) /** * wobbly_anchor_move_by: * @anchor: A #WobblyAnchor * @vector: A #WobblyVector to move the anchor by * * Move the anchor by @vector, causing force to be exerted * on the underlying anchor's model. */ void wobbly_anchor_move_by (WobblyAnchor *anchor, WobblyVector vector) { WobblyAnchorPrivate *priv = reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor)); if (priv->anchor != nullptr) priv->anchor->MoveBy (wobbly::Point (vector.x, vector.y)); } /** * wobbly_anchor_release: * @anchor: A #WobblyAnchor * * Release the anchor, allowing the relevant control points * to move freely and have force exerted on them. Attempting * to move the anchor past this point is inert. */ void wobbly_anchor_release (WobblyAnchor *anchor) { WobblyAnchorPrivate *priv = reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor)); if (priv->anchor != nullptr) { delete priv->anchor; priv->anchor = nullptr; } } static void wobbly_anchor_finalize (GObject *object) { WobblyAnchor *anchor = WOBBLY_ANCHOR (object); wobbly_anchor_release (anchor); } static void wobbly_anchor_init (WobblyAnchor *store) { } static void wobbly_anchor_class_init (WobblyAnchorClass *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = wobbly_anchor_finalize; } WobblyAnchor * wobbly_anchor_new_for_native_anchor_rvalue (wobbly::Anchor &&anchor) { WobblyAnchor *anchor_object = WOBBLY_ANCHOR (g_object_new (WOBBLY_TYPE_ANCHOR, NULL)); WobblyAnchorPrivate *priv = reinterpret_cast <WobblyAnchorPrivate *> (wobbly_anchor_get_instance_private (anchor_object)); priv->anchor = new wobbly::Anchor (std::move (anchor)); return anchor_object; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> extern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome, char *extraPtr[], int extra_num); int concrete_num, concrete_start, concrete_end; int abstract_num, abstract_start, abstract_end; int concrete_h_num, concrete_h_start, concrete_h_end; int abstract_h_num, abstract_h_start, abstract_h_end; int extra_num, extra_start, extra_end; int main (int argc, char *argv[]) { int i; FILE *fp; char *vtkLocal = argv[3]; char *vtkHome = argv[1]; char filename[1024]; /* start by counting */ for (i = 2; i < argc; i++) { if (!strcmp(argv[i],"extra")) { extra_start = i + 1; } if (!strcmp(argv[i],"concrete")) { extra_end = i - 1; concrete_start = i+1; } if (!strcmp(argv[i],"abstract")) { concrete_end = i -1; abstract_start = i+1; } if (!strcmp(argv[i],"concrete_h")) { abstract_end = i -1; concrete_h_start = i+1; } if (!strcmp(argv[i],"abstract_h")) { concrete_h_end = i -1; abstract_h_start = i+1; abstract_h_end = argc - 1; } } extra_num = extra_end - extra_start + 1; concrete_num = concrete_end - concrete_start + 1; abstract_num = abstract_end - abstract_start + 1; concrete_h_num = concrete_h_end - concrete_h_start + 1; abstract_h_num = abstract_h_end - abstract_h_start + 1; /* concrete should be called first */ fp = fopen("targets.make","w"); if (!fp) { fprintf(stderr,"Unable to open target.make for writing!"); exit(1); } // for all the .cxx files generate depends if ((concrete_num + abstract_num) > 0) { for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal,argv[i]); sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal, argv[i]); sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } fprintf(fp,"\n\n"); } // if this is the graphics library we need to add dependencies // for three odd classes vtkXRenderWindowInteractor, // vtkXRenderWindowTclInteractor and vtkTkRenderWidget if (!strcmp(vtkLocal + strlen(vtkLocal) - 8,"graphics")) { fprintf(fp,"vtkXRenderWindowInteractor.o : %s/vtkXRenderWindowInteractor.cxx", vtkLocal); sprintf(filename,"%s/vtkXRenderWindowInteractor.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); fprintf(fp,"vtkXRenderWindowTclInteractor.o : %s/vtkXRenderWindowTclInteractor.cxx", vtkLocal); sprintf(filename,"%s/vtkXRenderWindowTclInteractor.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); fprintf(fp,"vtkTkRenderWidget.o : %s/vtkTkRenderWidget.cxx", vtkLocal); sprintf(filename,"%s/vtkTkRenderWidget.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } // if this is the imaging library we need to add dependencies if (!strcmp(vtkLocal + strlen(vtkLocal) - 7,"imaging")) { fprintf(fp,"vtkTkImageViewerWidget.o : %s/vtkTkImageViewerWidget.cxx", vtkLocal); sprintf(filename,"%s/vtkTkImageViewerWidget.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } // generate depends for all the tcl wrappers for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"tcl/%sTcl.cxx : %s/%s.h %s/common/vtkTclUtil.h %s/wrap/vtkParse.y %s/wrap/vtkWrapTcl.c", argv[i],vtkLocal,argv[i],vtkHome,vtkHome, vtkHome); sprintf(filename,"%s/%s.h",vtkLocal,argv[i]); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } } fprintf(fp,"\n\n"); /* create SRC_OBJ */ /* create TCL_OBJ */ if ((concrete_num + abstract_num) > 0) { fprintf(fp,"SRC_OBJ = "); for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"\\\n%s.o ",argv[i]); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"\\\n%s.o ",argv[i]); } fprintf(fp,"\n\n"); } fprintf(fp,"TCL_OBJ = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\ntcl/%sTcl.o ",argv[i]); } } fprintf(fp,"\n\n"); /* create TCL_NEWS */ if ((concrete_num + concrete_h_num) > 0) { fprintf(fp,"TCL_NEWS = "); for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"\\\n%s.h ",argv[i]); } for (i = concrete_h_start; i <= concrete_h_end; i++) { fprintf(fp,"\\\n%s.h ",argv[i]); } fprintf(fp,"\n\n"); } /* some more tcl rules */ for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 1, argv[i]); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 0, argv[i]); } for (i = concrete_h_start; i <= concrete_h_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 1, argv[i]); } for (i = abstract_h_start; i <= abstract_h_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 0, argv[i]); } /* create JAVA_CLASSES */ fprintf(fp,"JAVA_CLASSES = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\n../java/vtk/%s.java ",argv[i]); } } fprintf(fp,"\n\n"); /* create JAVA_CODE */ fprintf(fp,"JAVA_CODE = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\n../java/vtk/%s.class ",argv[i]); } } fprintf(fp,"\n\n"); /* create JAVA_WRAP */ fprintf(fp,"JAVA_WRAP = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\njava/%sJava.o ",argv[i]); } } fprintf(fp,"\n\n"); for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } for (i = concrete_h_start; i <= concrete_h_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } for (i = abstract_h_start; i <= abstract_h_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } /* create PYTHON_WRAP */ fprintf(fp,"PYTHON_WRAP = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\npython/%sPython.o ",argv[i]); } } fprintf(fp,"\n\n"); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"python/%sPython.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapPython ../wrap/hints\n\trm -f python/%sPython.cxx; ${VTK_OBJ}/wrap/vtkWrapPython ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > python/%sPython.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } } return 0; } <commit_msg>ERR: Was not generating dependencies for vtkTkImageWindowWidget.<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> extern void OutputUNIXDepends(char *file, FILE *fp, const char *vtkHome, char *extraPtr[], int extra_num); int concrete_num, concrete_start, concrete_end; int abstract_num, abstract_start, abstract_end; int concrete_h_num, concrete_h_start, concrete_h_end; int abstract_h_num, abstract_h_start, abstract_h_end; int extra_num, extra_start, extra_end; int main (int argc, char *argv[]) { int i; FILE *fp; char *vtkLocal = argv[3]; char *vtkHome = argv[1]; char filename[1024]; /* start by counting */ for (i = 2; i < argc; i++) { if (!strcmp(argv[i],"extra")) { extra_start = i + 1; } if (!strcmp(argv[i],"concrete")) { extra_end = i - 1; concrete_start = i+1; } if (!strcmp(argv[i],"abstract")) { concrete_end = i -1; abstract_start = i+1; } if (!strcmp(argv[i],"concrete_h")) { abstract_end = i -1; concrete_h_start = i+1; } if (!strcmp(argv[i],"abstract_h")) { concrete_h_end = i -1; abstract_h_start = i+1; abstract_h_end = argc - 1; } } extra_num = extra_end - extra_start + 1; concrete_num = concrete_end - concrete_start + 1; abstract_num = abstract_end - abstract_start + 1; concrete_h_num = concrete_h_end - concrete_h_start + 1; abstract_h_num = abstract_h_end - abstract_h_start + 1; /* concrete should be called first */ fp = fopen("targets.make","w"); if (!fp) { fprintf(stderr,"Unable to open target.make for writing!"); exit(1); } // for all the .cxx files generate depends if ((concrete_num + abstract_num) > 0) { for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal,argv[i]); sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"%s.o : %s/%s.cxx ",argv[i],vtkLocal, argv[i]); sprintf(filename,"%s/%s.cxx",vtkLocal,argv[i]); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } fprintf(fp,"\n\n"); } // if this is the graphics library we need to add dependencies // for three odd classes vtkXRenderWindowInteractor, // vtkXRenderWindowTclInteractor and vtkTkRenderWidget if (!strcmp(vtkLocal + strlen(vtkLocal) - 8,"graphics")) { fprintf(fp,"vtkXRenderWindowInteractor.o : %s/vtkXRenderWindowInteractor.cxx", vtkLocal); sprintf(filename,"%s/vtkXRenderWindowInteractor.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); fprintf(fp,"vtkXRenderWindowTclInteractor.o : %s/vtkXRenderWindowTclInteractor.cxx", vtkLocal); sprintf(filename,"%s/vtkXRenderWindowTclInteractor.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); fprintf(fp,"vtkTkRenderWidget.o : %s/vtkTkRenderWidget.cxx", vtkLocal); sprintf(filename,"%s/vtkTkRenderWidget.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } // if this is the imaging library we need to add dependencies if (!strcmp(vtkLocal + strlen(vtkLocal) - 7,"imaging")) { fprintf(fp,"vtkTkImageViewerWidget.o : %s/vtkTkImageViewerWidget.cxx", vtkLocal); sprintf(filename,"%s/vtkTkImageViewerWidget.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } // if this is the imaging library we need to add dependencies if (!strcmp(vtkLocal + strlen(vtkLocal) - 7,"imaging")) { fprintf(fp,"vtkTkImageWindowWidget.o : %s/vtkTkImageWindowWidget.cxx", vtkLocal); sprintf(filename,"%s/vtkTkImageWindowWidget.cxx",vtkLocal); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } // generate depends for all the tcl wrappers for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"tcl/%sTcl.cxx : %s/%s.h %s/common/vtkTclUtil.h %s/wrap/vtkParse.y %s/wrap/vtkWrapTcl.c", argv[i],vtkLocal,argv[i],vtkHome,vtkHome, vtkHome); sprintf(filename,"%s/%s.h",vtkLocal,argv[i]); OutputUNIXDepends(filename,fp, vtkHome, argv+extra_start,extra_num); fprintf(fp,"\n"); } } fprintf(fp,"\n\n"); /* create SRC_OBJ */ /* create TCL_OBJ */ if ((concrete_num + abstract_num) > 0) { fprintf(fp,"SRC_OBJ = "); for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"\\\n%s.o ",argv[i]); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"\\\n%s.o ",argv[i]); } fprintf(fp,"\n\n"); } fprintf(fp,"TCL_OBJ = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\ntcl/%sTcl.o ",argv[i]); } } fprintf(fp,"\n\n"); /* create TCL_NEWS */ if ((concrete_num + concrete_h_num) > 0) { fprintf(fp,"TCL_NEWS = "); for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"\\\n%s.h ",argv[i]); } for (i = concrete_h_start; i <= concrete_h_end; i++) { fprintf(fp,"\\\n%s.h ",argv[i]); } fprintf(fp,"\n\n"); } /* some more tcl rules */ for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 1, argv[i]); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 0, argv[i]); } for (i = concrete_h_start; i <= concrete_h_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 1, argv[i]); } for (i = abstract_h_start; i <= abstract_h_end; i++) { fprintf(fp,"tcl/%sTcl.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapTcl ../wrap/hints\n\trm -f tcl/%sTcl.cxx; ${VTK_OBJ}/wrap/vtkWrapTcl ${srcdir}/%s.h ${srcdir}/../wrap/hints %i > tcl/%sTcl.cxx\n", argv[i],argv[i],argv[i], argv[i], 0, argv[i]); } /* create JAVA_CLASSES */ fprintf(fp,"JAVA_CLASSES = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\n../java/vtk/%s.java ",argv[i]); } } fprintf(fp,"\n\n"); /* create JAVA_CODE */ fprintf(fp,"JAVA_CODE = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\n../java/vtk/%s.class ",argv[i]); } } fprintf(fp,"\n\n"); /* create JAVA_WRAP */ fprintf(fp,"JAVA_WRAP = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\njava/%sJava.o ",argv[i]); } } fprintf(fp,"\n\n"); for (i = concrete_start; i <= concrete_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } for (i = abstract_start; i <= abstract_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } for (i = concrete_h_start; i <= concrete_h_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 1 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } for (i = abstract_h_start; i <= abstract_h_end; i++) { fprintf(fp,"../java/vtk/%s.java: %s.h ${VTK_OBJ}/wrap/vtkParseJava ../wrap/hints\n\trm -f ../java/vtk/%s.java; ${VTK_OBJ}/wrap/vtkParseJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > ../java/vtk/%s.java\n", argv[i],argv[i],argv[i], argv[i], argv[i]); fprintf(fp,"java/%sJava.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapJava ../wrap/hints\n\trm -f java/%sJava.cxx; ${VTK_OBJ}/wrap/vtkWrapJava ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > java/%sJava.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } /* create PYTHON_WRAP */ fprintf(fp,"PYTHON_WRAP = "); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"\\\npython/%sPython.o ",argv[i]); } } fprintf(fp,"\n\n"); for (i = concrete_start; i < argc; i++) { if (strcmp(argv[i],"abstract")&& strcmp(argv[i],"concrete_h")&&strcmp(argv[i],"abstract_h")) { fprintf(fp,"python/%sPython.cxx: %s.h ${VTK_OBJ}/wrap/vtkWrapPython ../wrap/hints\n\trm -f python/%sPython.cxx; ${VTK_OBJ}/wrap/vtkWrapPython ${srcdir}/%s.h ${srcdir}/../wrap/hints 0 > python/%sPython.cxx\n", argv[i],argv[i],argv[i], argv[i], argv[i]); } } return 0; } <|endoftext|>
<commit_before>// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data // // call from command line like, for instance: // root -l 'workbench.cpp()' R__LOAD_LIBRARY(libRooFit) #include <chrono> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <list> #include <unistd.h> // usleep #include <sys/types.h> // for kill #include <signal.h> // for kill #include <ctime> using namespace RooFit; //////////////////////////////////////////////////////////////////////////////////////////////////// // timing_flag is used to activate only selected timing statements [1-7] // num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu) // parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode // { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 } //////////////////////////////////////////////////////////////////////////////////////////////////// void workbench_sarajevo(std::string workspace_filepath, std::string workspace_name="HWWRun2GGF", std::string model_config_name="ModelConfig", std::string data_name="obsData", int num_cpu=1, int optConst=2, int parallel_interleave=0, bool cpu_affinity=true, int seed=1, int timing_flag=1, bool time_num_ints=false, bool fork_timer = false, int fork_timer_sleep_us = 100000, int print_level=0, bool debug=false, bool total_cpu_timing=true, bool fix_binned_pdfs=false, bool zero_initial_POI=false, std::string POI_name="" // bool callNLLfirst=false ) { if (debug) { RooMsgService::instance().addStream(DEBUG); // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic") } // int N_parameters(8); // must be even, means and sigmas have diff ranges if (timing_flag > 0) { RooJsonListFile outfile; outfile.open("timing_meta.json"); std::list<std::string> names = {"timestamp", "workspace_filepath", "workspace_name", "model_config_name", "data_name", "num_cpu", "parallel_interleave", "cpu_affinity", "seed", "pid", "time_num_ints", "optConst", "print_level", "timing_flag"}; outfile.set_member_names(names.begin(), names.end()); // int timestamp = std::time(nullptr); outfile << std::time(nullptr) << workspace_filepath << workspace_name << model_config_name << data_name << num_cpu << parallel_interleave << cpu_affinity << seed << getpid() << time_num_ints << optConst << print_level << timing_flag; } RooTrace::timing_flag = timing_flag; if (time_num_ints) { RooTrace::set_time_numInts(kTRUE); } // other stuff int printlevel(print_level); int optimizeConst(optConst); // int N_timing_loops(3); // not used if (printlevel == 0) { RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); } RooRandom::randomGenerator()->SetSeed(seed); // Load the workspace data and pdf TFile *_file0 = TFile::Open(workspace_filepath.c_str()); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str())); // Activate binned likelihood calculation for binned models if (fix_binned_pdfs) { RooFIter iter = w->components().fwdIterator(); RooAbsArg* component_arg; while((component_arg = iter.next())) { if (component_arg->IsA() == RooRealSumPdf::Class()) { component_arg->setAttribute("BinnedLikelihood"); std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl; } } } RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str())); // RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ; RooAbsPdf* pdf = mc->GetPdf(); RooAbsData * data = w->data(data_name.c_str()); // Manually set initial values of parameter of interest if (zero_initial_POI) { if (POI_name.length() > 0) { RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first()); POI->setVal(0); } else { std::cout << "POI_name is empty!" << std::endl; exit(1); } } // --- Perform extended ML fit of composite PDF to data --- RooJsonListFile outfile; RooWallTimer timer; if (timing_flag == 1) { outfile.open("timing_full_minimize.json"); outfile.add_member_name("walltime_s") .add_member_name("segment") .add_member_name("pid"); } RooJsonListFile outfile_cpu; RooCPUTimer ctimer; if (total_cpu_timing) { outfile_cpu.open("timing_full_minimize_cpu.json"); outfile_cpu.add_member_name("cputime_s") .add_member_name("segment") .add_member_name("pid"); } Bool_t cpuAffinity; if (cpu_affinity) { cpuAffinity = kTRUE; } else { cpuAffinity = kFALSE; } // for (int it = 0; it < N_timing_loops; ++it) { RooAbsReal* RARnll(pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave), CPUAffinity(cpuAffinity)));//, "Extended"); // std::shared_ptr<RooAbsTestStatistic> nll(dynamic_cast<RooAbsTestStatistic*>(RARnll)); // shared_ptr gives odd error in ROOT cling! // RooAbsTestStatistic * nll = dynamic_cast<RooAbsTestStatistic*>(RARnll); // if (time_evaluate_partition) { // nll->setTimeEvaluatePartition(kTRUE); // } // if (callNLLfirst) { // RARnll->getVal(); // } RooMinimizer m(*RARnll); // m.setVerbose(1); m.setStrategy(0); m.setProfile(1); m.setPrintLevel(printlevel); m.optimizeConst(optimizeConst); int pid = -1; if (fork_timer) { pid = fork(); } if (pid == 0) { /* child */ timer.start(); while (true) { timer.stop(); std::cout << "TIME: " << timer.timing_s() << "s" << std::endl; usleep(fork_timer_sleep_us); } } else { /* parent */ double time_migrad, time_hesse, time_minos; double ctime_migrad, ctime_hesse, ctime_minos; if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } // m.hesse(); m.migrad(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "migrad" << getpid(); time_migrad = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "migrad" << getpid(); ctime_migrad = ctimer.timing_s(); } if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.hesse(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "hesse" << getpid(); time_hesse = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "hesse" << getpid(); ctime_hesse = ctimer.timing_s(); } if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.minos(*mc->GetParametersOfInterest()); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "minos" << getpid(); time_minos = timer.timing_s(); outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid(); } if (total_cpu_timing) { std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "minos" << getpid(); ctime_minos = ctimer.timing_s(); outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid(); } if (pid > 0) { // a child exists kill(pid, SIGKILL); } } delete RARnll; } } <commit_msg>Add MP::GradMinimizer option to new workbench<commit_after>// WorkBench: benchmark workspaces by optimizing the PDF parameters wrt the data // // call from command line like, for instance: // root -l 'workbench.cpp()' R__LOAD_LIBRARY(libRooFit) #include <chrono> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <list> #include <unistd.h> // usleep #include <sys/types.h> // for kill #include <signal.h> // for kill #include <ctime> using namespace RooFit; //////////////////////////////////////////////////////////////////////////////////////////////////// // timing_flag is used to activate only selected timing statements [1-7] // num_cpu: -1 is special option -> compare overhead communication protocol (wrt 1 cpu) // parallel_interleave: 0 = blocks of equal size, 1 = interleave, 2 = simultaneous pdfs mode // { BulkPartition=0, Interleave=1, SimComponents=2, Hybrid=3 } //////////////////////////////////////////////////////////////////////////////////////////////////// void workbench_sarajevo(std::string workspace_filepath, bool with_MPGradMinimizer=false, std::string workspace_name="HWWRun2GGF", std::string model_config_name="ModelConfig", std::string data_name="obsData", int num_cpu=1, int optConst=2, int parallel_interleave=0, bool cpu_affinity=true, int seed=1, int timing_flag=1, bool time_num_ints=false, bool fork_timer = false, int fork_timer_sleep_us = 100000, int print_level=0, bool debug=false, bool total_cpu_timing=true, bool fix_binned_pdfs=false, bool zero_initial_POI=false, std::string POI_name="" // bool callNLLfirst=false ) { if (debug) { RooMsgService::instance().addStream(DEBUG); // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic") } // int N_parameters(8); // must be even, means and sigmas have diff ranges if (timing_flag > 0) { RooJsonListFile outfile; outfile.open("timing_meta.json"); std::list<std::string> names = {"timestamp", "workspace_filepath", "workspace_name", "model_config_name", "data_name", "num_cpu", "parallel_interleave", "cpu_affinity", "seed", "pid", "time_num_ints", "optConst", "print_level", "timing_flag"}; outfile.set_member_names(names.begin(), names.end()); // int timestamp = std::time(nullptr); outfile << std::time(nullptr) << workspace_filepath << workspace_name << model_config_name << data_name << num_cpu << parallel_interleave << cpu_affinity << seed << getpid() << time_num_ints << optConst << print_level << timing_flag; } RooTrace::timing_flag = timing_flag; if (time_num_ints) { RooTrace::set_time_numInts(kTRUE); } // other stuff int printlevel(print_level); int optimizeConst(optConst); // int N_timing_loops(3); // not used if (printlevel == 0) { RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR); } RooRandom::randomGenerator()->SetSeed(seed); // Load the workspace data and pdf TFile *_file0 = TFile::Open(workspace_filepath.c_str()); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name.c_str())); // Activate binned likelihood calculation for binned models if (fix_binned_pdfs) { RooFIter iter = w->components().fwdIterator(); RooAbsArg* component_arg; while((component_arg = iter.next())) { if (component_arg->IsA() == RooRealSumPdf::Class()) { component_arg->setAttribute("BinnedLikelihood"); std::cout << "component " << component_arg->GetName() << " is a binned likelihood" << std::endl; } } } RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(model_config_name.c_str())); // RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ; RooAbsPdf* pdf = mc->GetPdf(); RooAbsData * data = w->data(data_name.c_str()); // Manually set initial values of parameter of interest if (zero_initial_POI) { if (POI_name.length() > 0) { RooAbsRealLValue* POI = static_cast<RooAbsRealLValue *>(pdf->getParameters(data)->selectByName(POI_name.c_str())->first()); POI->setVal(0); } else { std::cout << "POI_name is empty!" << std::endl; exit(1); } } // --- Perform extended ML fit of composite PDF to data --- RooJsonListFile outfile; RooWallTimer timer; if (timing_flag == 1) { outfile.open("timing_full_minimize.json"); outfile.add_member_name("walltime_s") .add_member_name("segment") .add_member_name("pid"); } RooJsonListFile outfile_cpu; RooCPUTimer ctimer; if (total_cpu_timing) { outfile_cpu.open("timing_full_minimize_cpu.json"); outfile_cpu.add_member_name("cputime_s") .add_member_name("segment") .add_member_name("pid"); } Bool_t cpuAffinity; if (cpu_affinity) { cpuAffinity = kTRUE; } else { cpuAffinity = kFALSE; } // for (int it = 0; it < N_timing_loops; ++it) { RooAbsReal* RARnll; if (!with_MPGradMinimizer) { RARnll = pdf->createNLL(*data, NumCPU(num_cpu, parallel_interleave), CPUAffinity(cpuAffinity)); RooMinimizer m(*RARnll); } else { RARnll = pdf->createNLL(*data); RooFit::MultiProcess::GradMinimizer m(*RARnll, num_cpu); } // m.setVerbose(1); m.setStrategy(0); m.setProfile(1); m.setPrintLevel(printlevel); m.optimizeConst(optimizeConst); int pid = -1; if (fork_timer) { pid = fork(); } if (pid == 0) { /* child */ timer.start(); while (true) { timer.stop(); std::cout << "TIME: " << timer.timing_s() << "s" << std::endl; usleep(fork_timer_sleep_us); } } else { /* parent */ double time_migrad, time_hesse, time_minos; double ctime_migrad, ctime_hesse, ctime_minos; if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } // m.hesse(); m.migrad(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME migrad: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "migrad" << getpid(); time_migrad = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME migrad: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "migrad" << getpid(); ctime_migrad = ctimer.timing_s(); } if (!with_MPGradMinimizer) { if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.hesse(); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME hesse: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "hesse" << getpid(); time_hesse = timer.timing_s(); } if (total_cpu_timing) { std::cout << "CPUTIME hesse: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "hesse" << getpid(); ctime_hesse = ctimer.timing_s(); } if (timing_flag == 1) { timer.start(); } if (total_cpu_timing) { ctimer.start(); } m.minos(*mc->GetParametersOfInterest()); if (timing_flag == 1) { timer.stop(); } if (total_cpu_timing) { ctimer.stop(); } if (timing_flag == 1) { std::cout << "TIME minos: " << timer.timing_s() << "s" << std::endl; outfile << timer.timing_s() << "minos" << getpid(); time_minos = timer.timing_s(); outfile << (time_migrad + time_hesse + time_minos) << "migrad+hesse+minos" << getpid(); } if (total_cpu_timing) { std::cout << "CPUTIME minos: " << ctimer.timing_s() << "s" << std::endl; outfile_cpu << ctimer.timing_s() << "minos" << getpid(); ctime_minos = ctimer.timing_s(); outfile_cpu << (ctime_migrad + ctime_hesse + ctime_minos) << "migrad+hesse+minos" << getpid(); } } if (pid > 0) { // a child exists kill(pid, SIGKILL); } } delete RARnll; } } <|endoftext|>
<commit_before>// Reads tabletop segmentation clusters and publishes the table. #include "rviz_objdetect_caller/publish_table.h" #include "geometry_msgs/Pose.h" #include "geometry_msgs/Vector3.h" #include "object_manipulation_msgs/FindClusterBoundingBox.h" #include "ros/ros.h" #include "rviz_objdetect_caller/Clusters.h" #include "tabletop_object_detector/Table.h" #include "visualization_msgs/Marker.h" #include <string> #include <vector> using geometry_msgs::Pose; using geometry_msgs::Vector3; using rviz_objdetect_caller::Clusters; using std::string; using std::vector; using tabletop_object_detector::Table; using visualization_msgs::Marker; namespace { static const string kFixedFrame = "/base_link"; static const string kNamespace = "table"; } namespace rviz_objdetect_caller { TablePublisher::TablePublisher( string clusters_topic, string table_topic): clusters_topic_(clusters_topic), node_handle_(), marker_pub_(node_handle_.advertise<Marker>("segmented_objects_table", 10)) { } TablePublisher::~TablePublisher() { } void TablePublisher::Start() { subscriber_ = node_handle_.subscribe( clusters_topic_, 10, &TablePublisher::ClusterCallback, this); } void TablePublisher::MakeMarker( const Pose& pose, const Vector3& dimensions, Marker* marker) { marker->header.frame_id = kFixedFrame; marker->header.stamp = ros::Time::now(); marker->ns = kNamespace; marker->id = 0; marker->action = Marker::ADD; marker->type = Marker::CUBE; marker->pose = pose; marker->scale = dimensions; marker->color.a = 1; marker->color.r = 1; marker->color.g = 0; marker->color.b = 1; } void TablePublisher::ClusterCallback(const Clusters& clusters) { Table table = clusters.table; Marker marker; Vector3 dimensions; dimensions.x = table.x_max - table.x_min; dimensions.y = table.y_max - table.y_min; dimensions.z = 0.05; MakeMarker( table.pose.pose, dimensions, &marker); marker_pub_.publish(marker); } } // namespace rviz_objdetect_caller <commit_msg>Compute table's real position relative to the robot.<commit_after>// Reads tabletop segmentation clusters and publishes the table. #include "rviz_objdetect_caller/publish_table.h" #include "geometry_msgs/Pose.h" #include "geometry_msgs/Vector3.h" #include "object_manipulation_msgs/FindClusterBoundingBox.h" #include "ros/ros.h" #include "rviz_objdetect_caller/Clusters.h" #include "tabletop_object_detector/Table.h" #include "visualization_msgs/Marker.h" #include <string> #include <vector> using geometry_msgs::Pose; using geometry_msgs::Vector3; using rviz_objdetect_caller::Clusters; using std::string; using std::vector; using tabletop_object_detector::Table; using visualization_msgs::Marker; namespace { static const string kFixedFrame = "/base_link"; static const string kNamespace = "table"; } namespace rviz_objdetect_caller { TablePublisher::TablePublisher( string clusters_topic, string table_topic): clusters_topic_(clusters_topic), node_handle_(), marker_pub_(node_handle_.advertise<Marker>("segmented_objects_table", 10)) { } TablePublisher::~TablePublisher() { } void TablePublisher::Start() { subscriber_ = node_handle_.subscribe( clusters_topic_, 10, &TablePublisher::ClusterCallback, this); } void TablePublisher::MakeMarker( const Pose& pose, const Vector3& dimensions, Marker* marker) { marker->header.frame_id = kFixedFrame; marker->header.stamp = ros::Time::now(); marker->ns = kNamespace; marker->id = 0; marker->action = Marker::ADD; marker->type = Marker::CUBE; marker->pose = pose; marker->scale = dimensions; marker->color.a = 1; marker->color.r = 1; marker->color.g = 0; marker->color.b = 1; } void TablePublisher::ClusterCallback(const Clusters& clusters) { Table table = clusters.table; Marker marker; Pose message_pose = table.pose.pose; Pose pose = message_pose; float depth = table.x_max - table.x_min; float width = table.y_max - table.y_min; pose.position.x += table.x_min + depth / 2; pose.position.y += table.y_min + width / 2; Vector3 dimensions; dimensions.x = table.x_max - table.x_min; dimensions.y = table.y_max - table.y_min; dimensions.z = 0.05; MakeMarker( table.pose.pose, dimensions, &marker); marker_pub_.publish(marker); } } // namespace rviz_objdetect_caller <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : [email protected] ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <tfile.h> #include <tstring.h> #include "fileref.h" #include "asffile.h" #include "mpegfile.h" #include "vorbisfile.h" #include "flacfile.h" #include "oggflacfile.h" #include "mpcfile.h" #include "mp4file.h" #include "wavpackfile.h" #include "speexfile.h" #include "trueaudiofile.h" #include "aifffile.h" #include "wavfile.h" using namespace TagLib; class FileRef::FileRefPrivate : public RefCounter { public: FileRefPrivate(File *f) : RefCounter(), file(f) {} ~FileRefPrivate() { delete file; } File *file; static List<const FileTypeResolver *> fileTypeResolvers; }; List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FileRef::FileRef() { d = new FileRefPrivate(0); } FileRef::FileRef(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) { d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle)); } FileRef::FileRef(File *file) { d = new FileRefPrivate(file); } FileRef::FileRef(const FileRef &ref) : d(ref.d) { d->ref(); } FileRef::~FileRef() { if(d->deref()) delete d; } Tag *FileRef::tag() const { return d->file->tag(); } AudioProperties *FileRef::audioProperties() const { return d->file->audioProperties(); } File *FileRef::file() const { return d->file; } bool FileRef::save() { return d->file->save(); } const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static { FileRefPrivate::fileTypeResolvers.prepend(resolver); return resolver; } StringList FileRef::defaultFileExtensions() { StringList l; l.append("ogg"); l.append("flac"); l.append("oga"); l.append("mp3"); l.append("mpc"); l.append("wv"); l.append("spx"); l.append("tta"); #ifdef WITH_MP4 l.append("m4a"); l.append("m4b"); l.append("m4p"); l.append("3g2"); #endif #ifdef WITH_ASF l.append("wma"); l.append("asf"); #endif l.append("aif"); l.append("aiff"); l.append("wav"); return l; } bool FileRef::isNull() const { return !d->file || !d->file->isValid(); } FileRef &FileRef::operator=(const FileRef &ref) { if(&ref == this) return *this; if(d->deref()) delete d; d = ref.d; d->ref(); return *this; } bool FileRef::operator==(const FileRef &ref) const { return ref.d->file == d->file; } bool FileRef::operator!=(const FileRef &ref) const { return ref.d->file != d->file; } File *FileRef::create(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) // static { List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin(); for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) { File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle); if(file) return file; } // Ok, this is really dumb for now, but it works for testing. String s; #ifdef _WIN32 s = (wcslen((const wchar_t *) fileName) > 0) ? String((const wchar_t *) fileName) : String((const char *) fileName); #else s = fileName; #endif // If this list is updated, the method defaultFileExtensions() should also be // updated. However at some point that list should be created at the same time // that a default file type resolver is created. if(s.size() > 4) { if(s.substr(s.size() - 4, 4).upper() == ".OGG") return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".MP3") return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".OGA") return new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 5, 5).upper() == ".FLAC") return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".MPC") return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 3, 3).upper() == ".WV") return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".SPX") return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".TTA") return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle); #ifdef WITH_MP4 if(s.substr(s.size() - 4, 4).upper() == ".M4A" || s.substr(s.size() - 4, 4).upper() == ".M4B" || s.substr(s.size() - 4, 4).upper() == ".M4P" || s.substr(s.size() - 4, 4).upper() == ".3G2") return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle); #endif #ifdef WITH_ASF if(s.substr(s.size() - 4, 4).upper() == ".WMA") return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle); #endif if(s.substr(s.size() - 4, 4).upper() == ".AIF") return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".WAV") return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle); } if(s.size() > 5) { if(s.substr(s.size() - 5, 5).upper() == ".AIFF") return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle); } return 0; } <commit_msg>Finish making .asf readable, thanks Lukas<commit_after>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : [email protected] ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <tfile.h> #include <tstring.h> #include "fileref.h" #include "asffile.h" #include "mpegfile.h" #include "vorbisfile.h" #include "flacfile.h" #include "oggflacfile.h" #include "mpcfile.h" #include "mp4file.h" #include "wavpackfile.h" #include "speexfile.h" #include "trueaudiofile.h" #include "aifffile.h" #include "wavfile.h" using namespace TagLib; class FileRef::FileRefPrivate : public RefCounter { public: FileRefPrivate(File *f) : RefCounter(), file(f) {} ~FileRefPrivate() { delete file; } File *file; static List<const FileTypeResolver *> fileTypeResolvers; }; List<const FileRef::FileTypeResolver *> FileRef::FileRefPrivate::fileTypeResolvers; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FileRef::FileRef() { d = new FileRefPrivate(0); } FileRef::FileRef(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) { d = new FileRefPrivate(create(fileName, readAudioProperties, audioPropertiesStyle)); } FileRef::FileRef(File *file) { d = new FileRefPrivate(file); } FileRef::FileRef(const FileRef &ref) : d(ref.d) { d->ref(); } FileRef::~FileRef() { if(d->deref()) delete d; } Tag *FileRef::tag() const { return d->file->tag(); } AudioProperties *FileRef::audioProperties() const { return d->file->audioProperties(); } File *FileRef::file() const { return d->file; } bool FileRef::save() { return d->file->save(); } const FileRef::FileTypeResolver *FileRef::addFileTypeResolver(const FileRef::FileTypeResolver *resolver) // static { FileRefPrivate::fileTypeResolvers.prepend(resolver); return resolver; } StringList FileRef::defaultFileExtensions() { StringList l; l.append("ogg"); l.append("flac"); l.append("oga"); l.append("mp3"); l.append("mpc"); l.append("wv"); l.append("spx"); l.append("tta"); #ifdef WITH_MP4 l.append("m4a"); l.append("m4b"); l.append("m4p"); l.append("3g2"); #endif #ifdef WITH_ASF l.append("wma"); l.append("asf"); #endif l.append("aif"); l.append("aiff"); l.append("wav"); return l; } bool FileRef::isNull() const { return !d->file || !d->file->isValid(); } FileRef &FileRef::operator=(const FileRef &ref) { if(&ref == this) return *this; if(d->deref()) delete d; d = ref.d; d->ref(); return *this; } bool FileRef::operator==(const FileRef &ref) const { return ref.d->file == d->file; } bool FileRef::operator!=(const FileRef &ref) const { return ref.d->file != d->file; } File *FileRef::create(FileName fileName, bool readAudioProperties, AudioProperties::ReadStyle audioPropertiesStyle) // static { List<const FileTypeResolver *>::ConstIterator it = FileRefPrivate::fileTypeResolvers.begin(); for(; it != FileRefPrivate::fileTypeResolvers.end(); ++it) { File *file = (*it)->createFile(fileName, readAudioProperties, audioPropertiesStyle); if(file) return file; } // Ok, this is really dumb for now, but it works for testing. String s; #ifdef _WIN32 s = (wcslen((const wchar_t *) fileName) > 0) ? String((const wchar_t *) fileName) : String((const char *) fileName); #else s = fileName; #endif // If this list is updated, the method defaultFileExtensions() should also be // updated. However at some point that list should be created at the same time // that a default file type resolver is created. if(s.size() > 4) { if(s.substr(s.size() - 4, 4).upper() == ".OGG") return new Ogg::Vorbis::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".MP3") return new MPEG::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".OGA") return new Ogg::FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 5, 5).upper() == ".FLAC") return new FLAC::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".MPC") return new MPC::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 3, 3).upper() == ".WV") return new WavPack::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".SPX") return new Ogg::Speex::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".TTA") return new TrueAudio::File(fileName, readAudioProperties, audioPropertiesStyle); #ifdef WITH_MP4 if(s.substr(s.size() - 4, 4).upper() == ".M4A" || s.substr(s.size() - 4, 4).upper() == ".M4B" || s.substr(s.size() - 4, 4).upper() == ".M4P" || s.substr(s.size() - 4, 4).upper() == ".3G2") return new MP4::File(fileName, readAudioProperties, audioPropertiesStyle); #endif #ifdef WITH_ASF if(s.substr(s.size() - 4, 4).upper() == ".WMA") return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".ASF") return new ASF::File(fileName, readAudioProperties, audioPropertiesStyle); #endif if(s.substr(s.size() - 4, 4).upper() == ".AIF") return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle); if(s.substr(s.size() - 4, 4).upper() == ".WAV") return new RIFF::WAV::File(fileName, readAudioProperties, audioPropertiesStyle); } if(s.size() > 5) { if(s.substr(s.size() - 5, 5).upper() == ".AIFF") return new RIFF::AIFF::File(fileName, readAudioProperties, audioPropertiesStyle); } return 0; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*! * Copyright (c) 2016 by Contributors * \file graph_attr_types.cc * \brief Graph node data structure. */ #include <nnvm/graph.h> #include <nnvm/op_attr_types.h> #include <limits> namespace nnvm { const IndexedGraph& Graph::indexed_graph() const { if (indexed_graph_ == nullptr) { indexed_graph_.reset(new IndexedGraph(*this)); } return *indexed_graph_; } // a subgraph should not refer to any nodes with higher level // where "level" refers to the nested depth of the subgraph // e.g. the main graph is level 0 // subgraphs of the main graph is level 1 // subgraphs of the subgraphs of the main graph is level 2 static void SubgraphSanityCheck(const std::vector<std::shared_ptr<Symbol>> &subgraphs) { std::vector<const std::vector<nnvm::NodeEntry>*> curr_level; std::vector<const std::vector<nnvm::NodeEntry>*> next_level; std::unordered_map<nnvm::Node*, uint32_t> node2level; for (auto &subgraph : subgraphs) next_level.push_back(&subgraph->outputs); for (uint32_t level = 0; !next_level.empty(); ++level) { curr_level.swap(next_level); next_level.clear(); for (const std::vector<NodeEntry> *graph_ptr : curr_level) { const std::vector<NodeEntry> &graph = *graph_ptr; DFSVisit(graph, [&next_level, &node2level, level](const NodePtr& n) { nnvm::Node *node = n.get(); // if the node is visited, but on a different level, then check failed // if check failed here or before, we stop doing anything, but raise an error CHECK(!node2level.count(node) || node2level[node] == level) << "A subgraph should not depend on the outputs of nodes on higher levels"; // otherwise, this node belongs to the current level node2level[node] = level; // subgraphs of current node belongs to next level for (const auto& subgraph : n->attrs.subgraphs) { next_level.push_back(&subgraph->outputs); } }); } } } // implement constructor from graph IndexedGraph::IndexedGraph(const Graph &g) { entry_rptr_.push_back(0); std::vector<size_t> inputs_rptr{0}, control_rptr{0}; std::vector<std::shared_ptr<Symbol>> subgraphs; DFSVisit(g.outputs, [this, &inputs_rptr, &control_rptr, &subgraphs] (const NodePtr& n) { const auto& is_ghost = Op::GetAttr<TIsGhost>("TIsGhost"); if (!n->is_variable() && is_ghost.get(n->op(), false)) return; CHECK_LT(nodes_.size(), std::numeric_limits<uint32_t>::max()); uint32_t nid = static_cast<uint32_t>(nodes_.size()); CHECK(n); for (const auto &subgraph : n->attrs.subgraphs) subgraphs.push_back(subgraph); // nodes_ IndexedGraph::Node new_node; new_node.source = n.get(); new_node.weak_ref = n; nodes_.emplace_back(std::move(new_node)); // arg_nodes_ if (n->is_variable()) { input_nodes_.push_back(nid); } // node2index_ node2index_[n.get()] = nid; // entry rptr entry_rptr_.push_back(entry_rptr_.back() + n->num_outputs()); // input entries for (const auto& e : n->inputs) { auto it = node2index_.find(e.node.get()); CHECK(it != node2index_.end() && it->first == e.node.get()); input_entries_.emplace_back(NodeEntry{it->second, e.index, e.version}); } inputs_rptr.push_back(input_entries_.size()); // control deps for (const auto& nptr : n->control_deps) { if (!nptr->is_variable() && is_ghost.get(nptr->op(), false)) continue; auto it = node2index_.find(nptr.get()); CHECK(it != node2index_.end() && it->first == nptr.get()); control_deps_.push_back(it->second); } control_rptr.push_back(control_deps_.size()); }); if (!subgraphs.empty()) SubgraphSanityCheck(subgraphs); for (const auto& e : g.outputs) { outputs_.emplace_back(NodeEntry{ node2index_.at(e.node.get()), e.index, e.version}); } static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs"); // setup array view // input_entries_ and control_rptr must not change after this step. const NodeEntry* iptr = dmlc::BeginPtr(input_entries_); for (size_t nid = 0; nid < nodes_.size(); ++nid) { nodes_[nid].inputs = array_view<NodeEntry>( iptr + inputs_rptr[nid], iptr + inputs_rptr[nid + 1]); if (nodes_[nid].source->op() != nullptr && fmutate_inputs.count(nodes_[nid].source->op())) { for (uint32_t i : fmutate_inputs[nodes_[nid].source->op()](nodes_[nid].source->attrs)) { mutable_input_nodes_.insert(nodes_[nid].inputs[i].node_id); } } } const uint32_t* cptr = dmlc::BeginPtr(control_deps_); for (size_t nid = 0; nid < nodes_.size(); ++nid) { nodes_[nid].control_deps = array_view<uint32_t>( cptr + control_rptr[nid], cptr + control_rptr[nid + 1]); } } } // namespace nnvm <commit_msg>Minor improve to assertion (#3295)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*! * Copyright (c) 2016 by Contributors * \file graph_attr_types.cc * \brief Graph node data structure. */ #include <nnvm/graph.h> #include <nnvm/op_attr_types.h> #include <limits> namespace nnvm { const IndexedGraph& Graph::indexed_graph() const { if (indexed_graph_ == nullptr) { indexed_graph_.reset(new IndexedGraph(*this)); } return *indexed_graph_; } // a subgraph should not refer to any nodes with higher level // where "level" refers to the nested depth of the subgraph // e.g. the main graph is level 0 // subgraphs of the main graph is level 1 // subgraphs of the subgraphs of the main graph is level 2 static void SubgraphSanityCheck(const std::vector<std::shared_ptr<Symbol>> &subgraphs) { std::vector<const std::vector<nnvm::NodeEntry>*> curr_level; std::vector<const std::vector<nnvm::NodeEntry>*> next_level; std::unordered_map<nnvm::Node*, uint32_t> node2level; for (auto &subgraph : subgraphs) next_level.push_back(&subgraph->outputs); for (uint32_t level = 0; !next_level.empty(); ++level) { curr_level.swap(next_level); next_level.clear(); for (const std::vector<NodeEntry> *graph_ptr : curr_level) { const std::vector<NodeEntry> &graph = *graph_ptr; DFSVisit(graph, [&next_level, &node2level, level](const NodePtr& n) { nnvm::Node *node = n.get(); // if the node is visited, but on a different level, then check failed // if check failed here or before, we stop doing anything, but raise an error CHECK(!node2level.count(node) || node2level[node] == level) << "A subgraph should not depend on the outputs of nodes on higher levels"; // otherwise, this node belongs to the current level node2level[node] = level; // subgraphs of current node belongs to next level for (const auto& subgraph : n->attrs.subgraphs) { next_level.push_back(&subgraph->outputs); } }); } } } // implement constructor from graph IndexedGraph::IndexedGraph(const Graph &g) { entry_rptr_.push_back(0); std::vector<size_t> inputs_rptr{0}, control_rptr{0}; std::vector<std::shared_ptr<Symbol>> subgraphs; DFSVisit(g.outputs, [this, &inputs_rptr, &control_rptr, &subgraphs] (const NodePtr& n) { const auto& is_ghost = Op::GetAttr<TIsGhost>("TIsGhost"); if (!n->is_variable() && is_ghost.get(n->op(), false)) return; CHECK_LT(nodes_.size(), std::numeric_limits<uint32_t>::max()); uint32_t nid = static_cast<uint32_t>(nodes_.size()); CHECK(n); for (const auto &subgraph : n->attrs.subgraphs) subgraphs.push_back(subgraph); // nodes_ IndexedGraph::Node new_node; new_node.source = n.get(); new_node.weak_ref = n; nodes_.emplace_back(std::move(new_node)); // arg_nodes_ if (n->is_variable()) { input_nodes_.push_back(nid); } // node2index_ node2index_[n.get()] = nid; // entry rptr entry_rptr_.push_back(entry_rptr_.back() + n->num_outputs()); // input entries for (const auto& e : n->inputs) { auto it = node2index_.find(e.node.get()); CHECK(it != node2index_.end() && it->first == e.node.get()); input_entries_.emplace_back(NodeEntry{it->second, e.index, e.version}); } inputs_rptr.push_back(input_entries_.size()); // control deps for (const auto& nptr : n->control_deps) { if (!nptr->is_variable() && is_ghost.get(nptr->op(), false)) continue; auto it = node2index_.find(nptr.get()); CHECK(it != node2index_.end()) << "control dep not found in graph"; control_deps_.push_back(it->second); } control_rptr.push_back(control_deps_.size()); }); if (!subgraphs.empty()) SubgraphSanityCheck(subgraphs); for (const auto& e : g.outputs) { outputs_.emplace_back(NodeEntry{ node2index_.at(e.node.get()), e.index, e.version}); } static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs"); // setup array view // input_entries_ and control_rptr must not change after this step. const NodeEntry* iptr = dmlc::BeginPtr(input_entries_); for (size_t nid = 0; nid < nodes_.size(); ++nid) { nodes_[nid].inputs = array_view<NodeEntry>( iptr + inputs_rptr[nid], iptr + inputs_rptr[nid + 1]); if (nodes_[nid].source->op() != nullptr && fmutate_inputs.count(nodes_[nid].source->op())) { for (uint32_t i : fmutate_inputs[nodes_[nid].source->op()](nodes_[nid].source->attrs)) { mutable_input_nodes_.insert(nodes_[nid].inputs[i].node_id); } } } const uint32_t* cptr = dmlc::BeginPtr(control_deps_); for (size_t nid = 0; nid < nodes_.size(); ++nid) { nodes_[nid].control_deps = array_view<uint32_t>( cptr + control_rptr[nid], cptr + control_rptr[nid + 1]); } } } // namespace nnvm <|endoftext|>
<commit_before>#include <stdio.h> #include "PimAction.h" #include "PimSprite.h" #include "PimAssert.h" // Upon implementing the various Action subclasses, I noticed that most of the // code in the update-methods were structurally identical. The following macros // may seem large, inuntuitive and nasty (and frankly they are), but the amount // of duplicated code avoided by this method is in my opinion a worthy tradeoff. // // ACTION_UPDATE_RELATIVE: // Update macro for [verb]ToActions // // PARAMETERS: // _PARENT_TYPE: The type of the parent; Sprite, GameNode, etc. // _MEMBER: The member variable to change; position, scale, etc // _UPDATE_SET: Must be of type _MEMBER. Look at any usage for reference. // _FINAL_SET: Must be of type _MEMBER. Set the final value of _MEMBER. #define ACTION_UPDATE_STATIC(_PARENT_TYPE,_MEMBER,_UPDATE_SET,_FINAL_SET) \ timer -= dt; \ if (timer > 0.f ) \ { \ ((_PARENT_TYPE*)GetParent())->_MEMBER = _UPDATE_SET; \ } \ else \ { \ ((_PARENT_TYPE*)GetParent())->_MEMBER = _FINAL_SET; \ Cleanup(); \ } // // ACTION_UPDATE_RELATIVE: // Update macro for [verb]ByActions // // PARAMETERS: // _PARENT_TYPE: The type of the parent; Sprite, GameNode, etc. // _MEMBER: The member variable to change; position, scale, color, etc. // Note that the _MEMBER-type ABSOLUTELY MUST override the "+=" operator. // _UPDATE_VAR: Must be of type _MEMBER. Only pass the variable, it's multiplied by // 'dt' and '(1.f/dur)' in the macro. #define ACTION_UPDATE_RELATIVE(_PARENT_TYPE,_MEMBER,_UPDATE_VAR) \ bool ovride = false; \ if (timer > 0.f && timer - dt <= 0.f) \ { \ float tmp = timer; \ timer -= dt; \ dt = tmp; \ ovride = true; \ } \ else \ { \ timer -= dt; \ } \ if (timer > 0.f || ovride) \ { \ ((_PARENT_TYPE*)GetParent())->_MEMBER += _UPDATE_VAR *dt*(1.f/dur); \ if (ovride) /* override means we're done */ \ { \ Cleanup(); \ } \ } \ else \ { \ Cleanup(); \ } namespace Pim { /* ===================== BaseAction::BaseAction ===================== */ BaseAction::BaseAction(float duration) { done = false; inQueue = false; notifyOnCompletion = false; queue = NULL; notificationCallback = NULL; dur = duration; timer = duration; initialDur = duration; } /* ===================== BaseAction::Cleanup ===================== */ void BaseAction::Cleanup() { if (notifyOnCompletion) { notificationCallback->OnActionCompleted(this); } if (inQueue) { done = true; UnlistenFrame(); queue->ActivateNext(); } else { GetParent()->RemoveChild(this); } } /* ===================== Action::Action ===================== */ void Action::Activate() { PimAssert(GetParent() != NULL, "Action is orphan"); ListenFrame(); if (!notificationCallback) { notificationCallback = GetParent(); } } /* ===================== MoveToAction::MoveToAction ===================== */ MoveToAction::MoveToAction(Vec2 destination, float duration) : Action(duration) { dest = destination; } /* ===================== MoveToAction::Activate ===================== */ void MoveToAction::Activate() { Action::Activate(); start = GetParent()->position; } /* ===================== MoveToAction::Update ===================== */ void MoveToAction::Update(float dt) { ACTION_UPDATE_STATIC( GameNode, position, Vec2( dest.x + (start.x-dest.x) * (timer/dur), dest.y + (start.y-dest.y) * (timer/dur) ), dest ); } /* ===================== MoveByAction::MoveByAction ===================== */ MoveByAction::MoveByAction(Vec2 relative, float duration) : Action(duration) { rel = relative; } /* ===================== MoveByAction::Activate ===================== */ void MoveByAction::Activate() { Action::Activate(); } /* ===================== MoveByAction::Update ===================== */ void MoveByAction::Update(float dt) { ACTION_UPDATE_RELATIVE(GameNode, position, rel); } /* ===================== RotateByAction::RotateByAction ===================== */ RotateByAction::RotateByAction(float angle, float duration) : Action(duration) { total = angle; dir = angle / abs(angle); } /* ===================== RotateByAction::Activate ===================== */ void RotateByAction::Activate() { Action::Activate(); remainding = total; } /* ===================== RotateByAction::Update ===================== */ void RotateByAction::Update(float dt) { ACTION_UPDATE_RELATIVE(GameNode, rotation, total); } /* ===================== DelayAction::DelayAction ===================== */ DelayAction::DelayAction(float duration) : Action(duration) { } /* ===================== DelayAction::Activate ===================== */ void DelayAction::Activate() { Action::Activate(); } /* ===================== DelayAction::Update ===================== */ void DelayAction::Update(float dt) { timer -= dt; if (timer <= 0.f) { Cleanup(); } } /* ===================== SpriteAction::Activate ===================== */ void SpriteAction::Activate() { PimAssert(GetParent() != NULL, "Action is orphan"); PimAssert(dynamic_cast<Sprite*>(GetParent()) != NULL, "Cannot add a Sprite-action to a non-sprite node!"); ListenFrame(); if (!notificationCallback) { notificationCallback = GetParent(); } } /* ===================== TintAction::TintAction ===================== */ TintAction::TintAction(Color fadeTo, float duration) : SpriteAction(duration) { dest = fadeTo; } /* ===================== TintAction::Activate ===================== */ void TintAction::Activate() { SpriteAction::Activate(); source = ((Sprite*)GetParent())->color; } /* ===================== TintAction::Update ===================== */ void TintAction::Update(float dt) { ACTION_UPDATE_STATIC( Sprite, color, Color( dest.r + (source.r-dest.r) * (timer/dur), dest.g + (source.g-dest.g) * (timer/dur), dest.b + (source.b-dest.b) * (timer/dur), dest.a + (source.a-dest.a) * (timer/dur) ), dest ); } /* ===================== ScaleToAction::ScaleToAction ===================== */ ScaleToAction::ScaleToAction(Vec2 factor, float duration) : SpriteAction(duration) { dest = factor; } /* ===================== ScaleToAction::Activate ===================== */ void ScaleToAction::Activate() { SpriteAction::Activate(); source = ((Sprite*)GetParent())->scale; } /* ===================== ScaleToAction::Update ===================== */ void ScaleToAction::Update(float dt) { ACTION_UPDATE_STATIC( Sprite, scale, Vec2( dest.x + (source.x-dest.x) * (timer/dur), dest.y + (source.y-dest.y) * (timer/dur) ), dest ); } /* ===================== ScaleByAction::ScaleByAction ===================== */ ScaleByAction::ScaleByAction(Vec2 factor, float duration) : SpriteAction(duration) { remainding = factor; } /* ===================== ScaleByAction::Activate ===================== */ void ScaleByAction::Activate() { SpriteAction::Activate(); } /* ===================== ScaleByAction::Update ===================== */ void ScaleByAction::Update(float dt) { ACTION_UPDATE_RELATIVE(Sprite, scale, remainding); } /* ===================== ActionQueue::ActionQueue ===================== */ ActionQueue::ActionQueue(int numAct, BaseAction *act1, ...) : Action(0.f) { PimAssert(numAct != 0, "No actions / invalid num provided to ActionQueue"); PimAssert(numAct < 32, "ActionQueues does not support more than 32 actions"); curAct = NULL; actions.push_back(act1); act1->inQueue = true; act1->queue = this; va_list argp; va_start(argp, act1); for (int i=1; i<numAct; i++) { actions.push_back(va_arg(argp, BaseAction*)); actions[i]->inQueue = true; actions[i]->queue = this; } va_end(argp); } /* ===================== ActionQueue::~ActionQueue ===================== */ ActionQueue::~ActionQueue() { // Delete unplayed actions for (unsigned i=0; i<actions.size(); i++) { delete actions[i]; } actions.clear(); } /* ===================== ActionQueue::Activate ===================== */ void ActionQueue::Activate() { PimAssert(GetParent() != NULL, "Action is orphan"); ListenFrame(); ActivateNext(); } /* ===================== ActionQueue::Update ===================== */ void ActionQueue::Update(float dt) { if (done) { GetParent()->RemoveChild(this); } } /* ===================== ActionQueue::ActivateNext ===================== */ void ActionQueue::ActivateNext() { if (actions.size() != 0) { float excess = 0.f; if (curAct) { excess = curAct->timer; if (parent) { parent->RemoveChild(curAct); } } curAct = actions[0]; actions.pop_front(); curAct->dur += excess; curAct->timer += excess; if (parent) { parent->AddChild(curAct); curAct->Activate(); } } else { curAct = NULL; done = true; } } /* ===================== ActionQueueRepeat::ActionQueueRepeat ===================== */ ActionQueueRepeat::ActionQueueRepeat(unsigned int repNum, int numAct, BaseAction *act1, ...) { // Code duplication from ActionQueue::ActionQueue(...). // Variable arguments proved difficult to pass on. PimAssert(numAct != 0, "No actions / invalid num provided to ActionQueue"); PimAssert(numAct < 32, "ActionQueues does not support more than 32 actions"); curAct = NULL; actions.push_back(act1); act1->inQueue = true; act1->queue = this; va_list argp; va_start(argp, act1); for (int i=1; i<numAct; i++) { actions.push_back(va_arg(argp, BaseAction*)); actions[i]->inQueue = true; actions[i]->queue = this; } va_end(argp); // Custom init actionIdx = -1; // gets incremented in activateNext() remaindingLoops = repNum; infinite = false; } /* ===================== ActionQueueRepeat::~ActionQueueRepeat ===================== */ ActionQueueRepeat::~ActionQueueRepeat() { if (curAct) { // Everything in the actions-deque is deleted in ActionQueue's // destructor - to avoid the ActionQueue AND the parent of curAct // attempting to delete it, it's removed from the actions-deque. for (unsigned i=0; i<actions.size(); i++) { if (actions[i] == curAct) { actions.erase(actions.begin() + i); if (parent) { parent->RemoveChild(curAct); } } } } } /* ===================== ActionQueueRepeat::ActivateNext ===================== */ void ActionQueueRepeat::ActivateNext() { if (willDelete) return; // Update the action counters if (unsigned(++actionIdx) >= actions.size()) { actionIdx = 0; if (!infinite) { remaindingLoops--; } } if (infinite || remaindingLoops > 0) { float excess = 0.f; if (curAct) { excess = curAct->timer; // The action is not deleted. if (parent) { GetParent()->RemoveChild(curAct, false); } curAct->UnlistenFrame(); } // Prepare the next action curAct = actions[actionIdx]; curAct->timer = curAct->initialDur + excess; curAct->dur = curAct->initialDur + excess; curAct->done = false; // Run the next action if (parent) { GetParent()->AddChild(curAct); curAct->Activate(); } curAct->Update(-excess); } else { done = true; } } }<commit_msg>Added conditional detachment from parent in BaseAction::Cleanup<commit_after>#include <stdio.h> #include "PimAction.h" #include "PimSprite.h" #include "PimAssert.h" // Upon implementing the various Action subclasses, I noticed that most of the // code in the update-methods were structurally identical. The following macros // may seem large, inuntuitive and nasty (and frankly they are), but the amount // of duplicated code avoided by this method is in my opinion a worthy tradeoff. // // ACTION_UPDATE_RELATIVE: // Update macro for [verb]ToActions // // PARAMETERS: // _PARENT_TYPE: The type of the parent; Sprite, GameNode, etc. // _MEMBER: The member variable to change; position, scale, etc // _UPDATE_SET: Must be of type _MEMBER. Look at any usage for reference. // _FINAL_SET: Must be of type _MEMBER. Set the final value of _MEMBER. #define ACTION_UPDATE_STATIC(_PARENT_TYPE,_MEMBER,_UPDATE_SET,_FINAL_SET) \ timer -= dt; \ if (timer > 0.f ) \ { \ ((_PARENT_TYPE*)GetParent())->_MEMBER = _UPDATE_SET; \ } \ else \ { \ ((_PARENT_TYPE*)GetParent())->_MEMBER = _FINAL_SET; \ Cleanup(); \ } // // ACTION_UPDATE_RELATIVE: // Update macro for [verb]ByActions // // PARAMETERS: // _PARENT_TYPE: The type of the parent; Sprite, GameNode, etc. // _MEMBER: The member variable to change; position, scale, color, etc. // Note that the _MEMBER-type ABSOLUTELY MUST override the "+=" operator. // _UPDATE_VAR: Must be of type _MEMBER. Only pass the variable, it's multiplied by // 'dt' and '(1.f/dur)' in the macro. #define ACTION_UPDATE_RELATIVE(_PARENT_TYPE,_MEMBER,_UPDATE_VAR) \ bool ovride = false; \ if (timer > 0.f && timer - dt <= 0.f) \ { \ float tmp = timer; \ timer -= dt; \ dt = tmp; \ ovride = true; \ } \ else \ { \ timer -= dt; \ } \ if (timer > 0.f || ovride) \ { \ ((_PARENT_TYPE*)GetParent())->_MEMBER += _UPDATE_VAR *dt*(1.f/dur); \ if (ovride) /* override means we're done */ \ { \ Cleanup(); \ } \ } \ else \ { \ Cleanup(); \ } namespace Pim { /* ===================== BaseAction::BaseAction ===================== */ BaseAction::BaseAction(float duration) { done = false; inQueue = false; notifyOnCompletion = false; queue = NULL; notificationCallback = NULL; dur = duration; timer = duration; initialDur = duration; } /* ===================== BaseAction::Cleanup ===================== */ void BaseAction::Cleanup() { if (notifyOnCompletion) { notificationCallback->OnActionCompleted(this); } if (inQueue) { done = true; UnlistenFrame(); queue->ActivateNext(); } else { if (GetParent()) { GetParent()->RemoveChild(this); } } } /* ===================== Action::Action ===================== */ void Action::Activate() { PimAssert(GetParent() != NULL, "Action is orphan"); ListenFrame(); if (!notificationCallback) { notificationCallback = GetParent(); } } /* ===================== MoveToAction::MoveToAction ===================== */ MoveToAction::MoveToAction(Vec2 destination, float duration) : Action(duration) { dest = destination; } /* ===================== MoveToAction::Activate ===================== */ void MoveToAction::Activate() { Action::Activate(); start = GetParent()->position; } /* ===================== MoveToAction::Update ===================== */ void MoveToAction::Update(float dt) { ACTION_UPDATE_STATIC( GameNode, position, Vec2( dest.x + (start.x-dest.x) * (timer/dur), dest.y + (start.y-dest.y) * (timer/dur) ), dest ); } /* ===================== MoveByAction::MoveByAction ===================== */ MoveByAction::MoveByAction(Vec2 relative, float duration) : Action(duration) { rel = relative; } /* ===================== MoveByAction::Activate ===================== */ void MoveByAction::Activate() { Action::Activate(); } /* ===================== MoveByAction::Update ===================== */ void MoveByAction::Update(float dt) { ACTION_UPDATE_RELATIVE(GameNode, position, rel); } /* ===================== RotateByAction::RotateByAction ===================== */ RotateByAction::RotateByAction(float angle, float duration) : Action(duration) { total = angle; dir = angle / abs(angle); } /* ===================== RotateByAction::Activate ===================== */ void RotateByAction::Activate() { Action::Activate(); remainding = total; } /* ===================== RotateByAction::Update ===================== */ void RotateByAction::Update(float dt) { ACTION_UPDATE_RELATIVE(GameNode, rotation, total); } /* ===================== DelayAction::DelayAction ===================== */ DelayAction::DelayAction(float duration) : Action(duration) { } /* ===================== DelayAction::Activate ===================== */ void DelayAction::Activate() { Action::Activate(); } /* ===================== DelayAction::Update ===================== */ void DelayAction::Update(float dt) { timer -= dt; if (timer <= 0.f) { Cleanup(); } } /* ===================== SpriteAction::Activate ===================== */ void SpriteAction::Activate() { PimAssert(GetParent() != NULL, "Action is orphan"); PimAssert(dynamic_cast<Sprite*>(GetParent()) != NULL, "Cannot add a Sprite-action to a non-sprite node!"); ListenFrame(); if (!notificationCallback) { notificationCallback = GetParent(); } } /* ===================== TintAction::TintAction ===================== */ TintAction::TintAction(Color fadeTo, float duration) : SpriteAction(duration) { dest = fadeTo; } /* ===================== TintAction::Activate ===================== */ void TintAction::Activate() { SpriteAction::Activate(); source = ((Sprite*)GetParent())->color; } /* ===================== TintAction::Update ===================== */ void TintAction::Update(float dt) { ACTION_UPDATE_STATIC( Sprite, color, Color( dest.r + (source.r-dest.r) * (timer/dur), dest.g + (source.g-dest.g) * (timer/dur), dest.b + (source.b-dest.b) * (timer/dur), dest.a + (source.a-dest.a) * (timer/dur) ), dest ); } /* ===================== ScaleToAction::ScaleToAction ===================== */ ScaleToAction::ScaleToAction(Vec2 factor, float duration) : SpriteAction(duration) { dest = factor; } /* ===================== ScaleToAction::Activate ===================== */ void ScaleToAction::Activate() { SpriteAction::Activate(); source = ((Sprite*)GetParent())->scale; } /* ===================== ScaleToAction::Update ===================== */ void ScaleToAction::Update(float dt) { ACTION_UPDATE_STATIC( Sprite, scale, Vec2( dest.x + (source.x-dest.x) * (timer/dur), dest.y + (source.y-dest.y) * (timer/dur) ), dest ); } /* ===================== ScaleByAction::ScaleByAction ===================== */ ScaleByAction::ScaleByAction(Vec2 factor, float duration) : SpriteAction(duration) { remainding = factor; } /* ===================== ScaleByAction::Activate ===================== */ void ScaleByAction::Activate() { SpriteAction::Activate(); } /* ===================== ScaleByAction::Update ===================== */ void ScaleByAction::Update(float dt) { ACTION_UPDATE_RELATIVE(Sprite, scale, remainding); } /* ===================== ActionQueue::ActionQueue ===================== */ ActionQueue::ActionQueue(int numAct, BaseAction *act1, ...) : Action(0.f) { PimAssert(numAct != 0, "No actions / invalid num provided to ActionQueue"); PimAssert(numAct < 32, "ActionQueues does not support more than 32 actions"); curAct = NULL; actions.push_back(act1); act1->inQueue = true; act1->queue = this; va_list argp; va_start(argp, act1); for (int i=1; i<numAct; i++) { actions.push_back(va_arg(argp, BaseAction*)); actions[i]->inQueue = true; actions[i]->queue = this; } va_end(argp); } /* ===================== ActionQueue::~ActionQueue ===================== */ ActionQueue::~ActionQueue() { // Delete unplayed actions for (unsigned i=0; i<actions.size(); i++) { delete actions[i]; } actions.clear(); } /* ===================== ActionQueue::Activate ===================== */ void ActionQueue::Activate() { PimAssert(GetParent() != NULL, "Action is orphan"); ListenFrame(); ActivateNext(); } /* ===================== ActionQueue::Update ===================== */ void ActionQueue::Update(float dt) { if (done) { GetParent()->RemoveChild(this); } } /* ===================== ActionQueue::ActivateNext ===================== */ void ActionQueue::ActivateNext() { if (actions.size() != 0) { float excess = 0.f; if (curAct) { excess = curAct->timer; if (parent) { parent->RemoveChild(curAct); } } curAct = actions[0]; actions.pop_front(); curAct->dur += excess; curAct->timer += excess; if (parent) { parent->AddChild(curAct); curAct->Activate(); } } else { curAct = NULL; done = true; } } /* ===================== ActionQueueRepeat::ActionQueueRepeat ===================== */ ActionQueueRepeat::ActionQueueRepeat(unsigned int repNum, int numAct, BaseAction *act1, ...) { // Code duplication from ActionQueue::ActionQueue(...). // Variable arguments proved difficult to pass on. PimAssert(numAct != 0, "No actions / invalid num provided to ActionQueue"); PimAssert(numAct < 32, "ActionQueues does not support more than 32 actions"); curAct = NULL; actions.push_back(act1); act1->inQueue = true; act1->queue = this; va_list argp; va_start(argp, act1); for (int i=1; i<numAct; i++) { actions.push_back(va_arg(argp, BaseAction*)); actions[i]->inQueue = true; actions[i]->queue = this; } va_end(argp); // Custom init actionIdx = -1; // gets incremented in activateNext() remaindingLoops = repNum; infinite = false; } /* ===================== ActionQueueRepeat::~ActionQueueRepeat ===================== */ ActionQueueRepeat::~ActionQueueRepeat() { if (curAct) { // Everything in the actions-deque is deleted in ActionQueue's // destructor - to avoid the ActionQueue AND the parent of curAct // attempting to delete it, it's removed from the actions-deque. for (unsigned i=0; i<actions.size(); i++) { if (actions[i] == curAct) { actions.erase(actions.begin() + i); if (parent) { parent->RemoveChild(curAct); } } } } } /* ===================== ActionQueueRepeat::ActivateNext ===================== */ void ActionQueueRepeat::ActivateNext() { if (willDelete) return; // Update the action counters if (unsigned(++actionIdx) >= actions.size()) { actionIdx = 0; if (!infinite) { remaindingLoops--; } } if (infinite || remaindingLoops > 0) { float excess = 0.f; if (curAct) { excess = curAct->timer; // The action is not deleted. if (parent) { GetParent()->RemoveChild(curAct, false); } curAct->UnlistenFrame(); } // Prepare the next action curAct = actions[actionIdx]; curAct->timer = curAct->initialDur + excess; curAct->dur = curAct->initialDur + excess; curAct->done = false; // Run the next action if (parent) { GetParent()->AddChild(curAct); curAct->Activate(); } curAct->Update(-excess); } else { done = true; } } }<|endoftext|>
<commit_before>#include <iostream> #include "structs.h" using namespace std; int main(void) { // The default constructor for a struct just zeroes the values Vec3 v = Vec3(); Vec3 vprime = Vec3(); Vec2 w = Vec2(); cout << "-----Pass by value test-----" << endl; cout << "Original 3 vector:" << endl; print_vec(v); vprime = set_vec(v, 1.0, 2.0, 3.0); cout << "Original 3 vector after modification:" << endl; print_vec(v); cout << "New 3 vector after modification:" << endl; print_vec(vprime); cout << "-----Pass by reference test-----" << endl; cout << "Original 2 vector:" << endl; print_vec(w); set_vec(w, 1.0, 2.0); cout << "Original 2 vector after modification:" << endl; print_vec(w); return 0; } Vec3 set_vec(Vec3 v, Component x, Component y, Component z) { // Local value v is a copy of the original v v.x = x; v.y = y; v.z = z; return v; } void set_vec(Vec2 &wr, Component x, Component y) { // Local reference wr refers directly to original memory location wr.x = x; wr.y = y; } void print_vec(const Vec3 v) { cout << "3-Vector : [" << v.x << ", " << v.y << ", " << v.z << "]" << endl; } void print_vec(const Vec2 &wr) { // Passing in a reference wr prevents unnecessary memory copying cout << "2Vector : [" << wr.x << ", " << wr.y << "]" << endl; } //TODO : Implement overloaded + operators <commit_msg>structs.cc<commit_after>#include <iostream> #include "structs.h" using namespace std; int main(void) { // The default constructor for a struct just zeroes the values Vec3 v = Vec3(); Vec3 vprime = Vec3(); Vec2 w = Vec2(); cout << "-----Pass by value test-----" << endl; cout << "Original 3 vector:" << endl; print_vec(v); vprime = set_vec(v, 1.0, 2.0, 3.0); cout << "Original 3 vector after modification:" << endl; print_vec(v); cout << "New 3 vector after modification:" << endl; print_vec(vprime); cout << "-----Pass by reference test-----" << endl; cout << "Original 2 vector:" << endl; print_vec(w); set_vec(w, 1.0, 2.0); cout << "Original 2 vector after modification:" << endl; print_vec(w); cout << "-----Operator+ Vec3 test-----" << endl; cout << "Original 3 vector:" << endl; print_vec(vprime); cout << "The sum of two vprimes is:" << endl; print_vec(vprime + vprime); cout << "-----Operator+ Vec2 test-----" << endl; cout << "Original 2 vector:" << endl; print_vec(w); cout << "The sum of two vprimes is:" << endl; print_vec(w + w); return 0; } Vec3 set_vec(Vec3 v, Component x, Component y, Component z) { // Local value v is a copy of the original v v.x = x; v.y = y; v.z = z; return v; } void set_vec(Vec2 &wr, Component x, Component y) { // Local reference wr refers directly to original memory location wr.x = x; wr.y = y; } void print_vec(const Vec3 v) { cout << "3-Vector : [" << v.x << ", " << v.y << ", " << v.z << "]" << endl; } void print_vec(const Vec2 &wr) { // Passing in a reference wr prevents unnecessary memory copying cout << "2Vector : [" << wr.x << ", " << wr.y << "]" << endl; } //TODO : Implement overloaded + operators Vec3 operator+(const Vec3& a, const Vec3& b) { Vec3 sum3; sum3.x = a.x + b.x; sum3.y = a.y + b.y; sum3.z = a.z + b.z; return sum3; } Vec2 operator+(const Vec2& c, const Vec2& d) { Vec2 sum2; sum2.x = c.x + d.x; sum2.y = c.y + d.y; return sum2; } <|endoftext|>
<commit_before>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <boost/python.hpp> #include <boost/optional.hpp> #include <nix.hpp> #include <accessors.hpp> #include <transmorgify.hpp> #include <iostream> #include <PyEntity.hpp> using namespace nix; using namespace boost::python; namespace nixpy { // getter for Section boost::optional<Section> getSectionById(const Section& section, const std::string& id) { Section sec = section.getSection(id); return sec ? boost::optional<Section>(sec) : boost::none; } boost::optional<Section> getSectionByPos(const Section& section, size_t index) { Section sec = section.getSection(index); return sec ? boost::optional<Section>(sec) : boost::none; } // Property Property createProperty(Section& sec, const std::string& name, PyObject* obj) { extract<DataType> ext_type(obj); if (ext_type.check()) { return sec.createProperty(name, ext_type()); } extract<Value&> ext_val(obj); if (ext_val.check()) { return sec.createProperty(name, ext_val()); } extract<std::vector<Value>> ext_vec(obj); if (ext_vec.check()) { return sec.createProperty(name, ext_vec()); } throw new std::runtime_error("Second parameter must be a Value, list of Value or DataType"); } boost::optional<Property> getPropertyById(const Section& section, const std::string& id) { Property prop = section.getProperty(id); return prop ? boost::optional<Property>(prop) : boost::none; } boost::optional<Property> getPropertyByPos(const Section& section, size_t index) { Property prop = section.getProperty(index); return prop ? boost::optional<Property>(prop) : boost::none; } boost::optional<Property> getPropertyByName(const Section& section, const std::string& name) { Property prop = section.getProperty(name); return prop ? boost::optional<Property>(prop) : boost::none; } bool hasPropertyByName(const Section& section, const std::string& name) { return section.hasProperty(name); } // Repository void setRepository(Section& sec, const boost::optional<std::string>& str) { if (str) sec.repository(*str); else sec.repository(boost::none); } // Mapping void setMapping(Section& sec, const boost::optional<std::string>& str) { if (str) sec.mapping(*str); else sec.mapping(boost::none); } // Link void setLink(Section& section, const boost::optional<Section>& link) { if (link && *link) section.link(*link); else section.link(boost::none); } boost::optional<Section> getLink(const Section& sec) { Section link = sec.link(); return link ? boost::optional<Section>(link) : boost::none; } // Parent boost::optional<Section> getParent(const Section& sec) { Section parent = sec.parent(); return parent ? boost::optional<Section>(parent) : boost::none; } void PySection::do_export() { PyNamedEntity<base::ISection>::do_export("Section"); class_<Section, bases<base::NamedEntity<base::ISection>>>("Section") // Properties .add_property("repository", OPT_GETTER(std::string, Section, repository), setRepository, doc::section_repository) .add_property("mapping", OPT_GETTER(std::string, Section, mapping), setMapping, doc::section_mapping) .add_property("link", getLink, setLink, doc::section_link) // Section .add_property("parent", getParent, doc::section_parent) .def("create_section", &Section::createSection, doc::section_create_section) .def("_section_count", &Section::sectionCount) .def("_get_section_by_id", &getSectionById) .def("_get_section_by_pos", &getSectionByPos) .def("_delete_section_by_id", REMOVER(std::string, nix::Section, deleteSection)) // Property .def("_create_property", createProperty) .def("has_property_by_name", hasPropertyByName, doc::section_has_property_by_name) .def("get_property_by_name", getPropertyByName, doc::section_get_property_by_name) .def("_property_count", &Section::propertyCount) .def("_get_property_by_id", &getPropertyById) .def("_get_property_by_pos", &getPropertyByPos) .def("_delete_property_by_id", REMOVER(std::string, nix::Section, deleteProperty)) .def("inherited_properties", &Section::inheritedProperties) // Other .def("__str__", &toStr<Section>) .def("__repr__", &toStr<Section>) ; to_python_converter<std::vector<Section>, vector_transmogrify<Section>>(); to_python_converter<boost::optional<Section>, option_transmogrify<Section>>(); option_transmogrify<Section>::register_from_python(); } } <commit_msg>createProperty accepts Python values, not nix::Value<commit_after>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <boost/python.hpp> #include <boost/optional.hpp> #include <nix.hpp> #include <accessors.hpp> #include <transmorgify.hpp> #include <iostream> #include <PyEntity.hpp> using namespace nix; using namespace boost::python; namespace nixpy { // getter for Section boost::optional<Section> getSectionById(const Section& section, const std::string& id) { Section sec = section.getSection(id); return sec ? boost::optional<Section>(sec) : boost::none; } boost::optional<Section> getSectionByPos(const Section& section, size_t index) { Section sec = section.getSection(index); return sec ? boost::optional<Section>(sec) : boost::none; } // Property Property createProperty(Section& sec, const std::string& name, list& valuelist) { std::vector<Value> nixvaluelist; for (int idx = 0; idx < len(valuelist); ++idx) { nixvaluelist.push_back(Value(object(valuelist[idx]))); } return sec.createProperty(name, nixvaluelist); } Property createProperty(Section& sec, const std::string& name, PyObject* value) { Value nixvalue; if (PyBool_Check(value)) { bool conv = extract<bool>(value); nixvalue = Value(conv); #if PY_MAJOR_VERSION >= 3 } else if (PyLong_Check(value)) { #else } else if (PyInt_Check(value)) { #endif int64_t conv = extract<int64_t>(value); nixvalue = Value(conv); } else if (PyFloat_Check(value)) { double conv = extract<double>(value); nixvalue = Value(conv); #if PY_MAJOR_VERSION >= 3 } else if (PyUnicode_Check(value)) { #else } else if (PyString_Check(value)) { #endif std::string conv = extract<std::string>(value); nixvalue = Value(conv); } else { throw std::runtime_error("Wrong type"); } return sec.createProperty(name, nixvalue); } Property (*createPropertyValue)(Section&, const std::string&, PyObject*) = createProperty; Property (*createPropertyList)(Section&, const std::string&, boost::python::list&) = createProperty; //Property createProperty(Section& sec, const std::string& name, PyObject* obj) { // extract<DataType> ext_type(obj); // if (ext_type.check()) { // return sec.createProperty(name, ext_type()); // } // // extract<Value&> ext_val(obj); // if (ext_val.check()) { // return sec.createProperty(name, ext_val()); // } // // extract<std::vector<Value>> ext_vec(obj); // if (ext_vec.check()) { // return sec.createProperty(name, ext_vec()); // } // // throw new std::runtime_error("Second parameter must be a Value, list of Value or DataType"); //} boost::optional<Property> getPropertyById(const Section& section, const std::string& id) { Property prop = section.getProperty(id); return prop ? boost::optional<Property>(prop) : boost::none; } boost::optional<Property> getPropertyByPos(const Section& section, size_t index) { Property prop = section.getProperty(index); return prop ? boost::optional<Property>(prop) : boost::none; } boost::optional<Property> getPropertyByName(const Section& section, const std::string& name) { Property prop = section.getProperty(name); return prop ? boost::optional<Property>(prop) : boost::none; } bool hasPropertyByName(const Section& section, const std::string& name) { return section.hasProperty(name); } // Repository void setRepository(Section& sec, const boost::optional<std::string>& str) { if (str) sec.repository(*str); else sec.repository(boost::none); } // Mapping void setMapping(Section& sec, const boost::optional<std::string>& str) { if (str) sec.mapping(*str); else sec.mapping(boost::none); } // Link void setLink(Section& section, const boost::optional<Section>& link) { if (link && *link) section.link(*link); else section.link(boost::none); } boost::optional<Section> getLink(const Section& sec) { Section link = sec.link(); return link ? boost::optional<Section>(link) : boost::none; } // Parent boost::optional<Section> getParent(const Section& sec) { Section parent = sec.parent(); return parent ? boost::optional<Section>(parent) : boost::none; } void PySection::do_export() { PyNamedEntity<base::ISection>::do_export("Section"); class_<Section, bases<base::NamedEntity<base::ISection>>>("Section") // Properties .add_property("repository", OPT_GETTER(std::string, Section, repository), setRepository, doc::section_repository) .add_property("mapping", OPT_GETTER(std::string, Section, mapping), setMapping, doc::section_mapping) .add_property("link", getLink, setLink, doc::section_link) // Section .add_property("parent", getParent, doc::section_parent) .def("create_section", &Section::createSection, doc::section_create_section) .def("_section_count", &Section::sectionCount) .def("_get_section_by_id", &getSectionById) .def("_get_section_by_pos", &getSectionByPos) .def("_delete_section_by_id", REMOVER(std::string, nix::Section, deleteSection)) // Property .def("_create_property", createPropertyValue) .def("_create_property", createPropertyList) .def("has_property_by_name", hasPropertyByName, doc::section_has_property_by_name) .def("get_property_by_name", getPropertyByName, doc::section_get_property_by_name) .def("_property_count", &Section::propertyCount) .def("_get_property_by_id", &getPropertyById) .def("_get_property_by_pos", &getPropertyByPos) .def("_delete_property_by_id", REMOVER(std::string, nix::Section, deleteProperty)) .def("inherited_properties", &Section::inheritedProperties) // Other .def("__str__", &toStr<Section>) .def("__repr__", &toStr<Section>) ; to_python_converter<std::vector<Section>, vector_transmogrify<Section>>(); to_python_converter<boost::optional<Section>, option_transmogrify<Section>>(); option_transmogrify<Section>::register_from_python(); } } <|endoftext|>
<commit_before>/* * This file is part of liblcf. Copyright (c) 2017 liblcf authors. * https://github.com/EasyRPG/liblcf - https://easyrpg.org * * liblcf is Free/Libre Open Source Software, released under the MIT License. * For the full copyright and license information, please view the COPYING * file that was distributed with this source code. */ #include <cstring> #include <iostream> #include <iomanip> #include <type_traits> #include "ldb_reader.h" #include "lmt_reader.h" #include "lmu_reader.h" #include "lsd_reader.h" #include "reader_struct.h" #include "rpg_save.h" #include "data.h" // Read/Write Struct template <class S> void Struct<S>::MakeFieldMap() { if (!field_map.empty()) return; for (int i = 0; fields[i] != NULL; i++) field_map[fields[i]->id] = fields[i]; } template <class S> void Struct<S>::MakeTagMap() { if (!tag_map.empty()) return; for (int i = 0; fields[i] != NULL; i++) tag_map[fields[i]->name] = fields[i]; } template <typename T> struct StructDefault { static T make() { return T(); } }; template <> struct StructDefault<RPG::Actor> { static RPG::Actor make() { auto actor = RPG::Actor(); actor.Setup(); return actor; } }; template <class S> void Struct<S>::ReadLcf(S& obj, LcfReader& stream) { MakeFieldMap(); LcfReader::Chunk chunk_info; while (!stream.Eof()) { chunk_info.ID = stream.ReadInt(); if (chunk_info.ID == 0) break; chunk_info.length = stream.ReadInt(); if (chunk_info.length == 0) continue; typename field_map_type::const_iterator it = field_map.find(chunk_info.ID); if (it != field_map.end()) { #ifdef LCF_DEBUG_TRACE printf("0x%02x (size: %d, pos: 0x%x): %s\n", chunk_info.ID, chunk_info.length, stream.Tell(), it->second->name); #endif it->second->ReadLcf(obj, stream, chunk_info.length); } else stream.Skip(chunk_info); } } template<typename T> typename std::enable_if<std::is_same<T, RPG::Save>::value || std::is_same<T, RPG::Database>::value>::type conditional_zero_writer(LcfWriter&) { // no-op } template<typename T> typename std::enable_if<!std::is_same<T, RPG::Save>::value && !std::is_same<T, RPG::Database>::value>::type conditional_zero_writer(LcfWriter& stream) { stream.WriteInt(0); } template <class S> void Struct<S>::WriteLcf(const S& obj, LcfWriter& stream) { const bool db_is2k3 = (Data::system.ldb_id == 2003); auto ref = StructDefault<S>::make(); int last = -1; for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; if (!db_is2k3 && field->is2k3) { continue; } if (field->id < last) std::cerr << "field order mismatch: " << field->id << " after " << last << " in struct " << name << std::endl; if (field->IsDefault(obj, ref)) { continue; } stream.WriteInt(field->id); stream.WriteInt(field->LcfSize(obj, stream)); field->WriteLcf(obj, stream); } // Writing a 0-byte after RPG::Database or RPG::Save breaks the parser in RPG_RT conditional_zero_writer<S>(stream); } template <class S> int Struct<S>::LcfSize(const S& obj, LcfWriter& stream) { const bool db_is2k3 = (Data::system.ldb_id == 2003); int result = 0; auto ref = StructDefault<S>::make(); for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; if (!db_is2k3 && field->is2k3) { continue; } //printf("%s\n", field->name); if (field->IsDefault(obj, ref)) continue; result += LcfReader::IntSize(field->id); int size = field->LcfSize(obj, stream); result += LcfReader::IntSize(size); result += size; } result += LcfReader::IntSize(0); return result; } template <class S> void Struct<S>::WriteXml(const S& obj, XmlWriter& stream) { IDReader::WriteXmlTag(obj, name, stream); for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; field->WriteXml(obj, stream); } stream.EndElement(name); } template <class S> class StructXmlHandler : public XmlHandler { public: StructXmlHandler(S& ref) : ref(ref), field(NULL) { Struct<S>::MakeTagMap(); } void StartElement(XmlReader& stream, const char* name, const char** /* atts */) { field = Struct<S>::tag_map[name]; field->BeginXml(ref, stream); } void EndElement(XmlReader& /* stream */, const char* /* name */) { field = NULL; } void CharacterData(XmlReader& /* stream */, const std::string& data) { if (field != NULL) field->ParseXml(ref, data); } private: S& ref; const Field<S>* field; }; template <class S> class StructFieldXmlHandler : public XmlHandler { public: StructFieldXmlHandler(S& ref) : ref(ref) {} void StartElement(XmlReader& stream, const char* name, const char** atts) { if (strcmp(name, Struct<S>::name) != 0) stream.Error("Expecting %s but got %s", Struct<S>::name, name); Struct<S>::IDReader::ReadIDXml(ref, atts); stream.SetHandler(new StructXmlHandler<S>(ref)); } private: S& ref; }; template <class S> void Struct<S>::BeginXml(S& obj, XmlReader& stream) { stream.SetHandler(new StructFieldXmlHandler<S>(obj)); } // Read/Write std::vector<Struct> template <class S> void Struct<S>::ReadLcf(std::vector<S>& vec, LcfReader& stream) { int count = stream.ReadInt(); vec.resize(count); for (int i = 0; i < count; i++) { IDReader::ReadID(vec[i], stream); TypeReader<S>::ReadLcf(vec[i], stream, 0); } } template <class S> void Struct<S>::WriteLcf(const std::vector<S>& vec, LcfWriter& stream) { int count = vec.size(); stream.WriteInt(count); for (int i = 0; i < count; i++) { IDReader::WriteID(vec[i], stream); TypeReader<S>::WriteLcf(vec[i], stream); } } template <class S> int Struct<S>::LcfSize(const std::vector<S>& vec, LcfWriter& stream) { int result = 0; int count = vec.size(); result += LcfReader::IntSize(count); for (int i = 0; i < count; i++) { result += IDReader::IDSize(vec[i]); result += TypeReader<S>::LcfSize(vec[i], stream); } return result; } template <class S> void Struct<S>::WriteXml(const std::vector<S>& vec, XmlWriter& stream) { int count = vec.size(); for (int i = 0; i < count; i++) TypeReader<S>::WriteXml(vec[i], stream); } template <class S> class StructVectorXmlHandler : public XmlHandler { public: StructVectorXmlHandler(std::vector<S>& ref) : ref(ref) {} void StartElement(XmlReader& stream, const char* name, const char** atts) { if (strcmp(name, Struct<S>::name) != 0) stream.Error("Expecting %s but got %s", Struct<S>::name, name); ref.resize(ref.size() + 1); S& obj = ref.back(); Struct<S>::IDReader::ReadIDXml(obj, atts); stream.SetHandler(new StructXmlHandler<S>(obj)); } private: std::vector<S>& ref; }; template <class S> void Struct<S>::BeginXml(std::vector<S>& obj, XmlReader& stream) { stream.SetHandler(new StructVectorXmlHandler<S>(obj)); } // Instantiate templates #ifdef _MSC_VER #pragma warning (disable : 4661) #endif template class Struct<RPG::Actor>; template class Struct<RPG::Animation>; template class Struct<RPG::AnimationCellData>; template class Struct<RPG::AnimationFrame>; template class Struct<RPG::AnimationTiming>; template class Struct<RPG::Attribute>; template class Struct<RPG::BattleCommand>; template class Struct<RPG::BattleCommands>; template class Struct<RPG::BattlerAnimation>; template class Struct<RPG::BattlerAnimationData>; template class Struct<RPG::BattlerAnimationExtension>; template class Struct<RPG::Chipset>; template class Struct<RPG::Class>; template class Struct<RPG::CommonEvent>; template class Struct<RPG::Database>; template class Struct<RPG::Encounter>; template class Struct<RPG::Enemy>; template class Struct<RPG::EnemyAction>; template class Struct<RPG::Event>; template class Struct<RPG::EventPage>; template class Struct<RPG::EventPageCondition>; template class Struct<RPG::Item>; template class Struct<RPG::ItemAnimation>; template class Struct<RPG::Learning>; template class Struct<RPG::Map>; template class Struct<RPG::MapInfo>; template class Struct<RPG::MoveRoute>; template class Struct<RPG::Music>; template class Struct<RPG::Save>; template class Struct<RPG::SaveActor>; template class Struct<RPG::SaveCommonEvent>; template class Struct<RPG::SaveEventCommands>; template class Struct<RPG::SaveEventData>; template class Struct<RPG::SaveInventory>; template class Struct<RPG::SaveMapEvent>; template class Struct<RPG::SaveMapInfo>; template class Struct<RPG::SavePartyLocation>; template class Struct<RPG::SavePicture>; template class Struct<RPG::SaveScreen>; template class Struct<RPG::SaveSystem>; template class Struct<RPG::SaveTarget>; template class Struct<RPG::SaveTitle>; template class Struct<RPG::SaveVehicleLocation>; template class Struct<RPG::Skill>; template class Struct<RPG::Sound>; template class Struct<RPG::Start>; template class Struct<RPG::State>; template class Struct<RPG::Switch>; template class Struct<RPG::System>; template class Struct<RPG::Terms>; template class Struct<RPG::Terrain>; template class Struct<RPG::TestBattler>; template class Struct<RPG::Troop>; template class Struct<RPG::TroopMember>; template class Struct<RPG::TroopPage>; template class Struct<RPG::TroopPageCondition>; template class Struct<RPG::Variable>; <commit_msg>Detect corrupted chunks and reset the parser<commit_after>/* * This file is part of liblcf. Copyright (c) 2017 liblcf authors. * https://github.com/EasyRPG/liblcf - https://easyrpg.org * * liblcf is Free/Libre Open Source Software, released under the MIT License. * For the full copyright and license information, please view the COPYING * file that was distributed with this source code. */ #include <cstring> #include <iostream> #include <iomanip> #include <type_traits> #include "ldb_reader.h" #include "lmt_reader.h" #include "lmu_reader.h" #include "lsd_reader.h" #include "reader_struct.h" #include "rpg_save.h" #include "data.h" // Read/Write Struct template <class S> void Struct<S>::MakeFieldMap() { if (!field_map.empty()) return; for (int i = 0; fields[i] != NULL; i++) field_map[fields[i]->id] = fields[i]; } template <class S> void Struct<S>::MakeTagMap() { if (!tag_map.empty()) return; for (int i = 0; fields[i] != NULL; i++) tag_map[fields[i]->name] = fields[i]; } template <typename T> struct StructDefault { static T make() { return T(); } }; template <> struct StructDefault<RPG::Actor> { static RPG::Actor make() { auto actor = RPG::Actor(); actor.Setup(); return actor; } }; template <class S> void Struct<S>::ReadLcf(S& obj, LcfReader& stream) { MakeFieldMap(); LcfReader::Chunk chunk_info; while (!stream.Eof()) { chunk_info.ID = stream.ReadInt(); if (chunk_info.ID == 0) break; chunk_info.length = stream.ReadInt(); if (chunk_info.length == 0) continue; typename field_map_type::const_iterator it = field_map.find(chunk_info.ID); if (it != field_map.end()) { #ifdef LCF_DEBUG_TRACE printf("0x%02x (size: %d, pos: 0x%x): %s\n", chunk_info.ID, chunk_info.length, stream.Tell(), it->second->name); #endif const auto off = stream.Tell(); it->second->ReadLcf(obj, stream, chunk_info.length); const auto bytes_read = stream.Tell() - off; if (bytes_read != chunk_info.length) { fprintf(stderr, "Warning: Corrupted Chunk 0x%02x (size: %d, pos: 0x%x): %s : Read %d bytes! Reseting...\n", chunk_info.ID, chunk_info.length, off, it->second->name, bytes_read); stream.Seek(off + chunk_info.length); } } else { stream.Skip(chunk_info); } } } template<typename T> typename std::enable_if<std::is_same<T, RPG::Save>::value || std::is_same<T, RPG::Database>::value>::type conditional_zero_writer(LcfWriter&) { // no-op } template<typename T> typename std::enable_if<!std::is_same<T, RPG::Save>::value && !std::is_same<T, RPG::Database>::value>::type conditional_zero_writer(LcfWriter& stream) { stream.WriteInt(0); } template <class S> void Struct<S>::WriteLcf(const S& obj, LcfWriter& stream) { const bool db_is2k3 = (Data::system.ldb_id == 2003); auto ref = StructDefault<S>::make(); int last = -1; for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; if (!db_is2k3 && field->is2k3) { continue; } if (field->id < last) std::cerr << "field order mismatch: " << field->id << " after " << last << " in struct " << name << std::endl; if (field->IsDefault(obj, ref)) { continue; } stream.WriteInt(field->id); stream.WriteInt(field->LcfSize(obj, stream)); field->WriteLcf(obj, stream); } // Writing a 0-byte after RPG::Database or RPG::Save breaks the parser in RPG_RT conditional_zero_writer<S>(stream); } template <class S> int Struct<S>::LcfSize(const S& obj, LcfWriter& stream) { const bool db_is2k3 = (Data::system.ldb_id == 2003); int result = 0; auto ref = StructDefault<S>::make(); for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; if (!db_is2k3 && field->is2k3) { continue; } //printf("%s\n", field->name); if (field->IsDefault(obj, ref)) continue; result += LcfReader::IntSize(field->id); int size = field->LcfSize(obj, stream); result += LcfReader::IntSize(size); result += size; } result += LcfReader::IntSize(0); return result; } template <class S> void Struct<S>::WriteXml(const S& obj, XmlWriter& stream) { IDReader::WriteXmlTag(obj, name, stream); for (int i = 0; fields[i] != NULL; i++) { const Field<S>* field = fields[i]; field->WriteXml(obj, stream); } stream.EndElement(name); } template <class S> class StructXmlHandler : public XmlHandler { public: StructXmlHandler(S& ref) : ref(ref), field(NULL) { Struct<S>::MakeTagMap(); } void StartElement(XmlReader& stream, const char* name, const char** /* atts */) { field = Struct<S>::tag_map[name]; field->BeginXml(ref, stream); } void EndElement(XmlReader& /* stream */, const char* /* name */) { field = NULL; } void CharacterData(XmlReader& /* stream */, const std::string& data) { if (field != NULL) field->ParseXml(ref, data); } private: S& ref; const Field<S>* field; }; template <class S> class StructFieldXmlHandler : public XmlHandler { public: StructFieldXmlHandler(S& ref) : ref(ref) {} void StartElement(XmlReader& stream, const char* name, const char** atts) { if (strcmp(name, Struct<S>::name) != 0) stream.Error("Expecting %s but got %s", Struct<S>::name, name); Struct<S>::IDReader::ReadIDXml(ref, atts); stream.SetHandler(new StructXmlHandler<S>(ref)); } private: S& ref; }; template <class S> void Struct<S>::BeginXml(S& obj, XmlReader& stream) { stream.SetHandler(new StructFieldXmlHandler<S>(obj)); } // Read/Write std::vector<Struct> template <class S> void Struct<S>::ReadLcf(std::vector<S>& vec, LcfReader& stream) { int count = stream.ReadInt(); vec.resize(count); for (int i = 0; i < count; i++) { IDReader::ReadID(vec[i], stream); TypeReader<S>::ReadLcf(vec[i], stream, 0); } } template <class S> void Struct<S>::WriteLcf(const std::vector<S>& vec, LcfWriter& stream) { int count = vec.size(); stream.WriteInt(count); for (int i = 0; i < count; i++) { IDReader::WriteID(vec[i], stream); TypeReader<S>::WriteLcf(vec[i], stream); } } template <class S> int Struct<S>::LcfSize(const std::vector<S>& vec, LcfWriter& stream) { int result = 0; int count = vec.size(); result += LcfReader::IntSize(count); for (int i = 0; i < count; i++) { result += IDReader::IDSize(vec[i]); result += TypeReader<S>::LcfSize(vec[i], stream); } return result; } template <class S> void Struct<S>::WriteXml(const std::vector<S>& vec, XmlWriter& stream) { int count = vec.size(); for (int i = 0; i < count; i++) TypeReader<S>::WriteXml(vec[i], stream); } template <class S> class StructVectorXmlHandler : public XmlHandler { public: StructVectorXmlHandler(std::vector<S>& ref) : ref(ref) {} void StartElement(XmlReader& stream, const char* name, const char** atts) { if (strcmp(name, Struct<S>::name) != 0) stream.Error("Expecting %s but got %s", Struct<S>::name, name); ref.resize(ref.size() + 1); S& obj = ref.back(); Struct<S>::IDReader::ReadIDXml(obj, atts); stream.SetHandler(new StructXmlHandler<S>(obj)); } private: std::vector<S>& ref; }; template <class S> void Struct<S>::BeginXml(std::vector<S>& obj, XmlReader& stream) { stream.SetHandler(new StructVectorXmlHandler<S>(obj)); } // Instantiate templates #ifdef _MSC_VER #pragma warning (disable : 4661) #endif template class Struct<RPG::Actor>; template class Struct<RPG::Animation>; template class Struct<RPG::AnimationCellData>; template class Struct<RPG::AnimationFrame>; template class Struct<RPG::AnimationTiming>; template class Struct<RPG::Attribute>; template class Struct<RPG::BattleCommand>; template class Struct<RPG::BattleCommands>; template class Struct<RPG::BattlerAnimation>; template class Struct<RPG::BattlerAnimationData>; template class Struct<RPG::BattlerAnimationExtension>; template class Struct<RPG::Chipset>; template class Struct<RPG::Class>; template class Struct<RPG::CommonEvent>; template class Struct<RPG::Database>; template class Struct<RPG::Encounter>; template class Struct<RPG::Enemy>; template class Struct<RPG::EnemyAction>; template class Struct<RPG::Event>; template class Struct<RPG::EventPage>; template class Struct<RPG::EventPageCondition>; template class Struct<RPG::Item>; template class Struct<RPG::ItemAnimation>; template class Struct<RPG::Learning>; template class Struct<RPG::Map>; template class Struct<RPG::MapInfo>; template class Struct<RPG::MoveRoute>; template class Struct<RPG::Music>; template class Struct<RPG::Save>; template class Struct<RPG::SaveActor>; template class Struct<RPG::SaveCommonEvent>; template class Struct<RPG::SaveEventCommands>; template class Struct<RPG::SaveEventData>; template class Struct<RPG::SaveInventory>; template class Struct<RPG::SaveMapEvent>; template class Struct<RPG::SaveMapInfo>; template class Struct<RPG::SavePartyLocation>; template class Struct<RPG::SavePicture>; template class Struct<RPG::SaveScreen>; template class Struct<RPG::SaveSystem>; template class Struct<RPG::SaveTarget>; template class Struct<RPG::SaveTitle>; template class Struct<RPG::SaveVehicleLocation>; template class Struct<RPG::Skill>; template class Struct<RPG::Sound>; template class Struct<RPG::Start>; template class Struct<RPG::State>; template class Struct<RPG::Switch>; template class Struct<RPG::System>; template class Struct<RPG::Terms>; template class Struct<RPG::Terrain>; template class Struct<RPG::TestBattler>; template class Struct<RPG::Troop>; template class Struct<RPG::TroopMember>; template class Struct<RPG::TroopPage>; template class Struct<RPG::TroopPageCondition>; template class Struct<RPG::Variable>; <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm 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. * **************************************************************************/ #ifndef REALM_UNICODE_HPP #define REALM_UNICODE_HPP #include <locale> #include <cstdint> #include <string> #include <realm/util/safe_int_ops.hpp> #include <realm/string_data.hpp> #include <realm/util/features.h> #include <realm/utilities.hpp> namespace realm { enum string_compare_method_t { STRING_COMPARE_CORE, STRING_COMPARE_CPP11, STRING_COMPARE_CALLBACK, STRING_COMPARE_CORE_SIMILAR }; extern StringCompareCallback string_compare_callback; extern string_compare_method_t string_compare_method; // Description for set_string_compare_method(): // // Short summary: iOS language binding: call // set_string_compare_method() for fast but slightly inaccurate sort in some countries, or // set_string_compare_method(2, callbackptr) for slow but precise sort (see callbackptr below) // // Different countries ('locales') have different sorting order for strings and letters. Because there unfortunatly // doesn't exist any unified standardized way to compare strings in C++ on multiple platforms, we need this method. // // It determins how sorting a TableView by a String column must take place. The 'method' argument can be: // // 0: Fast core-only compare (no OS/framework calls). LIMITATIONS: Works only upto 'Latin Extended 2' (unicodes // 0...591). Also, sorting order is according to 'en_US' so it may be slightly inaccurate for some countries. // 'callback' argument is ignored. // // Return value: Always 'true' // // 1: Native C++11 method if core is compiled as C++11. Gives precise sorting according // to user's current locale. LIMITATIONS: Currently works only on Windows and on Linux with clang. Does NOT work on // iOS (due to only 'C' locale being available in CoreFoundation, which puts 'Z' before 'a'). Unknown if works on // Windows Phone / Android. Furthermore it does NOT work on Linux with gcc 4.7 or 4.8 (lack of c++11 feature that // can convert utf8->wstring without calls to setlocale()). // // Return value: 'true' if supported, otherwise 'false' (if so, then previous setting, if any, is preserved). // // 2: Callback method. Language binding / C++ user must provide a utf-8 callback method of prototype: // bool callback(const char* string1, const char* string2) where 'callback' must return bool(string1 < string2). // // Return value: Always 'true' // // Default is method = 0 if the function is never called // // NOT THREAD SAFE! Call once during initialization or make sure it's not called simultaneously with different // arguments. The setting is remembered per-process; it does NOT need to be called prior to each sort bool set_string_compare_method(string_compare_method_t method, StringCompareCallback callback); // Return size in bytes of utf8 character. No error checking size_t sequence_length(char lead); // Limitations for case insensitive string search // Case insensitive search (equal, begins_with, ends_with and contains) // only works for unicodes 0...0x7f which is the same as the 0...127 // ASCII character set (letters a-z and A-Z). // In does *not* work for the 0...255 ANSI character set that contains // characters from many European countries like Germany, France, Denmark, // etc. // It also does not work for characters from non-western countries like // Japan, Russia, Arabia, etc. // If there exists characters outside the ASCII range either in the text // to be searched for, or in the Realm string column which is searched // in, then the compare yields a random result such that the row may or // may not be included in the result set. // Return bool(string1 < string2) bool utf8_compare(StringData string1, StringData string2); // Return unicode value of character. uint32_t utf8value(const char* character); inline bool equal_sequence(const char*& begin, const char* end, const char* begin2); // FIXME: The current approach to case insensitive comparison requires // that case mappings can be done in a way that does not change he // number of bytes used to encode the individual Unicode // character. This is not generally the case, so, as far as I can see, // this approach has no future. // // FIXME: The current approach to case insensitive comparison relies // on checking each "haystack" character against the corresponding // character in both a lower cased and an upper cased version of the // "needle". While this leads to efficient comparison, it ignores the // fact that "case folding" is the only correct approach to case // insensitive comparison in a locale agnostic Unicode // environment. // // See // http://www.w3.org/International/wiki/Case_folding // http://userguide.icu-project.org/transforms/casemappings#TOC-Case-Folding. // // The ideal API would probably be something like this: // // case_fold: utf_8 -> case_folded // equal_case_fold: (needle_case_folded, single_haystack_entry_utf_8) -> found // search_case_fold: (needle_case_folded, huge_haystack_string_utf_8) -> found_at_position // // The case folded form would probably be using UTF-32 or UTF-16. /// If successful, returns a string of the same size as \a source. /// Returns none if invalid UTF-8 encoding was encountered. util::Optional<std::string> case_map(StringData source, bool upper); enum IgnoreErrorsTag { IgnoreErrors }; std::string case_map(StringData source, bool upper, IgnoreErrorsTag); /// Assumes that the sizes of \a needle_upper and \a needle_lower are /// identical to the size of \a haystack. Returns false if the needle /// is different from the haystack. bool equal_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower); /// Assumes that the sizes of \a needle_upper and \a needle_lower are /// both equal to \a needle_size. Returns haystack.size() if the /// needle was not found. size_t search_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size); /// Assumes that the sizes of \a needle_upper and \a needle_lower are /// both equal to \a needle_size. Returns false if the /// needle was not found. bool contains_ins(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size, const std::array<uint8_t, 256> &charmap); /// Case insensitive wildcard matching ('?' for single char, '*' for zero or more chars) bool string_like_ins(StringData text, StringData pattern) noexcept; bool string_like_ins(StringData text, StringData upper, StringData lower) noexcept; } // namespace realm #endif // REALM_UNICODE_HPP <commit_msg>add like to the list of case insensitive limited predicates<commit_after>/************************************************************************* * * Copyright 2016 Realm 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. * **************************************************************************/ #ifndef REALM_UNICODE_HPP #define REALM_UNICODE_HPP #include <locale> #include <cstdint> #include <string> #include <realm/util/safe_int_ops.hpp> #include <realm/string_data.hpp> #include <realm/util/features.h> #include <realm/utilities.hpp> namespace realm { enum string_compare_method_t { STRING_COMPARE_CORE, STRING_COMPARE_CPP11, STRING_COMPARE_CALLBACK, STRING_COMPARE_CORE_SIMILAR }; extern StringCompareCallback string_compare_callback; extern string_compare_method_t string_compare_method; // Description for set_string_compare_method(): // // Short summary: iOS language binding: call // set_string_compare_method() for fast but slightly inaccurate sort in some countries, or // set_string_compare_method(2, callbackptr) for slow but precise sort (see callbackptr below) // // Different countries ('locales') have different sorting order for strings and letters. Because there unfortunatly // doesn't exist any unified standardized way to compare strings in C++ on multiple platforms, we need this method. // // It determins how sorting a TableView by a String column must take place. The 'method' argument can be: // // 0: Fast core-only compare (no OS/framework calls). LIMITATIONS: Works only upto 'Latin Extended 2' (unicodes // 0...591). Also, sorting order is according to 'en_US' so it may be slightly inaccurate for some countries. // 'callback' argument is ignored. // // Return value: Always 'true' // // 1: Native C++11 method if core is compiled as C++11. Gives precise sorting according // to user's current locale. LIMITATIONS: Currently works only on Windows and on Linux with clang. Does NOT work on // iOS (due to only 'C' locale being available in CoreFoundation, which puts 'Z' before 'a'). Unknown if works on // Windows Phone / Android. Furthermore it does NOT work on Linux with gcc 4.7 or 4.8 (lack of c++11 feature that // can convert utf8->wstring without calls to setlocale()). // // Return value: 'true' if supported, otherwise 'false' (if so, then previous setting, if any, is preserved). // // 2: Callback method. Language binding / C++ user must provide a utf-8 callback method of prototype: // bool callback(const char* string1, const char* string2) where 'callback' must return bool(string1 < string2). // // Return value: Always 'true' // // Default is method = 0 if the function is never called // // NOT THREAD SAFE! Call once during initialization or make sure it's not called simultaneously with different // arguments. The setting is remembered per-process; it does NOT need to be called prior to each sort bool set_string_compare_method(string_compare_method_t method, StringCompareCallback callback); // Return size in bytes of utf8 character. No error checking size_t sequence_length(char lead); // Limitations for case insensitive string search // Case insensitive search (equal, begins_with, ends_with, like and contains) // only works for unicodes 0...0x7f which is the same as the 0...127 // ASCII character set (letters a-z and A-Z). // In does *not* work for the 0...255 ANSI character set that contains // characters from many European countries like Germany, France, Denmark, // etc. // It also does not work for characters from non-western countries like // Japan, Russia, Arabia, etc. // If there exists characters outside the ASCII range either in the text // to be searched for, or in the Realm string column which is searched // in, then the compare yields a random result such that the row may or // may not be included in the result set. // Return bool(string1 < string2) bool utf8_compare(StringData string1, StringData string2); // Return unicode value of character. uint32_t utf8value(const char* character); inline bool equal_sequence(const char*& begin, const char* end, const char* begin2); // FIXME: The current approach to case insensitive comparison requires // that case mappings can be done in a way that does not change he // number of bytes used to encode the individual Unicode // character. This is not generally the case, so, as far as I can see, // this approach has no future. // // FIXME: The current approach to case insensitive comparison relies // on checking each "haystack" character against the corresponding // character in both a lower cased and an upper cased version of the // "needle". While this leads to efficient comparison, it ignores the // fact that "case folding" is the only correct approach to case // insensitive comparison in a locale agnostic Unicode // environment. // // See // http://www.w3.org/International/wiki/Case_folding // http://userguide.icu-project.org/transforms/casemappings#TOC-Case-Folding. // // The ideal API would probably be something like this: // // case_fold: utf_8 -> case_folded // equal_case_fold: (needle_case_folded, single_haystack_entry_utf_8) -> found // search_case_fold: (needle_case_folded, huge_haystack_string_utf_8) -> found_at_position // // The case folded form would probably be using UTF-32 or UTF-16. /// If successful, returns a string of the same size as \a source. /// Returns none if invalid UTF-8 encoding was encountered. util::Optional<std::string> case_map(StringData source, bool upper); enum IgnoreErrorsTag { IgnoreErrors }; std::string case_map(StringData source, bool upper, IgnoreErrorsTag); /// Assumes that the sizes of \a needle_upper and \a needle_lower are /// identical to the size of \a haystack. Returns false if the needle /// is different from the haystack. bool equal_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower); /// Assumes that the sizes of \a needle_upper and \a needle_lower are /// both equal to \a needle_size. Returns haystack.size() if the /// needle was not found. size_t search_case_fold(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size); /// Assumes that the sizes of \a needle_upper and \a needle_lower are /// both equal to \a needle_size. Returns false if the /// needle was not found. bool contains_ins(StringData haystack, const char* needle_upper, const char* needle_lower, size_t needle_size, const std::array<uint8_t, 256> &charmap); /// Case insensitive wildcard matching ('?' for single char, '*' for zero or more chars) bool string_like_ins(StringData text, StringData pattern) noexcept; bool string_like_ins(StringData text, StringData upper, StringData lower) noexcept; } // namespace realm #endif // REALM_UNICODE_HPP <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "RAID4PG.h" #include "OSD.h" #include "common/Logger.h" #include "messages/MOSDOp.h" #include "messages/MOSDOpReply.h" #include "messages/MOSDPGNotify.h" #include "messages/MOSDPGRemove.h" #include "config.h" #define dout(l) if (l<=g_conf.debug || l<=g_conf.debug_osd) *_dout << dbeginl << g_clock.now() << " osd" << osd->get_nodeid() << " " << (osd->osdmap ? osd->osdmap->get_epoch():0) << " " << *this << " " #include <errno.h> #include <sys/stat.h> bool RAID4PG::preprocess_op(MOSDOp *op, utime_t now) { return false; } void RAID4PG::do_op(MOSDOp *op) { } void RAID4PG::do_op_reply(MOSDOpReply *reply) { } // ----------------- // pg changes bool RAID4PG::same_for_read_since(epoch_t e) { return e >= info.history.same_since; // whole pg set same } bool RAID4PG::same_for_modify_since(epoch_t e) { return e >= info.history.same_since; // whole pg set same } bool RAID4PG::same_for_rep_modify_since(epoch_t e) { return e >= info.history.same_since; // whole pg set same } // ----------------- // RECOVERY bool RAID4PG::is_missing_object(object_t oid) { return false; } void RAID4PG::wait_for_missing_object(object_t oid, MOSDOp *op) { //assert(0); } void RAID4PG::note_failed_osd(int o) { dout(10) << "note_failed_osd osd" << o << dendl; //assert(0); } void RAID4PG::on_acker_change() { dout(10) << "on_acker_change" << dendl; //assert(0); } void RAID4PG::on_role_change() { dout(10) << "on_role_change" << dendl; //assert(0); } void RAID4PG::on_change() { dout(10) << "on_change" << dendl; //assert(0); } // misc recovery crap void RAID4PG::clean_up_local(ObjectStore::Transaction&) { } void RAID4PG::cancel_recovery() { //assert(0); } bool RAID4PG::do_recovery() { //assert(0); return false; } void RAID4PG::purge_strays() { //assert(0); } <commit_msg>some sample code for mapping logical object extent onto physical objects<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "RAID4PG.h" #include "OSD.h" #include "common/Logger.h" #include "messages/MOSDOp.h" #include "messages/MOSDOpReply.h" #include "messages/MOSDPGNotify.h" #include "messages/MOSDPGRemove.h" #include "config.h" #define dout(l) if (l<=g_conf.debug || l<=g_conf.debug_osd) *_dout << dbeginl << g_clock.now() << " osd" << osd->get_nodeid() << " " << (osd->osdmap ? osd->osdmap->get_epoch():0) << " " << *this << " " #include <errno.h> #include <sys/stat.h> bool RAID4PG::preprocess_op(MOSDOp *op, utime_t now) { return false; } void RAID4PG::do_op(MOSDOp *op) { // a write will do something like object_t oid = op->get_oid(); // logical object pg_t pg = op->get_pg(); ObjectLayout layout = op->get_layout(); bufferlist data = op->get_data(); off_t off = op->get_offset(); off_t left = op->get_length(); // map data onto pobjects int n = pg.size() - 1; // n+1 raid4 int rank = (off % layout.stripe_unit) % n; off_t off_in_bl = 0; while (left > 0) { pobject_t po(0, rank, oid); off_t off_in_po = off % layout.stripe_unit; off_t stripe_unit_end = off - off_in_po + layout.stripe_unit; off_t len_in_po = MAX(left, stripe_unit_end-off); bufferlist data_in_po; data_in_po.substr_of(data, off_in_bl, len_in_po); // next! off_in_bl += len_in_po; rank++; if (rank == n) rank = 0; } } void RAID4PG::do_op_reply(MOSDOpReply *reply) { } // ----------------- // pg changes bool RAID4PG::same_for_read_since(epoch_t e) { return e >= info.history.same_since; // whole pg set same } bool RAID4PG::same_for_modify_since(epoch_t e) { return e >= info.history.same_since; // whole pg set same } bool RAID4PG::same_for_rep_modify_since(epoch_t e) { return e >= info.history.same_since; // whole pg set same } // ----------------- // RECOVERY bool RAID4PG::is_missing_object(object_t oid) { return false; } void RAID4PG::wait_for_missing_object(object_t oid, MOSDOp *op) { //assert(0); } void RAID4PG::note_failed_osd(int o) { dout(10) << "note_failed_osd osd" << o << dendl; //assert(0); } void RAID4PG::on_acker_change() { dout(10) << "on_acker_change" << dendl; //assert(0); } void RAID4PG::on_role_change() { dout(10) << "on_role_change" << dendl; //assert(0); } void RAID4PG::on_change() { dout(10) << "on_change" << dendl; //assert(0); } // misc recovery crap void RAID4PG::clean_up_local(ObjectStore::Transaction&) { } void RAID4PG::cancel_recovery() { //assert(0); } bool RAID4PG::do_recovery() { //assert(0); return false; } void RAID4PG::purge_strays() { //assert(0); } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; while (keepGoing) { image = cvQueryFrame(capture); imshow("webcam", image); // thresholds on dark regions Mat black, blurred; Mat channel[3]; split(image, channel); equalizeHist(channel[0], channel[0]); equalizeHist(channel[1], channel[1]); equalizeHist(channel[2], channel[2]); merge(channel, 3, black); blur(black, blurred, Size(width/4.5,height/9)); split(blurred, channel); black = (channel[0] + channel[1] + channel[2])/3.0; equalizeHist(black, black); bitwise_not(black,black); threshold(black, black, 210, 1, THRESH_BINARY); // imshow("black", black); add(black, Scalar(2), black); Mat fgd, bgd; grabCut(image, black, Rect(1,1), bgd, fgd, 5, GC_INIT_WITH_MASK); imshow("bgd1", bgd); imshow("fgd1", fgd); grabCut(image, black, Rect(1,1), bgd, fgd, 15, GC_INIT_WITH_MASK); imshow("bgd2", bgd); imshow("fgd2", fgd); grabCut(image, black, Rect(1,1), bgd, fgd, 25, GC_INIT_WITH_MASK); imshow("bgd3", bgd); imshow("fgd3", fgd); /* split(image, channel); channel[0] = channel[0].mul(black); channel[1] = channel[1].mul(black); channel[2] = channel[2].mul(black); merge(channel, 3, image); */ // imshow("yox", image); //do some weird morphological closing thing // Mat channel[3]; /* Mat canny; Canny(image, canny, 0, 50); imshow("canny", canny); */ /* Mat fill = image.clone(); Point seed(rand()%width, rand()%height); floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25)); imshow("fill", fill); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; while (keepGoing) { image = cvQueryFrame(capture); imshow("webcam", image); // thresholds on dark regions Mat black, blurred; Mat channel[3]; split(image, channel); equalizeHist(channel[0], channel[0]); equalizeHist(channel[1], channel[1]); equalizeHist(channel[2], channel[2]); merge(channel, 3, black); blur(black, blurred, Size(width/4.5,height/9)); split(blurred, channel); black = (channel[0] + channel[1] + channel[2])/3.0; equalizeHist(black, black); bitwise_not(black,black); threshold(black, black, 210, 1, THRESH_BINARY); // imshow("black", black); add(black, Scalar(2), black); Mat fgd, bgd; grabCut(image, black, Rect(1,1,1,1), bgd, fgd, 5, GC_INIT_WITH_MASK); imshow("bgd1", bgd); imshow("fgd1", fgd); grabCut(image, black, Rect(1,1,1,1), bgd, fgd, 15, GC_INIT_WITH_MASK); imshow("bgd2", bgd); imshow("fgd2", fgd); grabCut(image, black, Rect(1,1,1,1), bgd, fgd, 25, GC_INIT_WITH_MASK); imshow("bgd3", bgd); imshow("fgd3", fgd); /* split(image, channel); channel[0] = channel[0].mul(black); channel[1] = channel[1].mul(black); channel[2] = channel[2].mul(black); merge(channel, 3, image); */ // imshow("yox", image); //do some weird morphological closing thing // Mat channel[3]; /* Mat canny; Canny(image, canny, 0, 50); imshow("canny", canny); */ /* Mat fill = image.clone(); Point seed(rand()%width, rand()%height); floodFill(fill, seed, Scalar(200,0,0), 0, Scalar(0,0,0), Scalar(25,25,25)); imshow("fill", fill); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); //imshow("webcam", image); // thresholds on dark regions Mat gray, blurred_gray, threshold_gray; cvtColor(image, gray, CV_BGR2GRAY); blur(gray, blurred_gray, Size(width/10,height/20)); equalizeHist(blurred_gray, blurred_gray); bitwise_not(blurred_gray, blurred_gray); threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY); imshow("threshold", threshold_gray); Mat mask = threshold_gray.mul(blurred_gray); imshow("mask", mask); Moments lol = moments(mask, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("threshold", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); //imshow("webcam", image); // thresholds on dark regions Mat gray, blurred_gray, threshold_gray; cvtColor(image, gray, CV_BGR2GRAY); blur(gray, blurred_gray, Size(width/10,height/20)); equalizeHist(blurred_gray, blurred_gray); bitwise_not(blurred_gray, blurred_gray); threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY); imshow("threshold", threshold_gray); Mat mask = threshold_gray.mul(blurred_gray); imshow("mask", mask); Moments lol = moments(mask, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before> #include <boost/python.hpp> using namespace boost::python; class Point { public: Point(float x = 0, float y = 0) { _x = x; _y = y; } float x() const { return _x; } void set_x(float x) { _x = x; } float y() const { return _y; } void set_y(float y) { _y = y; } private: float _x, _y; }; class Robot { public: Point pos, vel; float angle, angle_vel; }; BOOST_PYTHON_MODULE(robocup) { class_<Point>("Point", init<float, float>()) .add_property("x", &Point::x, &Point::set_x) .add_property("y", &Point::y, &Point::set_y) ; class_<Robot>("Robot", init<>()) .def_readwrite("pos", &Robot::pos) .def_readwrite("vel", &Robot::vel) .def_readwrite("angle", &Robot::angle) .def_readwrite("angle_vel", &Robot::angle_vel) ; } <commit_msg>removed junk stuff from boost python wrapper<commit_after> #include <boost/python.hpp> using namespace boost::python; BOOST_PYTHON_MODULE(robocup) { class_<Point>("Point", init<float, float>()) .add_property("x", &Point::x, &Point::set_x) .add_property("y", &Point::y, &Point::set_y) ; class_<Robot>("Robot", init<>()) .def_readwrite("pos", &Robot::pos) .def_readwrite("vel", &Robot::vel) .def_readwrite("angle", &Robot::angle) .def_readwrite("angle_vel", &Robot::angle_vel) ; } <|endoftext|>
<commit_before>/* Copyright 2015 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #ifndef REQL_REQL_PROTOCOL_HPP_ #define REQL_REQL_PROTOCOL_HPP_ #include "./reql/handshake.hpp" #include "./reql/query.hpp" #include "./reql/socket.hpp" #include <atomic> #include <cstdint> #include <sstream> #include <string> #include <thread> namespace _ReQL { template <class auth_e, class handshake_e, class socket_e> class Protocol_t { public: template <class addr_t, class auth_t, class func_t, class port_t> void connect(const addr_t &addr, const port_t &port, const auth_t &auth, func_t func) { p_sock.connect(addr, port); Handshake_t<auth_e, handshake_e>(p_sock, auth); std::thread([func, this] { size_t buff_size; std::ostringstream buffer; while (true) { while (buff_size < 12) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } auto string = buffer.str(); buffer.clear(); buffer << string.substr(12); auto token = get_token(string.c_str()); auto size = get_size(string.c_str() + 8); while (buff_size < size) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } string = buffer.str(); buffer.clear(); buffer << string.substr(size); run(token, make_query(REQL_CONTINUE)); func(string.substr(0, size), token); } }).detach(); } void disconnect() { p_sock.disconnect(); } bool connected() const { return p_sock.connected(); } template <class query_t> auto run(query_t query) { auto token = p_next_token++; run(token, query); return token; } void stop(std::uint64_t token) { run(token, make_query(REQL_STOP)); } private: template <class query_t> void run(std::uint64_t token, query_t query) { std::ostringstream stream("\0\0\0\0\0\0\0\0\0\0\0\0", std::ios_base::ate); stream << std::boolalpha << std::setprecision(std::numeric_limits<double>::digits10 + 1) << query; auto wire_query = stream.str(); auto size = wire_query.size(); auto data = wire_query.data(); make_token(data, token); make_size(data + 8, static_cast<std::uint32_t>(size - 12)); p_sock.write(data, size); } static std::uint32_t get_size(const char *buf) { return (static_cast<std::uint32_t>(buf[0]) << 0) | (static_cast<std::uint32_t>(buf[1]) << 8) | (static_cast<std::uint32_t>(buf[2]) << 16) | (static_cast<std::uint32_t>(buf[3]) << 24); } static void make_size(char *buf, const std::uint32_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); } static std::uint64_t get_token(const char *buf) { return (static_cast<std::uint64_t>(buf[0]) << 0) | (static_cast<std::uint64_t>(buf[1]) << 8) | (static_cast<std::uint64_t>(buf[2]) << 16) | (static_cast<std::uint64_t>(buf[3]) << 24) | (static_cast<std::uint64_t>(buf[4]) << 32) | (static_cast<std::uint64_t>(buf[5]) << 40) | (static_cast<std::uint64_t>(buf[6]) << 48) | (static_cast<std::uint64_t>(buf[7]) << 56); } static void make_token(char *buf, const std::uint64_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); buf[4] = static_cast<char>((magic >> 32) & 0xFF); buf[5] = static_cast<char>((magic >> 40) & 0xFF); buf[6] = static_cast<char>((magic >> 48) & 0xFF); buf[7] = static_cast<char>((magic >> 56) & 0xFF); } std::atomic<std::uint64_t> p_next_token; Socket_t<socket_e> p_sock; }; } // namespace _ReQL #endif // REQL_REQL_PROTOCOL_HPP_ <commit_msg>Fix const cast needed.<commit_after>/* Copyright 2015 Adam Grandquist 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. */ /** * @author Adam Grandquist * @copyright Apache */ #ifndef REQL_REQL_PROTOCOL_HPP_ #define REQL_REQL_PROTOCOL_HPP_ #include "./reql/handshake.hpp" #include "./reql/query.hpp" #include "./reql/socket.hpp" #include <atomic> #include <cstdint> #include <sstream> #include <string> #include <thread> namespace _ReQL { template <class auth_e, class handshake_e, class socket_e> class Protocol_t { public: template <class addr_t, class auth_t, class func_t, class port_t> void connect(const addr_t &addr, const port_t &port, const auth_t &auth, func_t func) { p_sock.connect(addr, port); Handshake_t<auth_e, handshake_e>(p_sock, auth); std::thread([func, this] { size_t buff_size; std::ostringstream buffer; while (true) { while (buff_size < 12) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } auto string = buffer.str(); buffer.clear(); buffer << string.substr(12); auto token = get_token(string.c_str()); auto size = get_size(string.c_str() + 8); while (buff_size < size) { auto string = p_sock.read(); buff_size += string.size(); buffer << string; } string = buffer.str(); buffer.clear(); buffer << string.substr(size); run(token, make_query(REQL_CONTINUE)); func(string.substr(0, size), token); } }).detach(); } void disconnect() { p_sock.disconnect(); } bool connected() const { return p_sock.connected(); } template <class query_t> auto run(query_t query) { auto token = p_next_token++; run(token, query); return token; } void stop(std::uint64_t token) { run(token, make_query(REQL_STOP)); } private: template <class query_t> void run(std::uint64_t token, query_t query) { std::ostringstream stream("\0\0\0\0\0\0\0\0\0\0\0\0", std::ios_base::ate); stream << std::boolalpha << std::setprecision(std::numeric_limits<double>::digits10 + 1) << query; auto wire_query = stream.str(); auto size = wire_query.size(); auto data = const_cast<char *>(wire_query.data()); make_token(data, token); make_size(data + 8, static_cast<std::uint32_t>(size - 12)); p_sock.write(data, size); } static std::uint32_t get_size(const char *buf) { return (static_cast<std::uint32_t>(buf[0]) << 0) | (static_cast<std::uint32_t>(buf[1]) << 8) | (static_cast<std::uint32_t>(buf[2]) << 16) | (static_cast<std::uint32_t>(buf[3]) << 24); } static void make_size(char *buf, const std::uint32_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); } static std::uint64_t get_token(const char *buf) { return (static_cast<std::uint64_t>(buf[0]) << 0) | (static_cast<std::uint64_t>(buf[1]) << 8) | (static_cast<std::uint64_t>(buf[2]) << 16) | (static_cast<std::uint64_t>(buf[3]) << 24) | (static_cast<std::uint64_t>(buf[4]) << 32) | (static_cast<std::uint64_t>(buf[5]) << 40) | (static_cast<std::uint64_t>(buf[6]) << 48) | (static_cast<std::uint64_t>(buf[7]) << 56); } static void make_token(char *buf, const std::uint64_t magic) { buf[0] = static_cast<char>((magic >> 0) & 0xFF); buf[1] = static_cast<char>((magic >> 8) & 0xFF); buf[2] = static_cast<char>((magic >> 16) & 0xFF); buf[3] = static_cast<char>((magic >> 24) & 0xFF); buf[4] = static_cast<char>((magic >> 32) & 0xFF); buf[5] = static_cast<char>((magic >> 40) & 0xFF); buf[6] = static_cast<char>((magic >> 48) & 0xFF); buf[7] = static_cast<char>((magic >> 56) & 0xFF); } std::atomic<std::uint64_t> p_next_token; Socket_t<socket_e> p_sock; }; } // namespace _ReQL #endif // REQL_REQL_PROTOCOL_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "resolve_links.hpp" #include "libtorrent/torrent_info.hpp" #include <boost/shared_ptr.hpp> namespace libtorrent { #ifndef TORRENT_DISABLE_MUTABLE_TORRENTS resolve_links::resolve_links(boost::shared_ptr<torrent_info> ti) : m_torrent_file(ti) { TORRENT_ASSERT(ti); int piece_size = ti->piece_length(); file_storage const& fs = ti->files(); m_file_sizes.reserve(fs.num_files()); for (int i = 0; i < fs.num_files(); ++i) { // don't match pad-files, and don't match files that aren't aligned to // ieces. Files are matched by comparing piece hashes, so pieces must // be aligned and the same size if (fs.pad_file_at(i)) continue; if ((fs.file_offset(i) % piece_size) != 0) continue; m_file_sizes.insert(std::make_pair(fs.file_size(i), i)); } m_links.resize(m_torrent_file->num_files()); } void resolve_links::match(boost::shared_ptr<const torrent_info> const& ti , std::string const& save_path) { if (!ti) return; // only torrents with the same if (ti->piece_length() != m_torrent_file->piece_length()) return; int piece_size = ti->piece_length(); file_storage const& fs = ti->files(); m_file_sizes.reserve(fs.num_files()); for (int i = 0; i < fs.num_files(); ++i) { // for every file in the other torrent, see if we have one that match // it in m_torrent_file // if the file base is not aligned to pieces, we're not going to match // it anyway (we only compare piece hashes) if ((fs.file_offset(i) % piece_size) != 0) continue; if (fs.pad_file_at(i)) continue; boost::int64_t file_size = fs.file_size(i); typedef boost::unordered_multimap<boost::int64_t, int>::iterator iterator; iterator iter = m_file_sizes.find(file_size); // we don't have a file whose size matches, look at the next one if (iter == m_file_sizes.end()) continue; TORRENT_ASSERT(iter->second < m_torrent_file->files().num_files()); TORRENT_ASSERT(iter->second >= 0); // if we already have found a duplicate for this file, no need // to keep looking if (m_links[iter->second].ti) continue; // files are aligned and have the same size, now start comparing // piece hashes, to see if the files are identical // the pieces of the incoming file int their_piece = fs.map_file(i, 0, 0).piece; // the pieces of "this" file (from m_torrent_file) int our_piece = m_torrent_file->files().map_file( iter->second, 0, 0).piece; int num_pieces = (file_size + piece_size - 1) / piece_size; bool match = true; for (int p = 0; p < num_pieces; ++p, ++their_piece, ++our_piece) { if (m_torrent_file->hash_for_piece(our_piece) != ti->hash_for_piece(their_piece)) { match = false; break; } } if (!match) continue; m_links[iter->second].ti = ti; m_links[iter->second].save_path = save_path; m_links[iter->second].file_idx = i; // since we have a duplicate for this file, we may as well remove // it from the file-size map, so we won't find it again. m_file_sizes.erase(iter); } } #endif // TORRENT_DISABLE_MUTABLE_TORRENTS } // namespace libtorrent <commit_msg>fix inlude in resolve_links.cpp<commit_after>/* Copyright (c) 2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/resolve_links.hpp" #include "libtorrent/torrent_info.hpp" #include <boost/shared_ptr.hpp> namespace libtorrent { #ifndef TORRENT_DISABLE_MUTABLE_TORRENTS resolve_links::resolve_links(boost::shared_ptr<torrent_info> ti) : m_torrent_file(ti) { TORRENT_ASSERT(ti); int piece_size = ti->piece_length(); file_storage const& fs = ti->files(); m_file_sizes.reserve(fs.num_files()); for (int i = 0; i < fs.num_files(); ++i) { // don't match pad-files, and don't match files that aren't aligned to // ieces. Files are matched by comparing piece hashes, so pieces must // be aligned and the same size if (fs.pad_file_at(i)) continue; if ((fs.file_offset(i) % piece_size) != 0) continue; m_file_sizes.insert(std::make_pair(fs.file_size(i), i)); } m_links.resize(m_torrent_file->num_files()); } void resolve_links::match(boost::shared_ptr<const torrent_info> const& ti , std::string const& save_path) { if (!ti) return; // only torrents with the same if (ti->piece_length() != m_torrent_file->piece_length()) return; int piece_size = ti->piece_length(); file_storage const& fs = ti->files(); m_file_sizes.reserve(fs.num_files()); for (int i = 0; i < fs.num_files(); ++i) { // for every file in the other torrent, see if we have one that match // it in m_torrent_file // if the file base is not aligned to pieces, we're not going to match // it anyway (we only compare piece hashes) if ((fs.file_offset(i) % piece_size) != 0) continue; if (fs.pad_file_at(i)) continue; boost::int64_t file_size = fs.file_size(i); typedef boost::unordered_multimap<boost::int64_t, int>::iterator iterator; iterator iter = m_file_sizes.find(file_size); // we don't have a file whose size matches, look at the next one if (iter == m_file_sizes.end()) continue; TORRENT_ASSERT(iter->second < m_torrent_file->files().num_files()); TORRENT_ASSERT(iter->second >= 0); // if we already have found a duplicate for this file, no need // to keep looking if (m_links[iter->second].ti) continue; // files are aligned and have the same size, now start comparing // piece hashes, to see if the files are identical // the pieces of the incoming file int their_piece = fs.map_file(i, 0, 0).piece; // the pieces of "this" file (from m_torrent_file) int our_piece = m_torrent_file->files().map_file( iter->second, 0, 0).piece; int num_pieces = (file_size + piece_size - 1) / piece_size; bool match = true; for (int p = 0; p < num_pieces; ++p, ++their_piece, ++our_piece) { if (m_torrent_file->hash_for_piece(our_piece) != ti->hash_for_piece(their_piece)) { match = false; break; } } if (!match) continue; m_links[iter->second].ti = ti; m_links[iter->second].save_path = save_path; m_links[iter->second].file_idx = i; // since we have a duplicate for this file, we may as well remove // it from the file-size map, so we won't find it again. m_file_sizes.erase(iter); } } #endif // TORRENT_DISABLE_MUTABLE_TORRENTS } // namespace libtorrent <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: connctr.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2006-04-20 15:15:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "connctr.hxx" #include "objwin.hxx" #include "depwin.hxx" //#include "depapp.hxx" #include "math.h" BOOL Connector::msbHideMode = FALSE; Connector::Connector( DepWin* pParent, WinBits nWinStyle ) : mpStartWin( 0L ), mpEndWin( 0L ), mnStartId( 0 ), mnEndId( 0 ), len( 70 ), bVisible( FALSE ) { mpParent = pParent; if ( mpParent ) mpParent->AddConnector( this ); } Connector::~Connector() { if ( mpStartWin ) mpStartWin->RemoveConnector( this ); if ( mpEndWin ) mpEndWin->RemoveConnector( this ); if ( mpParent ) mpParent->RemoveConnector( this ); mpParent->Invalidate( Rectangle( mStart, mEnd )); mpParent->Invalidate( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3))); } void Connector::Initialize( ObjectWin* pStartWin, ObjectWin* pEndWin, BOOL bVis ) { mpStartWin = pStartWin; mpEndWin = pEndWin; mpStartWin->AddConnector( this ); mpEndWin->AddConnector( this ); mCenter = GetMiddle(); mStart = pStartWin->GetFixPoint( mCenter ); mEnd = pEndWin->GetFixPoint( mCenter ); mnStartId = pStartWin->GetId(); mnEndId = pEndWin->GetId(); bVisible = bVis; // if ( mpParent->IsPaintEnabled()) if ( IsVisible() ) { mpParent->DrawLine( mEnd, mStart ); mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2))); } UpdateVisibility(); //null_Project } void Connector::UpdateVisibility() { bVisible = mpStartWin->IsVisible() && mpEndWin->IsVisible(); } Point Connector::GetMiddle() { Point aStartPoint = mpStartWin->GetPosPixel(); Size aStartSize = mpStartWin->GetSizePixel(); int nMoveHorz, nMoveVert; aStartPoint.Move( aStartSize.Width() / 2, aStartSize.Height() / 2 ); Point aEndPoint = mpEndWin->GetPosPixel(); Size aEndSize = mpEndWin->GetSizePixel(); aEndPoint.Move( aEndSize.Width() / 2, aEndSize.Height() / 2 ); Point aRetPoint = aEndPoint; nMoveHorz = aStartPoint.X() - aEndPoint.X(); if ( nMoveHorz ) nMoveHorz /= 2; nMoveVert = aStartPoint.Y() - aEndPoint.Y(); if ( nMoveVert ) nMoveVert /= 2; aRetPoint.Move( nMoveHorz, nMoveVert ); return aRetPoint; } void Connector::Paint( const Rectangle& rRect ) { //MyApp *pApp = (MyApp*)GetpApp(); //SolDep *pSoldep = pApp->GetSolDep(); if (msbHideMode) { /* if ((mpStartWin->GetMarkMode() == 0) || (mpEndWin->GetMarkMode() == 0)) { //bVisible = FALSE; UpdateVisibility(); fprintf( ((MyApp*)GetpApp())->pDebugFile, "FALSE connctr: Start: %s %i - End: %s %i\n", mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(), mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode()); } else { bVisible = TRUE; fprintf( ((MyApp*)GetpApp())->pDebugFile, "TRUE connctr: Start: %s %i - End: %s %i\n", mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(), mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode()); } */ if (!(mpStartWin->IsNullObject())) //null_project { if (mpStartWin->GetMarkMode() == 0) { mpStartWin->SetViewMask(0); //objwin invisible } else { mpStartWin->SetViewMask(1); //objwin visible } } if (!(mpEndWin->IsNullObject())) { if (mpEndWin->GetMarkMode() == 0) { mpEndWin->SetViewMask(0); //objwin invisible } else { mpEndWin->SetViewMask(1); //objwin visible } } UpdateVisibility(); } else //IsHideMode { //bVisible = TRUE; if (!(mpStartWin->IsNullObject())) //null_project { mpStartWin->SetViewMask(1); } if (!(mpEndWin->IsNullObject())) //null_project { mpEndWin->SetViewMask(1); } UpdateVisibility(); } if ( (mpStartWin->GetBodyText() != ByteString("null")) && //null_project (mpEndWin->GetBodyText() != ByteString("null")) && IsVisible()) //null_project { mpParent->DrawLine( mEnd, mStart ); mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2))); } } void Connector::UpdatePosition( ObjectWin* pWin, BOOL bPaint ) { // more than one call ? // Point OldStart, OldEnd; static ULONG nCallCount = 0; //MyApp *pApp = (MyApp*)GetpApp(); //SolDep *pSoldep = pApp->GetSolDep(); if (msbHideMode) bVisible = 1; if ( nCallCount ) // only one call nCallCount++; else { nCallCount++; while ( nCallCount ) { if ( bPaint ) { OldStart = mStart; OldEnd = mEnd; } mCenter = GetMiddle(); mStart=mpStartWin->GetFixPoint( mCenter, bPaint ); mEnd=mpEndWin->GetFixPoint( mCenter, bPaint ); if ( bPaint ) { mpParent->Invalidate( Rectangle( OldStart, OldEnd )); mpParent->Invalidate( Rectangle( OldEnd - Point( 2, 2), OldEnd + Point( 2, 2))); //Don't paint "null_project" connectors if ( (mpStartWin->GetBodyText() != ByteString("null")) && //null_project (mpEndWin->GetBodyText() != ByteString("null"))) //null_project { Paint ( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3))); Paint ( Rectangle( mEnd, mStart )); } } nCallCount--; } } } USHORT Connector::Save( SvFileStream& rOutFile ) { rOutFile << mpStartWin->GetId(); rOutFile << mpEndWin->GetId(); return 0; } USHORT Connector::Load( SvFileStream& rInFile ) { rInFile >> mnStartId; rInFile >> mnEndId; return 0; } ObjectWin* Connector::GetOtherWin( ObjectWin* pWin ) { // get correspondent object ptr if ( mpStartWin == pWin ) return mpEndWin; else if ( mpEndWin == pWin ) return mpStartWin; return NULL; } ULONG Connector::GetOtherId( ULONG nId ) { // get correspondent object id if ( mnStartId == nId ) return mnEndId; else if ( mnEndId == nId ) return mnStartId; return NULL; } ULONG Connector::GetLen() { double dx, dy; dx = mStart.X() - mEnd.X(); dy = mStart.Y() - mEnd.Y(); return sqrt( dx * dx + dy * dy ); } BOOL Connector::IsStart( ObjectWin* pWin ) { return pWin == mpStartWin; } <commit_msg>INTEGRATION: CWS soldep2 (1.2.2); FILE MERGED 2006/11/21 16:27:53 obo 1.2.2.1: #143484# dialog for workspace has to support minors<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: connctr.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ihi $ $Date: 2006-12-21 12:22:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifdef _MSC_VER #pragma warning(disable:4100) #endif #include "connctr.hxx" #include "objwin.hxx" #include "depwin.hxx" #include "math.h" BOOL Connector::msbHideMode = FALSE; Connector::Connector( DepWin* pParent, WinBits nWinStyle ) : mpStartWin( 0L ), mpEndWin( 0L ), mnStartId( 0 ), mnEndId( 0 ), len( 70 ), bVisible( FALSE ) { mpParent = pParent; if ( mpParent ) mpParent->AddConnector( this ); } Connector::~Connector() { if ( mpStartWin ) mpStartWin->RemoveConnector( this ); if ( mpEndWin ) mpEndWin->RemoveConnector( this ); if ( mpParent ) mpParent->RemoveConnector( this ); mpParent->Invalidate( Rectangle( mStart, mEnd )); mpParent->Invalidate( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3))); } void Connector::Initialize( ObjectWin* pStartWin, ObjectWin* pEndWin, BOOL bVis ) { mpStartWin = pStartWin; mpEndWin = pEndWin; mpStartWin->AddConnector( this ); mpEndWin->AddConnector( this ); mCenter = GetMiddle(); mStart = pStartWin->GetFixPoint( mCenter ); mEnd = pEndWin->GetFixPoint( mCenter ); mnStartId = pStartWin->GetId(); mnEndId = pEndWin->GetId(); bVisible = bVis; // if ( mpParent->IsPaintEnabled()) if ( IsVisible() ) { mpParent->DrawLine( mEnd, mStart ); mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2))); } UpdateVisibility(); //null_Project } void Connector::UpdateVisibility() { bVisible = mpStartWin->IsVisible() && mpEndWin->IsVisible(); } Point Connector::GetMiddle() { Point aStartPoint = mpStartWin->GetPosPixel(); Size aStartSize = mpStartWin->GetSizePixel(); int nMoveHorz, nMoveVert; aStartPoint.Move( aStartSize.Width() / 2, aStartSize.Height() / 2 ); Point aEndPoint = mpEndWin->GetPosPixel(); Size aEndSize = mpEndWin->GetSizePixel(); aEndPoint.Move( aEndSize.Width() / 2, aEndSize.Height() / 2 ); Point aRetPoint = aEndPoint; nMoveHorz = aStartPoint.X() - aEndPoint.X(); if ( nMoveHorz ) nMoveHorz /= 2; nMoveVert = aStartPoint.Y() - aEndPoint.Y(); if ( nMoveVert ) nMoveVert /= 2; aRetPoint.Move( nMoveHorz, nMoveVert ); return aRetPoint; } void Connector::Paint( const Rectangle& rRect ) { //MyApp *pApp = (MyApp*)GetpApp(); //SolDep *pSoldep = pApp->GetSolDep(); if (msbHideMode) { /* if ((mpStartWin->GetMarkMode() == 0) || (mpEndWin->GetMarkMode() == 0)) { //bVisible = FALSE; UpdateVisibility(); fprintf( ((MyApp*)GetpApp())->pDebugFile, "FALSE connctr: Start: %s %i - End: %s %i\n", mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(), mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode()); } else { bVisible = TRUE; fprintf( ((MyApp*)GetpApp())->pDebugFile, "TRUE connctr: Start: %s %i - End: %s %i\n", mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(), mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode()); } */ if (!(mpStartWin->IsNullObject())) //null_project { if (mpStartWin->GetMarkMode() == 0) { mpStartWin->SetViewMask(0); //objwin invisible } else { mpStartWin->SetViewMask(1); //objwin visible } } if (!(mpEndWin->IsNullObject())) { if (mpEndWin->GetMarkMode() == 0) { mpEndWin->SetViewMask(0); //objwin invisible } else { mpEndWin->SetViewMask(1); //objwin visible } } UpdateVisibility(); } else //IsHideMode { //bVisible = TRUE; if (!(mpStartWin->IsNullObject())) //null_project { mpStartWin->SetViewMask(1); } if (!(mpEndWin->IsNullObject())) //null_project { mpEndWin->SetViewMask(1); } UpdateVisibility(); } if ( (mpStartWin->GetBodyText() != ByteString("null")) && //null_project (mpEndWin->GetBodyText() != ByteString("null")) && IsVisible()) //null_project { mpParent->DrawLine( mEnd, mStart ); mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2))); } } void Connector::UpdatePosition( ObjectWin* pWin, BOOL bPaint ) { // more than one call ? // Point OldStart, OldEnd; static ULONG nCallCount = 0; //MyApp *pApp = (MyApp*)GetpApp(); //SolDep *pSoldep = pApp->GetSolDep(); if (msbHideMode) bVisible = 1; if ( nCallCount ) // only one call nCallCount++; else { nCallCount++; while ( nCallCount ) { if ( bPaint ) { OldStart = mStart; OldEnd = mEnd; } mCenter = GetMiddle(); mStart=mpStartWin->GetFixPoint( mCenter, bPaint ); mEnd=mpEndWin->GetFixPoint( mCenter, bPaint ); if ( bPaint ) { mpParent->Invalidate( Rectangle( OldStart, OldEnd )); mpParent->Invalidate( Rectangle( OldEnd - Point( 2, 2), OldEnd + Point( 2, 2))); //Don't paint "null_project" connectors if ( (mpStartWin->GetBodyText() != ByteString("null")) && //null_project (mpEndWin->GetBodyText() != ByteString("null"))) //null_project { Paint ( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3))); Paint ( Rectangle( mEnd, mStart )); } } nCallCount--; } } } USHORT Connector::Save( SvFileStream& rOutFile ) { rOutFile << mpStartWin->GetId(); rOutFile << mpEndWin->GetId(); return 0; } USHORT Connector::Load( SvFileStream& rInFile ) { rInFile >> mnStartId; rInFile >> mnEndId; return 0; } ObjectWin* Connector::GetOtherWin( ObjectWin* pWin ) { // get correspondent object ptr if ( mpStartWin == pWin ) return mpEndWin; else if ( mpEndWin == pWin ) return mpStartWin; return NULL; } ULONG Connector::GetOtherId( ULONG nId ) { // get correspondent object id if ( mnStartId == nId ) return mnEndId; else if ( mnEndId == nId ) return mnStartId; return NULL; } ULONG Connector::GetLen() { double dx, dy; dx = mStart.X() - mEnd.X(); dy = mStart.Y() - mEnd.Y(); return (ULONG) sqrt( dx * dx + dy * dy ); } BOOL Connector::IsStart( ObjectWin* pWin ) { return pWin == mpStartWin; }<|endoftext|>
<commit_before>#include <common.h> #include <Tokenizer.h> #include <ErrorProcessor.h> #include <Tools.h> namespace Lspl { namespace Parser { /////////////////////////////////////////////////////////////////////////////// void CToken::Print( ostream& out ) const { switch( Type ) { case TT_Regexp: out << '"' << Text << '"'; break; case TT_Number: out << Number; break; case TT_Identifier: out << Text; break; case TT_Dot: out << "."; break; case TT_Comma: out << ","; break; case TT_DollarSign: out << "$"; break; case TT_NumberSign: out << "#"; break; case TT_VerticalBar: out << "|"; break; case TT_OpeningBrace: out << "{"; break; case TT_ClosingBrace: out << "}"; break; case TT_OpeningBracket: out << "["; break; case TT_ClosingBracket: out << "]"; break; case TT_OpeningParenthesis: out << "("; break; case TT_ClosingParenthesis: out << ")"; break; case TT_EqualSign: out << "="; break; case TT_DoubleEqualSign: out << "=="; break; case TT_Tilde: out << "~"; break; case TT_TildeGreaterThanSign: out << "~>"; break; case TT_LessThanSign: out << "<"; break; case TT_DoubleLessThanSign: out << "<<"; break; case TT_GreaterThanSign: out << ">"; break; case TT_DoubleGreaterThanSign: out << ">>"; break; case TT_ExclamationPointEqualSign: out << "!="; break; } } /////////////////////////////////////////////////////////////////////////////// inline bool IsIdentifierCharacter( char c ) { return !IsByteAsciiSymbol( c ) || ( isalnum( c, locale::classic() ) || c == '-' || c == '_' ); } /////////////////////////////////////////////////////////////////////////////// CTokenizer::CTokenizer( CErrorProcessor& _errorProcessor ) : errorProcessor( _errorProcessor ) { Reset(); } CTokenizer::~CTokenizer() { Reset(); } void CTokenizer::Reset() { clear(); reset(); } void CTokenizer::TokenizeLine( CSharedFileLine _line ) { initialize( _line ); for( char c : line->Line ) { step( c ); offset++; } finalize(); } void CTokenizer::initialize( CSharedFileLine _line ) { check_logic( _line ); state = &CTokenizer::initialState; line = _line; text.clear(); offset = 0; } void CTokenizer::step( char c ) { ( this->*state )( c ); } void CTokenizer::finalize() { step( ' ' ); if( state == &CTokenizer::regexState ) { addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ ); errorProcessor.AddError( CError( CLineSegment( offset - text.length(), numeric_limits<size_t>::max() ), line, "newline in regular expression" ) ); } reset(); } void CTokenizer::reset() { state = nullptr; line = CSharedFileLine(); text.clear(); offset = 0; } void CTokenizer::addToken( TTokenType type, bool decreaseAnOffsetByOne ) { CLineSegment lineSegment( offset - text.length() ); if( decreaseAnOffsetByOne ) { lineSegment.Offset--; } push_back( CTokenPtr( new CToken( type, line, lineSegment ) ) ); CToken& token = *back(); switch( type ) { case TT_Regexp: token.Text = text; token.Length = text.length() + 2; break; case TT_Number: token.Number = stoul( text ); token.Length = text.length(); break; case TT_Identifier: token.Text = text; token.Length = text.length(); break; case TT_DoubleEqualSign: case TT_TildeGreaterThanSign: case TT_DoubleLessThanSign: case TT_DoubleGreaterThanSign: case TT_ExclamationPointEqualSign: token.Length = 2; break; default: break; } text.clear(); } void CTokenizer::checkIdentifier() { // check text } void CTokenizer::initialState( char c ) { switch( c ) { case ' ': break; // skip blank character case ';': state = &CTokenizer::commentState; break; case '.': addToken( TT_Dot ); break; case ',': addToken( TT_Comma ); break; case '$': addToken( TT_DollarSign ); break; case '#': addToken( TT_NumberSign ); break; case '|': addToken( TT_VerticalBar ); break; case '{': addToken( TT_OpeningBrace ); break; case '}': addToken( TT_ClosingBrace ); break; case '[': addToken( TT_OpeningBracket ); break; case ']': addToken( TT_ClosingBracket ); break; case '(': addToken( TT_OpeningParenthesis ); break; case ')': addToken( TT_ClosingParenthesis ); break; case '=': state = &CTokenizer::equalSignState; break; case '~': state = &CTokenizer::tildeState; break; case '<': state = &CTokenizer::lessThanSignState; break; case '>': state = &CTokenizer::greaterThanSignState; break; case '!': state = &CTokenizer::exclamationSignState; break; case '"': state = &CTokenizer::regexState; text.clear(); break; default: if( isdigit( c, locale::classic() ) ) { state = &CTokenizer::numberState; text.assign( 1, c ); } else if( IsIdentifierCharacter( c ) ) { state = &CTokenizer::indentifierState; text.assign( 1, c ); } else { errorProcessor.AddError( CError( CLineSegment( offset ), line, "unknown character " + c, ES_CriticalError ) ); } break; } } void CTokenizer::commentState( char /* c */ ) { // just skip any characters after ';' } void CTokenizer::regexState( char c ) { if( c == '"' ) { addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ ); state = &CTokenizer::initialState; } else { if( c == '\\' ) { state = &CTokenizer::regexStateAfterBackslash; } text.append( 1, c ); } } void CTokenizer::regexStateAfterBackslash( char c ) { state = &CTokenizer::regexState; text.append( 1, c ); } void CTokenizer::numberState( char c ) { if( isdigit( c, locale::classic() ) ) { text.append( 1, c ); } else { addToken( TT_Number ); state = &CTokenizer::initialState; step( c ); } } void CTokenizer::indentifierState( char c ) { if( IsIdentifierCharacter( c ) ) { text.append( 1, c ); } else { checkIdentifier(); addToken( TT_Identifier ); state = &CTokenizer::initialState; step( c ); } } void CTokenizer::tildeState( char c ) { state = &CTokenizer::initialState; if( c == '>' ) { addToken( TT_TildeGreaterThanSign, true /* decreaseAnOffsetByOne */ ); } else { addToken( TT_Tilde, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::equalSignState( char c ) { state = &CTokenizer::initialState; if( c == '=' ) { addToken( TT_DoubleEqualSign, true /* decreaseAnOffsetByOne */ ); } else { addToken( TT_EqualSign, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::lessThanSignState( char c ) { state = &CTokenizer::initialState; if( c == '<' ) { addToken( TT_DoubleLessThanSign, true /* decreaseAnOffsetByOne */ ); } else { addToken( TT_LessThanSign, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::greaterThanSignState( char c ) { state = &CTokenizer::initialState; if( c == '>' ) { addToken( TT_DoubleGreaterThanSign, true/* decreaseAnOffsetByOne */ ); } else { addToken( TT_GreaterThanSign, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::exclamationSignState( char c ) { if( c != '=' ) { errorProcessor.AddError( CError( CLineSegment( offset - 1, 2 ), line, "incorrect operation, you may possibly mean !=" ) ); } addToken( TT_ExclamationPointEqualSign, true/*decreaseAnOffsetByOne*/ ); state = &CTokenizer::initialState; } /////////////////////////////////////////////////////////////////////////////// } // end of Parser namespace } // end of Lspl namespace <commit_msg>small bug fixed<commit_after>#include <common.h> #include <Tokenizer.h> #include <ErrorProcessor.h> #include <Tools.h> namespace Lspl { namespace Parser { /////////////////////////////////////////////////////////////////////////////// void CToken::Print( ostream& out ) const { switch( Type ) { case TT_Regexp: out << '"' << Text << '"'; break; case TT_Number: out << Number; break; case TT_Identifier: out << Text; break; case TT_Dot: out << "."; break; case TT_Comma: out << ","; break; case TT_DollarSign: out << "$"; break; case TT_NumberSign: out << "#"; break; case TT_VerticalBar: out << "|"; break; case TT_OpeningBrace: out << "{"; break; case TT_ClosingBrace: out << "}"; break; case TT_OpeningBracket: out << "["; break; case TT_ClosingBracket: out << "]"; break; case TT_OpeningParenthesis: out << "("; break; case TT_ClosingParenthesis: out << ")"; break; case TT_EqualSign: out << "="; break; case TT_DoubleEqualSign: out << "=="; break; case TT_Tilde: out << "~"; break; case TT_TildeGreaterThanSign: out << "~>"; break; case TT_LessThanSign: out << "<"; break; case TT_DoubleLessThanSign: out << "<<"; break; case TT_GreaterThanSign: out << ">"; break; case TT_DoubleGreaterThanSign: out << ">>"; break; case TT_ExclamationPointEqualSign: out << "!="; break; } } /////////////////////////////////////////////////////////////////////////////// inline bool IsIdentifierCharacter( char c ) { return !IsByteAsciiSymbol( c ) || ( isalnum( c, locale::classic() ) || c == '-' || c == '_' ); } /////////////////////////////////////////////////////////////////////////////// CTokenizer::CTokenizer( CErrorProcessor& _errorProcessor ) : errorProcessor( _errorProcessor ) { Reset(); } CTokenizer::~CTokenizer() { Reset(); } void CTokenizer::Reset() { clear(); reset(); } void CTokenizer::TokenizeLine( CSharedFileLine _line ) { initialize( _line ); for( char c : line->Line ) { step( c ); offset++; } finalize(); } void CTokenizer::initialize( CSharedFileLine _line ) { check_logic( _line ); state = &CTokenizer::initialState; line = _line; text.clear(); offset = 0; } void CTokenizer::step( char c ) { ( this->*state )( c ); } void CTokenizer::finalize() { step( ' ' ); if( state == &CTokenizer::regexState ) { addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ ); errorProcessor.AddError( CError( CLineSegment( offset - text.length(), numeric_limits<size_t>::max() ), line, "newline in regular expression" ) ); } reset(); } void CTokenizer::reset() { state = nullptr; line = CSharedFileLine(); text.clear(); offset = 0; } void CTokenizer::addToken( TTokenType type, bool decreaseAnOffsetByOne ) { CLineSegment lineSegment( offset - text.length() ); if( decreaseAnOffsetByOne ) { lineSegment.Offset--; } push_back( CTokenPtr( new CToken( type, line, lineSegment ) ) ); CToken& token = *back(); switch( type ) { case TT_Regexp: token.Text = text; token.Length = text.length() + 2; break; case TT_Number: token.Number = stoul( text ); token.Length = text.length(); break; case TT_Identifier: token.Text = text; token.Length = text.length(); break; case TT_DoubleEqualSign: case TT_TildeGreaterThanSign: case TT_DoubleLessThanSign: case TT_DoubleGreaterThanSign: case TT_ExclamationPointEqualSign: token.Length = 2; break; default: break; } text.clear(); } void CTokenizer::checkIdentifier() { // check text } void CTokenizer::initialState( char c ) { switch( c ) { case ' ': break; // skip blank character case ';': state = &CTokenizer::commentState; break; case '.': addToken( TT_Dot ); break; case ',': addToken( TT_Comma ); break; case '$': addToken( TT_DollarSign ); break; case '#': addToken( TT_NumberSign ); break; case '|': addToken( TT_VerticalBar ); break; case '{': addToken( TT_OpeningBrace ); break; case '}': addToken( TT_ClosingBrace ); break; case '[': addToken( TT_OpeningBracket ); break; case ']': addToken( TT_ClosingBracket ); break; case '(': addToken( TT_OpeningParenthesis ); break; case ')': addToken( TT_ClosingParenthesis ); break; case '=': state = &CTokenizer::equalSignState; break; case '~': state = &CTokenizer::tildeState; break; case '<': state = &CTokenizer::lessThanSignState; break; case '>': state = &CTokenizer::greaterThanSignState; break; case '!': state = &CTokenizer::exclamationSignState; break; case '"': state = &CTokenizer::regexState; text.clear(); break; default: if( isdigit( c, locale::classic() ) ) { state = &CTokenizer::numberState; text.assign( 1, c ); } else if( IsIdentifierCharacter( c ) ) { state = &CTokenizer::indentifierState; text.assign( 1, c ); } else { errorProcessor.AddError( CError( CLineSegment( offset ), line, "unknown character " + string( 1, c ), ES_CriticalError ) ); } break; } } void CTokenizer::commentState( char /* c */ ) { // just skip any characters after ';' } void CTokenizer::regexState( char c ) { if( c == '"' ) { addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ ); state = &CTokenizer::initialState; } else { if( c == '\\' ) { state = &CTokenizer::regexStateAfterBackslash; } text.append( 1, c ); } } void CTokenizer::regexStateAfterBackslash( char c ) { state = &CTokenizer::regexState; text.append( 1, c ); } void CTokenizer::numberState( char c ) { if( isdigit( c, locale::classic() ) ) { text.append( 1, c ); } else { addToken( TT_Number ); state = &CTokenizer::initialState; step( c ); } } void CTokenizer::indentifierState( char c ) { if( IsIdentifierCharacter( c ) ) { text.append( 1, c ); } else { checkIdentifier(); addToken( TT_Identifier ); state = &CTokenizer::initialState; step( c ); } } void CTokenizer::tildeState( char c ) { state = &CTokenizer::initialState; if( c == '>' ) { addToken( TT_TildeGreaterThanSign, true /* decreaseAnOffsetByOne */ ); } else { addToken( TT_Tilde, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::equalSignState( char c ) { state = &CTokenizer::initialState; if( c == '=' ) { addToken( TT_DoubleEqualSign, true /* decreaseAnOffsetByOne */ ); } else { addToken( TT_EqualSign, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::lessThanSignState( char c ) { state = &CTokenizer::initialState; if( c == '<' ) { addToken( TT_DoubleLessThanSign, true /* decreaseAnOffsetByOne */ ); } else { addToken( TT_LessThanSign, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::greaterThanSignState( char c ) { state = &CTokenizer::initialState; if( c == '>' ) { addToken( TT_DoubleGreaterThanSign, true/* decreaseAnOffsetByOne */ ); } else { addToken( TT_GreaterThanSign, true /* decreaseAnOffsetByOne */ ); step( c ); } } void CTokenizer::exclamationSignState( char c ) { if( c != '=' ) { errorProcessor.AddError( CError( CLineSegment( offset - 1, 2 ), line, "incorrect operation, you may possibly mean !=" ) ); } addToken( TT_ExclamationPointEqualSign, true/*decreaseAnOffsetByOne*/ ); state = &CTokenizer::initialState; } /////////////////////////////////////////////////////////////////////////////// } // end of Parser namespace } // end of Lspl namespace <|endoftext|>
<commit_before>#ifdef __unix__ #include <iostream> #include <signal.h> #include <stdio.h> #include <unistd.h> #include "Tools.h" void StartBotProcess(const std::string& CommandLine) { FILE* pipe = popen(CommandLine.c_str(), "r"); if (!pipe) { std::cerr << "Can't launch command '" << CommandLine << "'" << std::endl; return; } int returnCode = pclose(pipe); if (returnCode != 0) { std::cerr << "Failed to finish command '" << CommandLine << "', code: " << returnCode << std::endl; } } void SleepFor(int seconds) { sleep(seconds); } void KillSc2Process(unsigned long pid) { kill(pid, SIGKILL); } bool MoveReplayFile(char* lpExistingFileName, char* lpNewFileName) { // todo throw "MoveFile is not implemented for linux yet."; } #endif<commit_msg>Fix linking error (again, but for Unix this time)<commit_after>#ifdef __unix__ #include <iostream> #include <signal.h> #include <stdio.h> #include <unistd.h> #include "Tools.h" void StartBotProcess(const std::string& CommandLine) { FILE* pipe = popen(CommandLine.c_str(), "r"); if (!pipe) { std::cerr << "Can't launch command '" << CommandLine << "'" << std::endl; return; } int returnCode = pclose(pipe); if (returnCode != 0) { std::cerr << "Failed to finish command '" << CommandLine << "', code: " << returnCode << std::endl; } } void SleepFor(int seconds) { sleep(seconds); } void KillSc2Process(unsigned long pid) { kill(pid, SIGKILL); } bool MoveReplayFile(const char* lpExistingFileName, const char* lpNewFileName) { // todo throw "MoveFile is not implemented for linux yet."; } #endif<|endoftext|>
<commit_before>/* * Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * * This program 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 * any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "DBCStores.h" #include "DataStore.h" #include "NGLog.h" SERVER_DECL DBCStorage<GemPropertyEntry> dbcGemProperty; SERVER_DECL DBCStorage<ItemSetEntry> dbcItemSet; SERVER_DECL DBCStorage<Lock> dbcLock; SERVER_DECL DBCStorage<SpellEntry> dbcSpell; SERVER_DECL DBCStorage<SpellDuration> dbcSpellDuration; SERVER_DECL DBCStorage<SpellRange> dbcSpellRange; SERVER_DECL DBCStorage<emoteentry> dbcEmoteEntry; SERVER_DECL DBCStorage<SpellRadius> dbcSpellRadius; SERVER_DECL DBCStorage<SpellCastTime> dbcSpellCastTime; SERVER_DECL DBCStorage<AreaTable> dbcArea; SERVER_DECL DBCStorage<FactionTemplateDBC> dbcFactionTemplate; SERVER_DECL DBCStorage<FactionDBC> dbcFaction; SERVER_DECL DBCStorage<EnchantEntry> dbcEnchant; SERVER_DECL DBCStorage<RandomProps> dbcRandomProps; SERVER_DECL DBCStorage<skilllinespell> dbcSkillLineSpell; SERVER_DECL DBCStorage<skilllineentry> dbcSkillLine; SERVER_DECL DBCStorage<DBCTaxiNode> dbcTaxiNode; SERVER_DECL DBCStorage<DBCTaxiPath> dbcTaxiPath; SERVER_DECL DBCStorage<DBCTaxiPathNode> dbcTaxiPathNode; SERVER_DECL DBCStorage<AuctionHouseDBC> dbcAuctionHouse; SERVER_DECL DBCStorage<TalentEntry> dbcTalent; SERVER_DECL DBCStorage<CreatureSpellDataEntry> dbcCreatureSpellData; SERVER_DECL DBCStorage<CreatureFamilyEntry> dbcCreatureFamily; SERVER_DECL DBCStorage<CharClassEntry> dbcCharClass; SERVER_DECL DBCStorage<CharRaceEntry> dbcCharRace; SERVER_DECL DBCStorage<MapEntry> dbcMap; SERVER_DECL DBCStorage<ItemExtendedCostEntry> dbcItemExtendedCost; SERVER_DECL DBCStorage<ItemRandomSuffixEntry> dbcItemRandomSuffix; const char * ItemSetFormat = "uuxxxxxxxxxxxxxxxuuuuuuuuuxxxxxxxxxuuuuuuuuuuuuuuuuuu"; const char * LockFormat = "uuuuuuxxxuuuuuxxxuuuuuxxxxxxxxxxx"; const char * EmoteEntryFormat = "uxuuuuxuxuxxxxxxxxx"; const char * skilllinespellFormat = "uuuxxxxxuuuuxxu"; const char * EnchantEntrYFormat = "uuuuuuuuuuuuuxxxxxxxxxxxxxxxxxuuuu"; const char * GemPropertyEntryFormat = "uuuuu"; const char * skilllineentrYFormat = "uuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * spellentrYFormat = "uuuuuuuuuuuuuuuuuuuuuuuuuuuuuiuuuuuuuuuufuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuffffffiiiiiiuuuuuuuuuuuuuuufffuuuuuuuuuuuufffuuuuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxuuuuuuuuuuifffuuuuuu"; const char * itemextendedcostFormat = "uuuuuuuuuuuuu"; const char * talententryFormat = "uuuuuuuuuxxxxuxxuxxxx"; const char * spellcasttimeFormat = "uuxx"; const char * spellradiusFormat = "ufxf"; const char * spellrangeFormat = "uffxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * spelldurationFormat = "uuuu"; const char * randompropsFormat = "uxuuuxxxxxxxxxxxxxxxxxxx"; const char * areatableFormat = "uuuuuxxxuxuxxxxxxxxxxxxxxxxxuxxxxxx"; const char * factiontemplatedbcFormat = "uuuuuuuuuuuuuu"; const char * auctionhousedbcFormat = "uuuuxxxxxxxxxxxxxxxxx"; const char * factiondbcFormat = "uiuuuuxxxxiiiixxxxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * dbctaxinodeFormat = "uufffxxxxxxxxxxxxxxxxxuu"; const char * dbctaxipathFormat = "uuuu"; const char * dbctaxipathnodeFormat = "uuuufffuuxx"; const char * creaturespelldataFormat = "uuuuuuuuu"; const char * charraceFormat = "uxuxxxxxuxxxxuxxxxxxxxxxxxxxxxxxxxx"; const char * charclassFormat = "uxuxxxxxxxxxxxxxxxxxxxxx"; const char * creaturefamilyFormat = "ufufuuuuxxxxxxxxxxxxxxxxxx"; const char * mapentryFormat = "uxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * itemrandomsuffixformat = "uxxxxxxxxxxxxxxxxxxuuuuuu"; template<class T> bool loader_stub(const char * filename, const char * format, bool ind, T& l) { Log.Notice("DBC", "Loading %s.", filename); return l.Load(filename, format, ind); } #define LOAD_DBC(filename, format, ind, stor) if(!loader_stub(filename, format, ind, stor)) { return false; } bool LoadDBCs() { LOAD_DBC("DBC/ItemSet.dbc", ItemSetFormat, true, dbcItemSet); LOAD_DBC("DBC/Lock.dbc", LockFormat, true, dbcLock); LOAD_DBC("DBC/EmotesText.dbc", EmoteEntryFormat, true, dbcEmoteEntry); LOAD_DBC("DBC/SkillLineAbility.dbc", skilllinespellFormat, false, dbcSkillLineSpell); LOAD_DBC("DBC/SpellItemEnchantment.dbc", EnchantEntrYFormat, true, dbcEnchant); LOAD_DBC("DBC/GemProperties.dbc", GemPropertyEntryFormat, true, dbcGemProperty); LOAD_DBC("DBC/SkillLine.dbc", skilllineentrYFormat, true, dbcSkillLine); LOAD_DBC("DBC/Spell.dbc", spellentrYFormat, true, dbcSpell); LOAD_DBC("DBC/ItemExtendedCost.dbc", itemextendedcostFormat, true, dbcItemExtendedCost); LOAD_DBC("DBC/Talent.dbc", talententryFormat, true, dbcTalent); LOAD_DBC("DBC/SpellCastTimes.dbc", spellcasttimeFormat, true, dbcSpellCastTime); LOAD_DBC("DBC/SpellRadius.dbc", spellradiusFormat, true, dbcSpellRadius); LOAD_DBC("DBC/SpellRange.dbc", spellrangeFormat, true, dbcSpellRange); LOAD_DBC("DBC/SpellDuration.dbc", spelldurationFormat, true, dbcSpellDuration); LOAD_DBC("DBC/ItemRandomProperties.dbc", randompropsFormat, true, dbcRandomProps); LOAD_DBC("DBC/AreaTable.dbc", areatableFormat, true, dbcArea); LOAD_DBC("DBC/FactionTemplate.dbc", factiontemplatedbcFormat, true, dbcFactionTemplate); LOAD_DBC("DBC/Faction.dbc", factiondbcFormat, true, dbcFaction); LOAD_DBC("DBC/TaxiNodes.dbc", dbctaxinodeFormat, false, dbcTaxiNode); LOAD_DBC("DBC/TaxiPath.dbc", dbctaxipathFormat, false, dbcTaxiPath); LOAD_DBC("DBC/TaxiPathNode.dbc", dbctaxipathnodeFormat, false, dbcTaxiPathNode); LOAD_DBC("DBC/CreatureSpellData.dbc", creaturespelldataFormat, true, dbcCreatureSpellData); LOAD_DBC("DBC/CreatureFamily.dbc", creaturefamilyFormat, true, dbcCreatureFamily); LOAD_DBC("DBC/ChrRaces.dbc", charraceFormat, true, dbcCharRace); LOAD_DBC("DBC/ChrClasses.dbc", charclassFormat, true, dbcCharClass); LOAD_DBC("DBC/Map.dbc", mapentryFormat, true, dbcMap); LOAD_DBC("DBC/AuctionHouse.dbc", auctionhousedbcFormat, true, dbcAuctionHouse); LOAD_DBC("DBC/ItemRandomSuffix.dbc", itemrandomsuffixformat, true, dbcItemRandomSuffix); return true; } <commit_msg>* 2.3.0 dbc updates<commit_after>/* * Ascent MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * * This program 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 * any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "DBCStores.h" #include "DataStore.h" #include "NGLog.h" SERVER_DECL DBCStorage<GemPropertyEntry> dbcGemProperty; SERVER_DECL DBCStorage<ItemSetEntry> dbcItemSet; SERVER_DECL DBCStorage<Lock> dbcLock; SERVER_DECL DBCStorage<SpellEntry> dbcSpell; SERVER_DECL DBCStorage<SpellDuration> dbcSpellDuration; SERVER_DECL DBCStorage<SpellRange> dbcSpellRange; SERVER_DECL DBCStorage<emoteentry> dbcEmoteEntry; SERVER_DECL DBCStorage<SpellRadius> dbcSpellRadius; SERVER_DECL DBCStorage<SpellCastTime> dbcSpellCastTime; SERVER_DECL DBCStorage<AreaTable> dbcArea; SERVER_DECL DBCStorage<FactionTemplateDBC> dbcFactionTemplate; SERVER_DECL DBCStorage<FactionDBC> dbcFaction; SERVER_DECL DBCStorage<EnchantEntry> dbcEnchant; SERVER_DECL DBCStorage<RandomProps> dbcRandomProps; SERVER_DECL DBCStorage<skilllinespell> dbcSkillLineSpell; SERVER_DECL DBCStorage<skilllineentry> dbcSkillLine; SERVER_DECL DBCStorage<DBCTaxiNode> dbcTaxiNode; SERVER_DECL DBCStorage<DBCTaxiPath> dbcTaxiPath; SERVER_DECL DBCStorage<DBCTaxiPathNode> dbcTaxiPathNode; SERVER_DECL DBCStorage<AuctionHouseDBC> dbcAuctionHouse; SERVER_DECL DBCStorage<TalentEntry> dbcTalent; SERVER_DECL DBCStorage<CreatureSpellDataEntry> dbcCreatureSpellData; SERVER_DECL DBCStorage<CreatureFamilyEntry> dbcCreatureFamily; SERVER_DECL DBCStorage<CharClassEntry> dbcCharClass; SERVER_DECL DBCStorage<CharRaceEntry> dbcCharRace; SERVER_DECL DBCStorage<MapEntry> dbcMap; SERVER_DECL DBCStorage<ItemExtendedCostEntry> dbcItemExtendedCost; SERVER_DECL DBCStorage<ItemRandomSuffixEntry> dbcItemRandomSuffix; const char * ItemSetFormat = "uuxxxxxxxxxxxxxxxuuuuuuuuuxxxxxxxxxuuuuuuuuuuuuuuuuuu"; const char * LockFormat = "uuuuuuxxxuuuuuxxxuuuuuxxxxxxxxxxx"; const char * EmoteEntryFormat = "uxuuuuxuxuxxxxxxxxx"; const char * skilllinespellFormat = "uuuxxxxxuuuuxxu"; const char * EnchantEntrYFormat = "uuuuuuuuuuuuuxxxxxxxxxxxxxxxxxuuuu"; const char * GemPropertyEntryFormat = "uuuuu"; const char * skilllineentrYFormat = "uuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * spellentrYFormat = "uuuuuuuuuuuuuuuuuuuuuuuuuuuuuiuuuuuuuuuufuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuffffffiiiiiiuuuuuuuuuuuuuuufffuuuuuuuuuuuufffuuuuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxuuuuuuuuuuifffuuuuuu"; const char * itemextendedcostFormat = "uuuuuuuuuuuuux"; const char * talententryFormat = "uuuuuuuuuxxxxuxxuxxxx"; const char * spellcasttimeFormat = "uuxx"; const char * spellradiusFormat = "ufxf"; const char * spellrangeFormat = "uffxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * spelldurationFormat = "uuuu"; const char * randompropsFormat = "uxuuuxxxxxxxxxxxxxxxxxxx"; const char * areatableFormat = "uuuuuxxxuxuxxxxxxxxxxxxxxxxxuxxxxxx"; const char * factiontemplatedbcFormat = "uuuuuuuuuuuuuu"; const char * auctionhousedbcFormat = "uuuuxxxxxxxxxxxxxxxxx"; const char * factiondbcFormat = "uiuuuuxxxxiiiixxxxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * dbctaxinodeFormat = "uufffxxxxxxxxxxxxxxxxxuu"; const char * dbctaxipathFormat = "uuuu"; const char * dbctaxipathnodeFormat = "uuuufffuuxx"; const char * creaturespelldataFormat = "uuuuuuuuu"; const char * charraceFormat = "uxuxxxxxuxxxxuxxxxxxxxxxxxxxxxxxxxx"; const char * charclassFormat = "uxuxxxxxxxxxxxxxxxxxxxxx"; const char * creaturefamilyFormat = "ufufuuuuxxxxxxxxxxxxxxxxxx"; const char * mapentryFormat = "uxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; const char * itemrandomsuffixformat = "uxxxxxxxxxxxxxxxxxxuuuuuu"; template<class T> bool loader_stub(const char * filename, const char * format, bool ind, T& l) { Log.Notice("DBC", "Loading %s.", filename); return l.Load(filename, format, ind); } #define LOAD_DBC(filename, format, ind, stor) if(!loader_stub(filename, format, ind, stor)) { return false; } bool LoadDBCs() { LOAD_DBC("DBC/ItemSet.dbc", ItemSetFormat, true, dbcItemSet); LOAD_DBC("DBC/Lock.dbc", LockFormat, true, dbcLock); LOAD_DBC("DBC/EmotesText.dbc", EmoteEntryFormat, true, dbcEmoteEntry); LOAD_DBC("DBC/SkillLineAbility.dbc", skilllinespellFormat, false, dbcSkillLineSpell); LOAD_DBC("DBC/SpellItemEnchantment.dbc", EnchantEntrYFormat, true, dbcEnchant); LOAD_DBC("DBC/GemProperties.dbc", GemPropertyEntryFormat, true, dbcGemProperty); LOAD_DBC("DBC/SkillLine.dbc", skilllineentrYFormat, true, dbcSkillLine); LOAD_DBC("DBC/Spell.dbc", spellentrYFormat, true, dbcSpell); LOAD_DBC("DBC/ItemExtendedCost.dbc", itemextendedcostFormat, true, dbcItemExtendedCost); LOAD_DBC("DBC/Talent.dbc", talententryFormat, true, dbcTalent); LOAD_DBC("DBC/SpellCastTimes.dbc", spellcasttimeFormat, true, dbcSpellCastTime); LOAD_DBC("DBC/SpellRadius.dbc", spellradiusFormat, true, dbcSpellRadius); LOAD_DBC("DBC/SpellRange.dbc", spellrangeFormat, true, dbcSpellRange); LOAD_DBC("DBC/SpellDuration.dbc", spelldurationFormat, true, dbcSpellDuration); LOAD_DBC("DBC/ItemRandomProperties.dbc", randompropsFormat, true, dbcRandomProps); LOAD_DBC("DBC/AreaTable.dbc", areatableFormat, true, dbcArea); LOAD_DBC("DBC/FactionTemplate.dbc", factiontemplatedbcFormat, true, dbcFactionTemplate); LOAD_DBC("DBC/Faction.dbc", factiondbcFormat, true, dbcFaction); LOAD_DBC("DBC/TaxiNodes.dbc", dbctaxinodeFormat, false, dbcTaxiNode); LOAD_DBC("DBC/TaxiPath.dbc", dbctaxipathFormat, false, dbcTaxiPath); LOAD_DBC("DBC/TaxiPathNode.dbc", dbctaxipathnodeFormat, false, dbcTaxiPathNode); LOAD_DBC("DBC/CreatureSpellData.dbc", creaturespelldataFormat, true, dbcCreatureSpellData); LOAD_DBC("DBC/CreatureFamily.dbc", creaturefamilyFormat, true, dbcCreatureFamily); LOAD_DBC("DBC/ChrRaces.dbc", charraceFormat, true, dbcCharRace); LOAD_DBC("DBC/ChrClasses.dbc", charclassFormat, true, dbcCharClass); LOAD_DBC("DBC/Map.dbc", mapentryFormat, true, dbcMap); LOAD_DBC("DBC/AuctionHouse.dbc", auctionhousedbcFormat, true, dbcAuctionHouse); LOAD_DBC("DBC/ItemRandomSuffix.dbc", itemrandomsuffixformat, true, dbcItemRandomSuffix); return true; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // stable_double.hpp // // Contains an implementation of an underflow- and overflow-resistant // alternative to floating point numbers // #ifndef structures_stable_double_hpp #define structures_stable_double_hpp #include <ostream> #include <cmath> #include <limits> namespace structures { using namespace std; /* * A class that supports basic floating point arithmetic operations on internal values stored * in log-transformed space to reduce risk of overflow and underflow at the cost of precision * in some ranges of values */ class StableDouble { public: /// Defaults to 0 StableDouble(); /// Convert from a double StableDouble(double x); /// Construct from log-transformed absolute value and a sign StableDouble(double log_abs_x, bool positive); /// Convert to double inline double to_double() const; /// Unary operators inline StableDouble operator-() const; inline StableDouble inverse() const; /// Binary operators with StableDoubles inline StableDouble operator*(const StableDouble& other) const; inline StableDouble operator/(const StableDouble& other) const; inline StableDouble operator+(const StableDouble& other) const; inline StableDouble operator-(const StableDouble& other) const; /// Binary operators with standard doubles inline StableDouble operator*(const double other) const; inline StableDouble operator/(const double other) const; inline StableDouble operator+(const double other) const; inline StableDouble operator-(const double other) const; /// Assignment operators with StableDoubles inline StableDouble& operator*=(const StableDouble& other); inline StableDouble& operator/=(const StableDouble& other); inline StableDouble& operator+=(const StableDouble& other); inline StableDouble& operator-=(const StableDouble& other); /// Assignment operators with standard doubles inline StableDouble& operator*=(const double other); inline StableDouble& operator/=(const double other); inline StableDouble& operator+=(const double other); inline StableDouble& operator-=(const double other); // Comparison operators with StableDoubles inline bool operator<(const StableDouble& other) const; inline bool operator>(const StableDouble& other) const; inline bool operator<=(const StableDouble& other) const; inline bool operator>=(const StableDouble& other) const; // Comparison operators with standard doubles inline bool operator<(const double other) const; inline bool operator>(const double other) const; inline bool operator<=(const double other) const; inline bool operator>=(const double other) const; // Equality operators with StableDoubles inline bool operator==(const StableDouble& other) const; inline bool operator!=(const StableDouble& other) const; // Equality operators with standard doubles inline bool operator==(const double other) const; inline bool operator!=(const double other) const; friend ostream& operator<<(ostream& out, const StableDouble& val); private: // Logarithm of the absolute value double log_abs_x; // Sign bool positive; // Returns the log of the sum of two log-transformed values without taking them // out of log space. inline double add_log(const double log_x, const double log_y) const; // Returns the log of the difference of two log-transformed values without taking // them out of log space. inline double subtract_log(const double log_x, const double log_y) const; }; ostream& operator<<(ostream& out, const StableDouble& val); inline double StableDouble::add_log(const double log_x, const double log_y) const { return log_x > log_y ? log_x + log(1.0 + exp(log_y - log_x)) : log_y + log(1.0 + exp(log_x - log_y)); } inline double StableDouble::subtract_log(const double log_x, const double log_y) const { return log_x + log(1.0 - exp(log_y - log_x)); } inline double StableDouble::to_double() const { return positive ? exp(log_abs_x) : -exp(log_abs_x); } inline StableDouble StableDouble::inverse() const { return StableDouble(-log_abs_x, positive); } inline StableDouble StableDouble::operator-() const { return StableDouble(log_abs_x, !positive); } inline StableDouble StableDouble::operator*(const StableDouble& other) const { return StableDouble(log_abs_x + other.log_abs_x, positive == other.positive); } inline StableDouble StableDouble::operator/(const StableDouble& other) const { return StableDouble(log_abs_x - other.log_abs_x, positive == other.positive); } inline StableDouble StableDouble::operator+(const StableDouble& other) const { if (positive == other.positive) { return StableDouble(add_log(log_abs_x, other.log_abs_x), positive); } else if (log_abs_x == other.log_abs_x) { return StableDouble(); } else if (log_abs_x > other.log_abs_x) { return StableDouble(subtract_log(log_abs_x, other.log_abs_x), positive); } else { return StableDouble(subtract_log(other.log_abs_x, log_abs_x), other.positive); } } inline StableDouble StableDouble::operator-(const StableDouble& other) const { return *this + (-other); } inline StableDouble StableDouble::operator*(const double other) const { return *this * StableDouble(other); } inline StableDouble StableDouble::operator/(const double other) const { return *this / StableDouble(other); } inline StableDouble StableDouble::operator+(const double other) const { return *this + StableDouble(other); } inline StableDouble StableDouble::operator-(const double other) const { return *this - StableDouble(other); } inline StableDouble& StableDouble::operator*=(const StableDouble& other) { *this = *this * other; return *this; } inline StableDouble& StableDouble::operator/=(const StableDouble& other) { *this = *this / other; return *this; } inline StableDouble& StableDouble::operator+=(const StableDouble& other) { *this = *this + other; return *this; } inline StableDouble& StableDouble::operator-=(const StableDouble& other) { *this = *this - other; return *this; } inline StableDouble& StableDouble::operator*=(const double other) { *this = *this * other; return *this; } inline StableDouble& StableDouble::operator/=(const double other) { *this = *this / other; return *this; } inline StableDouble& StableDouble::operator+=(const double other) { *this = *this + other; return *this; } inline StableDouble& StableDouble::operator-=(const double other) { *this = *this - other; return *this; } inline bool StableDouble::operator<(const StableDouble& other) const { if (positive != other.positive) { // make sure they're not both 0 with the sign arbitrarily set return other.positive && (log_abs_x != numeric_limits<double>::lowest() || other.log_abs_x != numeric_limits<double>::lowest()); } else { return positive ? (log_abs_x < other.log_abs_x) : (log_abs_x > other.log_abs_x) ; } } inline bool StableDouble::operator>(const StableDouble& other) const { return other < *this; } inline bool StableDouble::operator<=(const StableDouble& other) const { return !(other < *this); } inline bool StableDouble::operator>=(const StableDouble& other) const { return !(*this < other); } inline bool StableDouble::operator<(const double other) const { return *this < StableDouble(other); } inline bool StableDouble::operator>(const double other) const { return *this > StableDouble(other); } inline bool StableDouble::operator<=(const double other) const { return *this <= StableDouble(other); } inline bool StableDouble::operator>=(const double other) const { return *this >= StableDouble(other); } inline bool StableDouble::operator==(const StableDouble& other) const { return ((log_abs_x == other.log_abs_x) && (log_abs_x == numeric_limits<double>::lowest() || positive == other.positive)); } inline bool StableDouble::operator!=(const StableDouble& other) const { return !(*this == other); } inline bool StableDouble::operator==(const double other) const { return *this == StableDouble(other); } inline bool StableDouble::operator!=(const double other) const { return *this != StableDouble(other); } } #endif /* structures_stable_double_hpp */ <commit_msg>use log1p for improved stability<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // stable_double.hpp // // Contains an implementation of an underflow- and overflow-resistant // alternative to floating point numbers // #ifndef structures_stable_double_hpp #define structures_stable_double_hpp #include <ostream> #include <cmath> #include <limits> namespace structures { using namespace std; /* * A class that supports basic floating point arithmetic operations on internal values stored * in log-transformed space to reduce risk of overflow and underflow at the cost of precision * in some ranges of values */ class StableDouble { public: /// Defaults to 0 StableDouble(); /// Convert from a double StableDouble(double x); /// Construct from log-transformed absolute value and a sign StableDouble(double log_abs_x, bool positive); /// Convert to double inline double to_double() const; /// Unary operators inline StableDouble operator-() const; inline StableDouble inverse() const; /// Binary operators with StableDoubles inline StableDouble operator*(const StableDouble& other) const; inline StableDouble operator/(const StableDouble& other) const; inline StableDouble operator+(const StableDouble& other) const; inline StableDouble operator-(const StableDouble& other) const; /// Binary operators with standard doubles inline StableDouble operator*(const double other) const; inline StableDouble operator/(const double other) const; inline StableDouble operator+(const double other) const; inline StableDouble operator-(const double other) const; /// Assignment operators with StableDoubles inline StableDouble& operator*=(const StableDouble& other); inline StableDouble& operator/=(const StableDouble& other); inline StableDouble& operator+=(const StableDouble& other); inline StableDouble& operator-=(const StableDouble& other); /// Assignment operators with standard doubles inline StableDouble& operator*=(const double other); inline StableDouble& operator/=(const double other); inline StableDouble& operator+=(const double other); inline StableDouble& operator-=(const double other); // Comparison operators with StableDoubles inline bool operator<(const StableDouble& other) const; inline bool operator>(const StableDouble& other) const; inline bool operator<=(const StableDouble& other) const; inline bool operator>=(const StableDouble& other) const; // Comparison operators with standard doubles inline bool operator<(const double other) const; inline bool operator>(const double other) const; inline bool operator<=(const double other) const; inline bool operator>=(const double other) const; // Equality operators with StableDoubles inline bool operator==(const StableDouble& other) const; inline bool operator!=(const StableDouble& other) const; // Equality operators with standard doubles inline bool operator==(const double other) const; inline bool operator!=(const double other) const; friend ostream& operator<<(ostream& out, const StableDouble& val); private: // Logarithm of the absolute value double log_abs_x; // Sign bool positive; // Returns the log of the sum of two log-transformed values without taking them // out of log space. inline double add_log(const double log_x, const double log_y) const; // Returns the log of the difference of two log-transformed values without taking // them out of log space. inline double subtract_log(const double log_x, const double log_y) const; }; ostream& operator<<(ostream& out, const StableDouble& val); inline double StableDouble::add_log(const double log_x, const double log_y) const { return log_x > log_y ? log_x + log1p(exp(log_y - log_x)) : log_y + log(exp(log_x - log_y)); } inline double StableDouble::subtract_log(const double log_x, const double log_y) const { return log_x + log1p(-exp(log_y - log_x)); } inline double StableDouble::to_double() const { return positive ? exp(log_abs_x) : -exp(log_abs_x); } inline StableDouble StableDouble::inverse() const { return StableDouble(-log_abs_x, positive); } inline StableDouble StableDouble::operator-() const { return StableDouble(log_abs_x, !positive); } inline StableDouble StableDouble::operator*(const StableDouble& other) const { return StableDouble(log_abs_x + other.log_abs_x, positive == other.positive); } inline StableDouble StableDouble::operator/(const StableDouble& other) const { return StableDouble(log_abs_x - other.log_abs_x, positive == other.positive); } inline StableDouble StableDouble::operator+(const StableDouble& other) const { if (positive == other.positive) { return StableDouble(add_log(log_abs_x, other.log_abs_x), positive); } else if (log_abs_x == other.log_abs_x) { return StableDouble(); } else if (log_abs_x > other.log_abs_x) { return StableDouble(subtract_log(log_abs_x, other.log_abs_x), positive); } else { return StableDouble(subtract_log(other.log_abs_x, log_abs_x), other.positive); } } inline StableDouble StableDouble::operator-(const StableDouble& other) const { return *this + (-other); } inline StableDouble StableDouble::operator*(const double other) const { return *this * StableDouble(other); } inline StableDouble StableDouble::operator/(const double other) const { return *this / StableDouble(other); } inline StableDouble StableDouble::operator+(const double other) const { return *this + StableDouble(other); } inline StableDouble StableDouble::operator-(const double other) const { return *this - StableDouble(other); } inline StableDouble& StableDouble::operator*=(const StableDouble& other) { *this = *this * other; return *this; } inline StableDouble& StableDouble::operator/=(const StableDouble& other) { *this = *this / other; return *this; } inline StableDouble& StableDouble::operator+=(const StableDouble& other) { *this = *this + other; return *this; } inline StableDouble& StableDouble::operator-=(const StableDouble& other) { *this = *this - other; return *this; } inline StableDouble& StableDouble::operator*=(const double other) { *this = *this * other; return *this; } inline StableDouble& StableDouble::operator/=(const double other) { *this = *this / other; return *this; } inline StableDouble& StableDouble::operator+=(const double other) { *this = *this + other; return *this; } inline StableDouble& StableDouble::operator-=(const double other) { *this = *this - other; return *this; } inline bool StableDouble::operator<(const StableDouble& other) const { if (positive != other.positive) { // make sure they're not both 0 with the sign arbitrarily set return other.positive && (log_abs_x != numeric_limits<double>::lowest() || other.log_abs_x != numeric_limits<double>::lowest()); } else { return positive ? (log_abs_x < other.log_abs_x) : (log_abs_x > other.log_abs_x) ; } } inline bool StableDouble::operator>(const StableDouble& other) const { return other < *this; } inline bool StableDouble::operator<=(const StableDouble& other) const { return !(other < *this); } inline bool StableDouble::operator>=(const StableDouble& other) const { return !(*this < other); } inline bool StableDouble::operator<(const double other) const { return *this < StableDouble(other); } inline bool StableDouble::operator>(const double other) const { return *this > StableDouble(other); } inline bool StableDouble::operator<=(const double other) const { return *this <= StableDouble(other); } inline bool StableDouble::operator>=(const double other) const { return *this >= StableDouble(other); } inline bool StableDouble::operator==(const StableDouble& other) const { return ((log_abs_x == other.log_abs_x) && (log_abs_x == numeric_limits<double>::lowest() || positive == other.positive)); } inline bool StableDouble::operator!=(const StableDouble& other) const { return !(*this == other); } inline bool StableDouble::operator==(const double other) const { return *this == StableDouble(other); } inline bool StableDouble::operator!=(const double other) const { return *this != StableDouble(other); } } #endif /* structures_stable_double_hpp */ <|endoftext|>