text
stringlengths
54
60.6k
<commit_before>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_dfs_server.cpp * @version * @brief * @author duye * @date 2014-09-24 * @note * * 1. 2014-09-24 duye Created this file * */ #include <g_dfs_server.h> #include <g_logger.h> static const GInt8* LOG_PREFIX = "dfs.server.startup"; namespace gdfs { DfsServer::DfsServer() : gcom::HostServer() {} DfsServer::DfsServer(const std::string& dfs_cfg_file_path) : gcom::HostServer(), m_dfsCfgFilePath(dfs_cfg_file_path) {} DfsServer::~DfsServer() { gcom::ServerFactory::intance().destroyServer(m_httpServer); gcom::ServerFactory::intance().destroyServer(m_ftpServer); gcom::ServerFactory::intance().destroyServer(m_cliServer); } GResult DfsServer::start() { G_LOG_IN(); if (getServerState() == HOST_SERVER_WORK) { return G_YES; } if (m_dfsCfgFilePath.empty()) { m_dfsCfgFilePath = DEF_DFS_CFG_FILE_PATH; } IS_NO_R(m_cfgMgr.load(m_dfsCfgFilePath)); // init all service m_httpServer = gcom::ServerFactory::intance().createServer(HTTP_SERVER); m_ftpServer = gcom::ServerFactory::intance().createServer(FTP_SERVER); m_cliServer = gcom::ServerFactory::intance().createServer(CLI_SERVER); // start routine() thread this->startTask(); // set server state is work m_serverState = HOST_SERVER_WORK; G_LOG_OUT(); return G_YES; } GResult DfsServer::stop() { G_LOG_IN(); m_httpServer->stop(); m_ftpServer->stop(); m_cliServer->stop(); G_LOG_OUT(); return G_NO; } DfsServerState DfsServer::routine() { G_LOG_IN(); m_httpServer->start(); m_ftpServer->start(); m_cliServer->start(); for (;;) { // startup all server gcom::NetworkServerMonitor::keepServer(m_httpServer); gcom::NetworkServerMonitor::keepServer(m_ftpServer); gcom::NetworkServerMonitor::keepServer(m_cliServer); gsys::System::sleep(5); } G_LOG_OUT(); return G_YES; } } <commit_msg>Update g_dfs_server.cpp<commit_after>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_dfs_server.cpp * @version * @brief * @author duye * @date 2014-09-24 * @note * * 1. 2014-09-24 duye Created this file * */ #include <g_dfs_server.h> #include <g_logger.h> static const GInt8* LOG_PREFIX = "dfs.server.startup"; namespace gdfs { DfsServer::DfsServer() : gcom::HostServer() {} DfsServer::DfsServer(const std::string& dfs_cfg_file_path) : gcom::HostServer(), m_dfsCfgFilePath(dfs_cfg_file_path) {} DfsServer::~DfsServer() { G_LOG_IN(); gcom::ServerFactory::intance().destroyServer(m_httpServer); gcom::ServerFactory::intance().destroyServer(m_ftpServer); gcom::ServerFactory::intance().destroyServer(m_cliServer); G_LOG_OUT(); } GResult DfsServer::start() { G_LOG_IN(); if (getServerState() == HOST_SERVER_WORK) { return G_YES; } if (m_dfsCfgFilePath.empty()) { m_dfsCfgFilePath = DEF_DFS_CFG_FILE_PATH; } IS_NO_R(m_cfgMgr.load(m_dfsCfgFilePath)); // init all service m_httpServer = gcom::ServerFactory::intance().createServer(HTTP_SERVER); m_ftpServer = gcom::ServerFactory::intance().createServer(FTP_SERVER); m_cliServer = gcom::ServerFactory::intance().createServer(CLI_SERVER); // startup all service m_httpServer->start(); m_ftpServer->start(); m_cliServer->start(); // start routine() thread this->startTask(); // set server state is work m_serverState = HOST_SERVER_WORK; G_LOG_OUT(); return G_YES; } GResult DfsServer::stop() { G_LOG_IN(); m_httpServer->stop(); m_ftpServer->stop(); m_cliServer->stop(); G_LOG_OUT(); return G_NO; } DfsServerState DfsServer::routine() { G_LOG_IN(); for (;;) { // keep all service is running gcom::NetworkServerMonitor::keepServer(m_httpServer); gcom::NetworkServerMonitor::keepServer(m_ftpServer); gcom::NetworkServerMonitor::keepServer(m_cliServer); gsys::System::sleep(5); } G_LOG_OUT(); return G_YES; } } <|endoftext|>
<commit_before>/*! @file PDBReader.hpp @brief definition of a class that reads pdb atom. read pdb file and store the information as std::vector of shared_ptr of PDBAtom @author Toru Niina (niina.toru.68u@gmail.com) @date 2016-06-10 13:00 @copyright Toru Niina 2016 on MIT License */ #ifndef COFFEE_MILL_PDB_READER #define COFFEE_MILL_PDB_READER #include "PDBChain.hpp" #include <fstream> #include <sstream> namespace mill { //! PDBReader class /*! * read atoms in pdb file until "ENDMDL" or "END". * and then parse the PDBAtoms into vector of PDBChains. * for movie file, parse only one model at once. you can specify the model * by model index. */ template<typename vectorT> class PDBReader { public: using vector_type = vectorT; using atom_type = PDBAtom<vector_type>; using residue_type = PDBResidue<vector_type>; using chain_type = PDBChain<vector_type>; public: PDBReader() = default; ~PDBReader() = default; std::vector<chain_type> parse(const std::vector<atom_type>& atoms); std::vector<atom_type> read(const std::string& fname); std::vector<atom_type> read(const std::string& fname, const std::size_t model_idx); std::vector<atom_type> read(std::basic_istream<char>& fname); std::vector<atom_type> read(std::basic_istream<char>& fname, const std::size_t model_idx); }; template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(const std::string& fname) { std::ifstream ifs(fname); if(not ifs.good()) throw std::runtime_error("file open error: " + fname); const auto data = this->read(ifs); ifs.close(); return data; } template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(const std::string& fname, const std::size_t model_idx) { std::ifstream ifs(fname); if(not ifs.good()) throw std::runtime_error("file open error: " + fname); const auto data = this->read(ifs, model_idx); ifs.close(); return data; } template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(std::basic_istream<char>& ifs, const std::size_t model_idx) { while(not ifs.eof()) { std::string line; std::getline(ifs, line); if(line.empty()) continue; if(line.substr(0, 5) == "MODEL") { std::size_t index; std::istringstream iss(line); std::string model; iss >> model >> index; if(index == model_idx) break; } } if(ifs.eof()) throw std::invalid_argument("no model #" + std::to_string(model_idx)); return this->read(ifs); } template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(std::basic_istream<char>& ifs) { std::vector<atom_type> atoms; while(not ifs.eof()) { std::string line; std::getline(ifs, line); if(line.empty()) continue; if(line.substr(0, 3) == "END") break; // which is better ENDMDL or END? atom_type atom; if(line >> atom) atoms.emplace_back(std::move(atom)); } return atoms; } template<typename vectorT> std::vector<typename PDBReader<vectorT>::chain_type> PDBReader<vectorT>::parse(const std::vector<atom_type>& atoms) { std::vector<residue_type> residues; residue_type tmp_residue; int current_residue_id = std::numeric_limits<int>::min(); for(auto iter = atoms.cbegin(); iter != atoms.cend(); ++iter) { if(iter->residue_id != current_residue_id) { if(not tmp_residue.empty()) residues.push_back(tmp_residue); tmp_residue->clear(); current_residue_id = iter->residue_id; } tmp_residue.push_back(*iter); } if(not tmp_residue.empty()) residues.push_back(tmp_residue); std::vector<chain_type> chains; chain_type tmp_chain; std::string current_chain_id = ""; for(auto iter = residues.begin(); iter != residues.end(); ++iter) { if(iter->chain_id != current_chain_id) { if(not tmp_chain.empty()) chains.push_back(tmp_chain); tmp_chain.clear(); current_chain_id = iter->chain_id(); } tmp_chain.push_back(*iter); } if(not tmp_chain.empty()) chains.push_back(tmp_chain); return chains; } } // mill #endif//COFFEE_MILL_PURE_PDB_READER <commit_msg>add const to member function of PDBReader<commit_after>/*! @file PDBReader.hpp @brief pdb reader. read pdb atoms from input stream and parse atoms as chains. @author Toru Niina (niina.toru.68u@gmail.com) @date 2016-06-10 13:00 @copyright Toru Niina 2016 on MIT License */ #ifndef COFFEE_MILL_PDB_READER #define COFFEE_MILL_PDB_READER #include "PDBChain.hpp" #include <fstream> #include <sstream> namespace mill { //! PDBReader class /*! * read atoms in pdb file until "ENDMDL" or "END". * and then parse the PDBAtoms into vector of PDBChains. * for movie file, parse only one model at once. you can specify the model * by model index. */ template<typename vectorT> class PDBReader { public: using vector_type = vectorT; using atom_type = PDBAtom<vector_type>; using residue_type = PDBResidue<vector_type>; using chain_type = PDBChain<vector_type>; public: PDBReader() = default; ~PDBReader() = default; std::vector<chain_type> parse(const std::vector<atom_type>& atoms) const; std::vector<atom_type> read(const std::string& fname) const; std::vector<atom_type> read(const std::string& fname, const std::size_t model_idx) const; std::vector<atom_type> read(std::basic_istream<char>& fname) const; std::vector<atom_type> read(std::basic_istream<char>& fname, const std::size_t model_idx) const; }; template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(const std::string& fname) const { std::ifstream ifs(fname); if(not ifs.good()) throw std::runtime_error("file open error: " + fname); const auto data = this->read(ifs); ifs.close(); return data; } template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(const std::string& fname, const std::size_t model_idx) const { std::ifstream ifs(fname); if(not ifs.good()) throw std::runtime_error("file open error: " + fname); const auto data = this->read(ifs, model_idx); ifs.close(); return data; } template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(std::basic_istream<char>& ifs, const std::size_t model_idx) const { while(not ifs.eof()) { std::string line; std::getline(ifs, line); if(line.empty()) continue; if(line.substr(0, 5) == "MODEL") { std::size_t index; std::istringstream iss(line); std::string model; iss >> model >> index; if(index == model_idx) break; } } if(ifs.eof()) throw std::invalid_argument("no model #" + std::to_string(model_idx)); return this->read(ifs); } template<typename vectorT> std::vector<typename PDBReader<vectorT>::atom_type> PDBReader<vectorT>::read(std::basic_istream<char>& ifs) const { std::vector<atom_type> atoms; while(not ifs.eof()) { std::string line; std::getline(ifs, line); if(line.empty()) continue; if(line.substr(0, 3) == "END") break; // which is better ENDMDL or END? atom_type atom; if(line >> atom) atoms.emplace_back(std::move(atom)); } return atoms; } template<typename vectorT> std::vector<typename PDBReader<vectorT>::chain_type> PDBReader<vectorT>::parse(const std::vector<atom_type>& atoms) const { std::vector<residue_type> residues; residue_type tmp_residue; int current_residue_id = std::numeric_limits<int>::min(); for(auto iter = atoms.cbegin(); iter != atoms.cend(); ++iter) { if(iter->residue_id != current_residue_id) { if(not tmp_residue.empty()) residues.push_back(tmp_residue); tmp_residue->clear(); current_residue_id = iter->residue_id; } tmp_residue.push_back(*iter); } if(not tmp_residue.empty()) residues.push_back(tmp_residue); std::vector<chain_type> chains; chain_type tmp_chain; std::string current_chain_id = ""; for(auto iter = residues.begin(); iter != residues.end(); ++iter) { if(iter->chain_id != current_chain_id) { if(not tmp_chain.empty()) chains.push_back(tmp_chain); tmp_chain.clear(); current_chain_id = iter->chain_id(); } tmp_chain.push_back(*iter); } if(not tmp_chain.empty()) chains.push_back(tmp_chain); return chains; } } // mill #endif//COFFEE_MILL_PURE_PDB_READER <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * 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 Willow Garage 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. *********************************************************************/ /* \author Ioan Sucan */ #include "ompl/extension/samplingbased/kinematic/extension/ik/GAIK.h" #include <algorithm> bool ompl::GAIK::solve(double solveTime) { SpaceInformationKinematic_t si = dynamic_cast<SpaceInformationKinematic_t>(m_si); SpaceInformationKinematic::GoalRegionKinematic_t goal_r = dynamic_cast<SpaceInformationKinematic::GoalRegionKinematic_t>(si->getGoal()); unsigned int dim = si->getStateDimension(); if (!goal_r) { m_msg.error("GAIK: Unknown type of goal (or goal undefined)"); return false; } time_utils::Time endTime = time_utils::Time::now() + time_utils::Duration(solveTime); unsigned int maxPoolSize = m_poolSize + m_poolExpansion; std::vector<Individual> pool(maxPoolSize); IndividualSort gs; bool solved = false; int solution = -1; if (m_poolSize < 1) { m_msg.error("GAIK: Pool size too small"); return false; } for (unsigned int i = 0 ; i < maxPoolSize ; ++i) { pool[i].state = new SpaceInformationKinematic::StateKinematic(dim); si->sample(pool[i].state); if (goal_r->isSatisfied(pool[i].state, &(pool[i].distance))) { if (si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(pool[i].state))) { solved = true; solution = i; } } } unsigned int generations = 1; std::vector<double> range(dim); for (unsigned int i = 0 ; i < dim ; ++i) range[i] = m_rho * (si->getStateComponent(i).maxValue - si->getStateComponent(i).minValue); while (!solved && time_utils::Time::now() < endTime) { generations++; std::sort(pool.begin(), pool.end(), gs); for (unsigned int i = 0 ; i < 5 ; ++i) { if (si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(pool[i].state))) { if (tryToSolve(pool[i].state, &(pool[i].distance))) { solved = true; solution = i; break; } } } for (unsigned int i = m_poolSize ; i < maxPoolSize ; ++i) { si->sampleNear(pool[i].state, pool[i%m_poolSize].state, range); if (goal_r->isSatisfied(pool[i].state, &(pool[i].distance))) { if (si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(pool[i].state))) { solved = true; solution = i; break; } } } } m_msg.inform("GAIK: Ran for %u generations", generations); if (solved) { SpaceInformationKinematic::PathKinematic_t path = new SpaceInformationKinematic::PathKinematic(m_si); SpaceInformationKinematic::StateKinematic_t st = new SpaceInformationKinematic::StateKinematic(dim); si->copyState(st, pool[solution].state); path->states.push_back(st); goal_r->setDifference(pool[solution].distance); goal_r->setSolutionPath(path); } else { /* find an approximate solution */ std::sort(pool.begin(), pool.end(), gs); for (unsigned int i = 0 ; i < 5 ; ++i) { if (si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(pool[i].state))) { SpaceInformationKinematic::PathKinematic_t path = new SpaceInformationKinematic::PathKinematic(m_si); SpaceInformationKinematic::StateKinematic_t st = new SpaceInformationKinematic::StateKinematic(dim); si->copyState(st, pool[i].state); path->states.push_back(st); goal_r->setDifference(pool[i].distance); goal_r->setSolutionPath(path, true); break; } } } for (unsigned int i = 0 ; i < maxPoolSize ; ++i) delete pool[i].state; return goal_r->isAchieved(); } bool ompl::GAIK::tryToSolve(SpaceInformationKinematic::StateKinematic_t state, double *distance) { double dist = *distance; if (tryToSolveFact(1.01, state, distance)) return true; if (dist > *distance) { dist = *distance; if (tryToSolveFact(1.003, state, distance)) return true; } else return false; if (dist > *distance) { dist = *distance; if (tryToSolveFact(1.001, state, distance)) return true; } return false; } bool ompl::GAIK::tryToSolveFact(double factorP, SpaceInformationKinematic::StateKinematic_t state, double *distance) { SpaceInformationKinematic_t si = dynamic_cast<SpaceInformationKinematic_t>(m_si); SpaceInformationKinematic::GoalRegionKinematic_t goal_r = dynamic_cast<SpaceInformationKinematic::GoalRegionKinematic_t>(si->getGoal()); unsigned int dim = si->getStateDimension(); double factorM = 1.0/factorP; bool wasSatisfied = goal_r->isSatisfied(state, distance); double bestDist = *distance; bool change = true; while (change) { change = false; for (unsigned int i = 0 ; i < dim ; ++i) { bool better = true; while (better) { better = false; double backup = state->values[i]; state->values[i] *= factorP; bool isS = goal_r->isSatisfied(state, distance); if (wasSatisfied && !isS) state->values[i] = backup; else { wasSatisfied = isS; if (*distance < bestDist) { better = true; change = true; bestDist = *distance; } else state->values[i] = backup; } } better = true; while (better) { better = false; double backup = state->values[i]; state->values[i] *= factorM; bool isS = goal_r->isSatisfied(state, distance); if (wasSatisfied && !isS) state->values[i] = backup; else { wasSatisfied = isS; if (*distance < bestDist) { better = true; change = true; bestDist = *distance; } else state->values[i] = backup; } } } } *distance = bestDist; return wasSatisfied && si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(state)); } <commit_msg><commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * 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 Willow Garage 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. *********************************************************************/ /* \author Ioan Sucan */ #include "ompl/extension/samplingbased/kinematic/extension/ik/GAIK.h" #include <algorithm> bool ompl::GAIK::solve(double solveTime) { SpaceInformationKinematic_t si = dynamic_cast<SpaceInformationKinematic_t>(m_si); SpaceInformationKinematic::GoalRegionKinematic_t goal_r = dynamic_cast<SpaceInformationKinematic::GoalRegionKinematic_t>(si->getGoal()); unsigned int dim = si->getStateDimension(); if (!goal_r) { m_msg.error("GAIK: Unknown type of goal (or goal undefined)"); return false; } time_utils::Time endTime = time_utils::Time::now() + time_utils::Duration(solveTime); unsigned int maxPoolSize = m_poolSize + m_poolExpansion; std::vector<Individual> pool(maxPoolSize); IndividualSort gs; bool solved = false; int solution = -1; if (m_poolSize < 1) { m_msg.error("GAIK: Pool size too small"); return false; } for (unsigned int i = 0 ; i < maxPoolSize ; ++i) { pool[i].state = new SpaceInformationKinematic::StateKinematic(dim); si->sample(pool[i].state); if (goal_r->isSatisfied(pool[i].state, &(pool[i].distance))) { if (si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(pool[i].state))) { solved = true; solution = i; } } } unsigned int generations = 1; std::vector<double> range(dim); for (unsigned int i = 0 ; i < dim ; ++i) range[i] = m_rho * (si->getStateComponent(i).maxValue - si->getStateComponent(i).minValue); while (!solved && time_utils::Time::now() < endTime) { generations++; std::sort(pool.begin(), pool.end(), gs); for (unsigned int i = m_poolSize ; i < maxPoolSize ; ++i) { si->sampleNear(pool[i].state, pool[i%m_poolSize].state, range); if (goal_r->isSatisfied(pool[i].state, &(pool[i].distance))) { if (si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(pool[i].state))) { solved = true; solution = i; break; } } } } m_msg.inform("GAIK: Ran for %u generations", generations); if (solved) { SpaceInformationKinematic::PathKinematic_t path = new SpaceInformationKinematic::PathKinematic(m_si); SpaceInformationKinematic::StateKinematic_t st = new SpaceInformationKinematic::StateKinematic(dim); si->copyState(st, pool[solution].state); path->states.push_back(st); goal_r->setDifference(pool[solution].distance); goal_r->setSolutionPath(path); double dist = goal_r->getDifference(); tryToSolve(path->states[0], &dist); goal_r->setDifference(dist); } else { /* find an approximate solution */ std::sort(pool.begin(), pool.end(), gs); for (unsigned int i = 0 ; i < 5 ; ++i) { if (si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(pool[i].state))) { SpaceInformationKinematic::PathKinematic_t path = new SpaceInformationKinematic::PathKinematic(m_si); SpaceInformationKinematic::StateKinematic_t st = new SpaceInformationKinematic::StateKinematic(dim); si->copyState(st, pool[i].state); path->states.push_back(st); goal_r->setDifference(pool[i].distance); goal_r->setSolutionPath(path, true); double dist = goal_r->getDifference(); tryToSolve(path->states[0], &dist); goal_r->setDifference(dist); break; } } } for (unsigned int i = 0 ; i < maxPoolSize ; ++i) delete pool[i].state; return goal_r->isAchieved(); } bool ompl::GAIK::tryToSolve(SpaceInformationKinematic::StateKinematic_t state, double *distance) { tryToSolveFact(1.1, state, distance); tryToSolveFact(1.01, state, distance); tryToSolveFact(1.001, state, distance); tryToSolveFact(1.0001, state, distance); return true; } bool ompl::GAIK::tryToSolveFact(double factorP, SpaceInformationKinematic::StateKinematic_t state, double *distance) { SpaceInformationKinematic_t si = dynamic_cast<SpaceInformationKinematic_t>(m_si); SpaceInformationKinematic::GoalRegionKinematic_t goal_r = dynamic_cast<SpaceInformationKinematic::GoalRegionKinematic_t>(si->getGoal()); unsigned int dim = si->getStateDimension(); double factorM = 1.0/factorP; bool wasSatisfied = goal_r->isSatisfied(state, distance); double bestDist = *distance; bool change = true; while (change) { change = false; for (unsigned int i = 0 ; i < dim ; ++i) { bool better = true; while (better) { better = false; double backup = state->values[i]; state->values[i] *= factorP; bool isS = goal_r->isSatisfied(state, distance); if (wasSatisfied && !isS) state->values[i] = backup; else { wasSatisfied = isS; if (*distance < bestDist) { better = true; change = true; bestDist = *distance; } else state->values[i] = backup; } } better = true; while (better) { better = false; double backup = state->values[i]; state->values[i] *= factorM; bool isS = goal_r->isSatisfied(state, distance); if (wasSatisfied && !isS) state->values[i] = backup; else { wasSatisfied = isS; if (*distance < bestDist) { better = true; change = true; bestDist = *distance; } else state->values[i] = backup; } } } } *distance = bestDist; return wasSatisfied && si->isValid(static_cast<SpaceInformationKinematic::StateKinematic_t>(state)); } <|endoftext|>
<commit_before>#include "core/Loader.hpp" namespace Kvant { static std::vector<std::string> process_material_texture(aiMaterial *mat, aiTextureType type, std::string typeName) { std::vector<std::string> textures; for (unsigned int t = 0; t < mat->GetTextureCount(type); t++) { aiString str; mat->GetTexture(type, t, &str); textures.push_back(str.C_Str()); LOG_DEBUG << str.C_Str() << " " << type << ", " << aiTextureType_SPECULAR; } return textures; } static void process_mesh(RawModelData *model_data, const aiScene *scene, aiMesh *mesh) { auto mesh_cpy = std::make_unique<Mesh>(); std::unordered_map<Kvant::Vertex, int> vs; unsigned int vi = 0; // Store Vertex data for (unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vert; vert.position = {mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z}; vert.normal = {mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z}; if (mesh->mTextureCoords[0]) { vert.uvs = {mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y}; } else { vert.uvs = {0.0f, 0.0f}; } mesh_cpy->vertices.push_back(vert); } // Now wak through each of the mesh's faces (a face is a mesh its triangle) // and retrieve the corresponding vertex indices. for (unsigned int m = 0; m < mesh->mNumFaces; m++) { auto face = mesh->mFaces[m]; // Retrieve all indices of the face and store them in the indices vector for (unsigned int i = 0; i < face.mNumIndices; i++) { mesh_cpy->triangles.push_back(face.mIndices[i]); } } // push our mesh to the model model_data->model.meshes.push_back(std::move(mesh_cpy)); // Try read materials if (mesh->mMaterialIndex < 0) return; // No material exists auto *material = scene->mMaterials[mesh->mMaterialIndex]; // We assume a convention for sampler names in the shaders. Each diffuse // texture should be named as 'texture_diffuseN' where N is a sequential // number ranging from 1 to MAX_SAMPLER_NUMBER. Same applies to other texture // as the following list summarizes: Diffuse: texture_diffuseN Specular: // texture_specularN Normal: texture_normalN // diffuse model_data->diffuses = process_material_texture( material, aiTextureType_DIFFUSE, "texture_diffuse"); // normal model_data->normals = process_material_texture( material, aiTextureType_NORMALS, "texture_normal"); // specular model_data->speculars = process_material_texture( material, aiTextureType_SPECULAR, "texture_specular"); } static void process_node(RawModelData *model_data, const aiScene *scene, aiNode *node) { // Process each mesh located at the current node LOG_DEBUG << "Processing node " << node->mName.C_Str() << " with meshes = " << node->mNumMeshes << " children = " << node->mNumChildren; for (unsigned int i = 0; i < node->mNumMeshes; i++) { // The node object only contains indices to index the actual objects in the // scene. The scene contains all the data, node is just to keep stuff // organized (like relations between nodes). aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; process_mesh(model_data, scene, mesh); } // After we've processed all of the meshes (if any) we then recursively // process each of the children nodes for (unsigned int i = 0; i < node->mNumChildren; i++) { process_node(model_data, scene, node->mChildren[i]); } } RawModelData read_model(const char *filename) { RawModelData model_data; using namespace Assimp; Assimp::Importer importer; const aiScene *scene = importer.ReadFile(filename, aiProcess_Triangulate | aiProcess_FlipUVs); if (!scene) { throw std::runtime_error("Failed to load model " + std::string(filename)); } process_node(&model_data, scene, scene->mRootNode); model_data.model.generate_tangents(); return model_data; } bool load_png_for_texture(unsigned char **img, unsigned int *width, unsigned int *height, const char *filename) { bool success = false; unsigned error = lodepng_decode32_file(img, width, height, filename); if (error) { std::runtime_error("Error loading image"); } else { // Flip and invert the image unsigned char *imagePtr = *img; int halfTheHeightInPixels = *height / 2; int heightInPixels = *height; // Assume RGBA for 4 components per pixel int numColorComponents = 4; // Assuming each color component is an unsigned char int widthInChars = *width * numColorComponents; unsigned char *top = NULL; unsigned char *bottom = NULL; unsigned char temp = 0; for (int h = 0; h < halfTheHeightInPixels; ++h) { top = imagePtr + h * widthInChars; bottom = imagePtr + (heightInPixels - h - 1) * widthInChars; for (int w = 0; w < widthInChars; ++w) { // Swap the chars around. temp = *top; *top = *bottom; *bottom = temp; ++top; ++bottom; } } success = true; } return success; } } // namespace Kvant <commit_msg>Pass texture name by reference<commit_after>#include "core/Loader.hpp" namespace Kvant { static std::vector<std::string> process_material_texture(aiMaterial *mat, aiTextureType type, const std::string &typeName) { std::vector<std::string> textures; for (unsigned int t = 0; t < mat->GetTextureCount(type); t++) { aiString str; mat->GetTexture(type, t, &str); textures.push_back(str.C_Str()); LOG_DEBUG << str.C_Str() << " " << type << ", " << aiTextureType_SPECULAR; } return textures; } static void process_mesh(RawModelData *model_data, const aiScene *scene, aiMesh *mesh) { auto mesh_cpy = std::make_unique<Mesh>(); std::unordered_map<Kvant::Vertex, int> vs; unsigned int vi = 0; // Store Vertex data for (unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vert; vert.position = {mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z}; vert.normal = {mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z}; if (mesh->mTextureCoords[0]) { vert.uvs = {mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y}; } else { vert.uvs = {0.0f, 0.0f}; } mesh_cpy->vertices.push_back(vert); } // Now wak through each of the mesh's faces (a face is a mesh its triangle) // and retrieve the corresponding vertex indices. for (unsigned int m = 0; m < mesh->mNumFaces; m++) { auto face = mesh->mFaces[m]; // Retrieve all indices of the face and store them in the indices vector for (unsigned int i = 0; i < face.mNumIndices; i++) { mesh_cpy->triangles.push_back(face.mIndices[i]); } } // push our mesh to the model model_data->model.meshes.push_back(std::move(mesh_cpy)); // Try read materials if (mesh->mMaterialIndex < 0) return; // No material exists auto *material = scene->mMaterials[mesh->mMaterialIndex]; // We assume a convention for sampler names in the shaders. Each diffuse // texture should be named as 'texture_diffuseN' where N is a sequential // number ranging from 1 to MAX_SAMPLER_NUMBER. Same applies to other texture // as the following list summarizes: Diffuse: texture_diffuseN Specular: // texture_specularN Normal: texture_normalN // diffuse model_data->diffuses = process_material_texture( material, aiTextureType_DIFFUSE, "texture_diffuse"); // normal model_data->normals = process_material_texture( material, aiTextureType_NORMALS, "texture_normal"); // specular model_data->speculars = process_material_texture( material, aiTextureType_SPECULAR, "texture_specular"); } static void process_node(RawModelData *model_data, const aiScene *scene, aiNode *node) { // Process each mesh located at the current node LOG_DEBUG << "Processing node " << node->mName.C_Str() << " with meshes = " << node->mNumMeshes << " children = " << node->mNumChildren; for (unsigned int i = 0; i < node->mNumMeshes; i++) { // The node object only contains indices to index the actual objects in the // scene. The scene contains all the data, node is just to keep stuff // organized (like relations between nodes). aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; process_mesh(model_data, scene, mesh); } // After we've processed all of the meshes (if any) we then recursively // process each of the children nodes for (unsigned int i = 0; i < node->mNumChildren; i++) { process_node(model_data, scene, node->mChildren[i]); } } RawModelData read_model(const char *filename) { RawModelData model_data; using namespace Assimp; Assimp::Importer importer; const aiScene *scene = importer.ReadFile(filename, aiProcess_Triangulate | aiProcess_FlipUVs); if (!scene) { throw std::runtime_error("Failed to load model " + std::string(filename)); } process_node(&model_data, scene, scene->mRootNode); model_data.model.generate_tangents(); return model_data; } bool load_png_for_texture(unsigned char **img, unsigned int *width, unsigned int *height, const char *filename) { bool success = false; unsigned error = lodepng_decode32_file(img, width, height, filename); if (error) { std::runtime_error("Error loading image"); } else { // Flip and invert the image unsigned char *imagePtr = *img; int halfTheHeightInPixels = *height / 2; int heightInPixels = *height; // Assume RGBA for 4 components per pixel int numColorComponents = 4; // Assuming each color component is an unsigned char int widthInChars = *width * numColorComponents; unsigned char *top = NULL; unsigned char *bottom = NULL; unsigned char temp = 0; for (int h = 0; h < halfTheHeightInPixels; ++h) { top = imagePtr + h * widthInChars; bottom = imagePtr + (heightInPixels - h - 1) * widthInChars; for (int w = 0; w < widthInChars; ++w) { // Swap the chars around. temp = *top; *top = *bottom; *bottom = temp; ++top; ++bottom; } } success = true; } return success; } } // namespace Kvant <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "platform/scroll/ScrollbarTheme.h" #include "RuntimeEnabledFeatures.h" #include "platform/scroll/ScrollbarThemeClient.h" #include "platform/scroll/ScrollbarThemeMock.h" #include "platform/scroll/ScrollbarThemeOverlayMock.h" namespace WebCore { ScrollbarTheme* ScrollbarTheme::theme() { if (ScrollbarTheme::mockScrollbarsEnabled()) { if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) { DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, overlayMockTheme, ()); return &overlayMockTheme; } DEFINE_STATIC_LOCAL(ScrollbarThemeMock, mockTheme, ()); return &mockTheme; } return nativeTheme(); } bool ScrollbarTheme::gMockScrollbarsEnabled = false; void ScrollbarTheme::setMockScrollbarsEnabled(bool flag) { gMockScrollbarsEnabled = flag; } bool ScrollbarTheme::mockScrollbarsEnabled() { return gMockScrollbarsEnabled; } bool ScrollbarTheme::paint(ScrollbarThemeClient* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect) { // Create the ScrollbarControlPartMask based on the damageRect ScrollbarControlPartMask scrollMask = NoPart; IntRect backButtonStartPaintRect; IntRect backButtonEndPaintRect; IntRect forwardButtonStartPaintRect; IntRect forwardButtonEndPaintRect; if (hasButtons(scrollbar)) { backButtonStartPaintRect = backButtonRect(scrollbar, BackButtonStartPart, true); if (damageRect.intersects(backButtonStartPaintRect)) scrollMask |= BackButtonStartPart; backButtonEndPaintRect = backButtonRect(scrollbar, BackButtonEndPart, true); if (damageRect.intersects(backButtonEndPaintRect)) scrollMask |= BackButtonEndPart; forwardButtonStartPaintRect = forwardButtonRect(scrollbar, ForwardButtonStartPart, true); if (damageRect.intersects(forwardButtonStartPaintRect)) scrollMask |= ForwardButtonStartPart; forwardButtonEndPaintRect = forwardButtonRect(scrollbar, ForwardButtonEndPart, true); if (damageRect.intersects(forwardButtonEndPaintRect)) scrollMask |= ForwardButtonEndPart; } IntRect startTrackRect; IntRect thumbRect; IntRect endTrackRect; IntRect trackPaintRect = trackRect(scrollbar, true); if (damageRect.intersects(trackPaintRect)) scrollMask |= TrackBGPart; bool thumbPresent = hasThumb(scrollbar); if (thumbPresent) { IntRect track = trackRect(scrollbar); splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect); if (damageRect.intersects(thumbRect)) scrollMask |= ThumbPart; if (damageRect.intersects(startTrackRect)) scrollMask |= BackTrackPart; if (damageRect.intersects(endTrackRect)) scrollMask |= ForwardTrackPart; } // Paint the scrollbar background (only used by custom CSS scrollbars). paintScrollbarBackground(graphicsContext, scrollbar); // Paint the back and forward buttons. if (scrollMask & BackButtonStartPart) paintButton(graphicsContext, scrollbar, backButtonStartPaintRect, BackButtonStartPart); if (scrollMask & BackButtonEndPart) paintButton(graphicsContext, scrollbar, backButtonEndPaintRect, BackButtonEndPart); if (scrollMask & ForwardButtonStartPart) paintButton(graphicsContext, scrollbar, forwardButtonStartPaintRect, ForwardButtonStartPart); if (scrollMask & ForwardButtonEndPart) paintButton(graphicsContext, scrollbar, forwardButtonEndPaintRect, ForwardButtonEndPart); if (scrollMask & TrackBGPart) paintTrackBackground(graphicsContext, scrollbar, trackPaintRect); if ((scrollMask & ForwardTrackPart) || (scrollMask & BackTrackPart)) { // Paint the track pieces above and below the thumb. if (scrollMask & BackTrackPart) paintTrackPiece(graphicsContext, scrollbar, startTrackRect, BackTrackPart); if (scrollMask & ForwardTrackPart) paintTrackPiece(graphicsContext, scrollbar, endTrackRect, ForwardTrackPart); paintTickmarks(graphicsContext, scrollbar, trackPaintRect); } // Paint the thumb. if (scrollMask & ThumbPart) paintThumb(graphicsContext, scrollbar, thumbRect); return true; } ScrollbarPart ScrollbarTheme::hitTest(ScrollbarThemeClient* scrollbar, const IntPoint& position) { ScrollbarPart result = NoPart; if (!scrollbar->enabled()) return result; IntPoint testPosition = scrollbar->convertFromContainingWindow(position); testPosition.move(scrollbar->x(), scrollbar->y()); if (!scrollbar->frameRect().contains(testPosition)) return NoPart; result = ScrollbarBGPart; IntRect track = trackRect(scrollbar); if (track.contains(testPosition)) { IntRect beforeThumbRect; IntRect thumbRect; IntRect afterThumbRect; splitTrack(scrollbar, track, beforeThumbRect, thumbRect, afterThumbRect); if (thumbRect.contains(testPosition)) result = ThumbPart; else if (beforeThumbRect.contains(testPosition)) result = BackTrackPart; else if (afterThumbRect.contains(testPosition)) result = ForwardTrackPart; else result = TrackBGPart; } else if (backButtonRect(scrollbar, BackButtonStartPart).contains(testPosition)) { result = BackButtonStartPart; } else if (backButtonRect(scrollbar, BackButtonEndPart).contains(testPosition)) { result = BackButtonEndPart; } else if (forwardButtonRect(scrollbar, ForwardButtonStartPart).contains(testPosition)) { result = ForwardButtonStartPart; } else if (forwardButtonRect(scrollbar, ForwardButtonEndPart).contains(testPosition)) { result = ForwardButtonEndPart; } return result; } void ScrollbarTheme::invalidatePart(ScrollbarThemeClient* scrollbar, ScrollbarPart part) { if (part == NoPart) return; IntRect result; switch (part) { case BackButtonStartPart: result = backButtonRect(scrollbar, BackButtonStartPart, true); break; case BackButtonEndPart: result = backButtonRect(scrollbar, BackButtonEndPart, true); break; case ForwardButtonStartPart: result = forwardButtonRect(scrollbar, ForwardButtonStartPart, true); break; case ForwardButtonEndPart: result = forwardButtonRect(scrollbar, ForwardButtonEndPart, true); break; case TrackBGPart: result = trackRect(scrollbar, true); break; case ScrollbarBGPart: result = scrollbar->frameRect(); break; default: { IntRect beforeThumbRect, thumbRect, afterThumbRect; splitTrack(scrollbar, trackRect(scrollbar), beforeThumbRect, thumbRect, afterThumbRect); if (part == BackTrackPart) result = beforeThumbRect; else if (part == ForwardTrackPart) result = afterThumbRect; else result = thumbRect; } } result.moveBy(-scrollbar->location()); scrollbar->invalidateRect(result); } void ScrollbarTheme::splitTrack(ScrollbarThemeClient* scrollbar, const IntRect& unconstrainedTrackRect, IntRect& beforeThumbRect, IntRect& thumbRect, IntRect& afterThumbRect) { // This function won't even get called unless we're big enough to have some combination of these three rects where at least // one of them is non-empty. IntRect trackRect = constrainTrackRectToTrackPieces(scrollbar, unconstrainedTrackRect); int thumbPos = thumbPosition(scrollbar); if (scrollbar->orientation() == HorizontalScrollbar) { thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y(), thumbLength(scrollbar), scrollbar->height()); beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos + thumbRect.width() / 2, trackRect.height()); afterThumbRect = IntRect(trackRect.x() + beforeThumbRect.width(), trackRect.y(), trackRect.maxX() - beforeThumbRect.maxX(), trackRect.height()); } else { thumbRect = IntRect(trackRect.x(), trackRect.y() + thumbPos, scrollbar->width(), thumbLength(scrollbar)); beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos + thumbRect.height() / 2); afterThumbRect = IntRect(trackRect.x(), trackRect.y() + beforeThumbRect.height(), trackRect.width(), trackRect.maxY() - beforeThumbRect.maxY()); } } // Returns the size represented by track taking into account scrolling past // the end of the document. static float usedTotalSize(ScrollbarThemeClient* scrollbar) { float overhangAtStart = -scrollbar->currentPos(); float overhangAtEnd = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize(); float overhang = std::max(0.0f, std::max(overhangAtStart, overhangAtEnd)); return scrollbar->totalSize() + overhang; } int ScrollbarTheme::thumbPosition(ScrollbarThemeClient* scrollbar) { if (scrollbar->enabled()) { float size = usedTotalSize(scrollbar) - scrollbar->visibleSize(); // Avoid doing a floating point divide by zero and return 1 when usedTotalSize == visibleSize. if (!size) return 1; float pos = std::max(0.0f, scrollbar->currentPos()) * (trackLength(scrollbar) - thumbLength(scrollbar)) / size; return (pos < 1 && pos > 0) ? 1 : pos; } return 0; } int ScrollbarTheme::thumbLength(ScrollbarThemeClient* scrollbar) { if (!scrollbar->enabled()) return 0; float overhang = 0; if (scrollbar->currentPos() < 0) overhang = -scrollbar->currentPos(); else if (scrollbar->visibleSize() + scrollbar->currentPos() > scrollbar->totalSize()) overhang = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize(); float proportion = (scrollbar->visibleSize() - overhang) / usedTotalSize(scrollbar); int trackLen = trackLength(scrollbar); int length = round(proportion * trackLen); length = std::max(length, minimumThumbLength(scrollbar)); if (length > trackLen) length = 0; // Once the thumb is below the track length, it just goes away (to make more room for the track). return length; } int ScrollbarTheme::minimumThumbLength(ScrollbarThemeClient* scrollbar) { return scrollbarThickness(scrollbar->controlSize()); } int ScrollbarTheme::trackPosition(ScrollbarThemeClient* scrollbar) { IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar)); return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.x() - scrollbar->x() : constrainedTrackRect.y() - scrollbar->y(); } int ScrollbarTheme::trackLength(ScrollbarThemeClient* scrollbar) { IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar)); return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.width() : constrainedTrackRect.height(); } void ScrollbarTheme::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect) { context->fillRect(cornerRect, Color::white); } IntRect ScrollbarTheme::thumbRect(ScrollbarThemeClient* scrollbar) { if (!hasThumb(scrollbar)) return IntRect(); IntRect track = trackRect(scrollbar); IntRect startTrackRect; IntRect thumbRect; IntRect endTrackRect; splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect); return thumbRect; } int ScrollbarTheme::thumbThickness(ScrollbarThemeClient* scrollbar) { IntRect track = trackRect(scrollbar); return scrollbar->orientation() == HorizontalScrollbar ? track.height() : track.width(); } void ScrollbarTheme::paintOverhangBackground(GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect) { context->setFillColor(Color::white); if (!horizontalOverhangRect.isEmpty()) context->fillRect(intersection(horizontalOverhangRect, dirtyRect)); if (!verticalOverhangRect.isEmpty()) context->fillRect(intersection(verticalOverhangRect, dirtyRect)); } } <commit_msg>Makes ScrollbarTheme call through to theme engine for corner (2)<commit_after>/* * Copyright (C) 2011 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "platform/scroll/ScrollbarTheme.h" #include "RuntimeEnabledFeatures.h" #include "platform/scroll/ScrollbarThemeClient.h" #include "platform/scroll/ScrollbarThemeMock.h" #include "platform/scroll/ScrollbarThemeOverlayMock.h" #if !OS(MACOSX) #include "public/platform/Platform.h" #include "public/platform/WebRect.h" #include "public/platform/default/WebThemeEngine.h" #endif namespace WebCore { ScrollbarTheme* ScrollbarTheme::theme() { if (ScrollbarTheme::mockScrollbarsEnabled()) { if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) { DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, overlayMockTheme, ()); return &overlayMockTheme; } DEFINE_STATIC_LOCAL(ScrollbarThemeMock, mockTheme, ()); return &mockTheme; } return nativeTheme(); } bool ScrollbarTheme::gMockScrollbarsEnabled = false; void ScrollbarTheme::setMockScrollbarsEnabled(bool flag) { gMockScrollbarsEnabled = flag; } bool ScrollbarTheme::mockScrollbarsEnabled() { return gMockScrollbarsEnabled; } bool ScrollbarTheme::paint(ScrollbarThemeClient* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect) { // Create the ScrollbarControlPartMask based on the damageRect ScrollbarControlPartMask scrollMask = NoPart; IntRect backButtonStartPaintRect; IntRect backButtonEndPaintRect; IntRect forwardButtonStartPaintRect; IntRect forwardButtonEndPaintRect; if (hasButtons(scrollbar)) { backButtonStartPaintRect = backButtonRect(scrollbar, BackButtonStartPart, true); if (damageRect.intersects(backButtonStartPaintRect)) scrollMask |= BackButtonStartPart; backButtonEndPaintRect = backButtonRect(scrollbar, BackButtonEndPart, true); if (damageRect.intersects(backButtonEndPaintRect)) scrollMask |= BackButtonEndPart; forwardButtonStartPaintRect = forwardButtonRect(scrollbar, ForwardButtonStartPart, true); if (damageRect.intersects(forwardButtonStartPaintRect)) scrollMask |= ForwardButtonStartPart; forwardButtonEndPaintRect = forwardButtonRect(scrollbar, ForwardButtonEndPart, true); if (damageRect.intersects(forwardButtonEndPaintRect)) scrollMask |= ForwardButtonEndPart; } IntRect startTrackRect; IntRect thumbRect; IntRect endTrackRect; IntRect trackPaintRect = trackRect(scrollbar, true); if (damageRect.intersects(trackPaintRect)) scrollMask |= TrackBGPart; bool thumbPresent = hasThumb(scrollbar); if (thumbPresent) { IntRect track = trackRect(scrollbar); splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect); if (damageRect.intersects(thumbRect)) scrollMask |= ThumbPart; if (damageRect.intersects(startTrackRect)) scrollMask |= BackTrackPart; if (damageRect.intersects(endTrackRect)) scrollMask |= ForwardTrackPart; } // Paint the scrollbar background (only used by custom CSS scrollbars). paintScrollbarBackground(graphicsContext, scrollbar); // Paint the back and forward buttons. if (scrollMask & BackButtonStartPart) paintButton(graphicsContext, scrollbar, backButtonStartPaintRect, BackButtonStartPart); if (scrollMask & BackButtonEndPart) paintButton(graphicsContext, scrollbar, backButtonEndPaintRect, BackButtonEndPart); if (scrollMask & ForwardButtonStartPart) paintButton(graphicsContext, scrollbar, forwardButtonStartPaintRect, ForwardButtonStartPart); if (scrollMask & ForwardButtonEndPart) paintButton(graphicsContext, scrollbar, forwardButtonEndPaintRect, ForwardButtonEndPart); if (scrollMask & TrackBGPart) paintTrackBackground(graphicsContext, scrollbar, trackPaintRect); if ((scrollMask & ForwardTrackPart) || (scrollMask & BackTrackPart)) { // Paint the track pieces above and below the thumb. if (scrollMask & BackTrackPart) paintTrackPiece(graphicsContext, scrollbar, startTrackRect, BackTrackPart); if (scrollMask & ForwardTrackPart) paintTrackPiece(graphicsContext, scrollbar, endTrackRect, ForwardTrackPart); paintTickmarks(graphicsContext, scrollbar, trackPaintRect); } // Paint the thumb. if (scrollMask & ThumbPart) paintThumb(graphicsContext, scrollbar, thumbRect); return true; } ScrollbarPart ScrollbarTheme::hitTest(ScrollbarThemeClient* scrollbar, const IntPoint& position) { ScrollbarPart result = NoPart; if (!scrollbar->enabled()) return result; IntPoint testPosition = scrollbar->convertFromContainingWindow(position); testPosition.move(scrollbar->x(), scrollbar->y()); if (!scrollbar->frameRect().contains(testPosition)) return NoPart; result = ScrollbarBGPart; IntRect track = trackRect(scrollbar); if (track.contains(testPosition)) { IntRect beforeThumbRect; IntRect thumbRect; IntRect afterThumbRect; splitTrack(scrollbar, track, beforeThumbRect, thumbRect, afterThumbRect); if (thumbRect.contains(testPosition)) result = ThumbPart; else if (beforeThumbRect.contains(testPosition)) result = BackTrackPart; else if (afterThumbRect.contains(testPosition)) result = ForwardTrackPart; else result = TrackBGPart; } else if (backButtonRect(scrollbar, BackButtonStartPart).contains(testPosition)) { result = BackButtonStartPart; } else if (backButtonRect(scrollbar, BackButtonEndPart).contains(testPosition)) { result = BackButtonEndPart; } else if (forwardButtonRect(scrollbar, ForwardButtonStartPart).contains(testPosition)) { result = ForwardButtonStartPart; } else if (forwardButtonRect(scrollbar, ForwardButtonEndPart).contains(testPosition)) { result = ForwardButtonEndPart; } return result; } void ScrollbarTheme::invalidatePart(ScrollbarThemeClient* scrollbar, ScrollbarPart part) { if (part == NoPart) return; IntRect result; switch (part) { case BackButtonStartPart: result = backButtonRect(scrollbar, BackButtonStartPart, true); break; case BackButtonEndPart: result = backButtonRect(scrollbar, BackButtonEndPart, true); break; case ForwardButtonStartPart: result = forwardButtonRect(scrollbar, ForwardButtonStartPart, true); break; case ForwardButtonEndPart: result = forwardButtonRect(scrollbar, ForwardButtonEndPart, true); break; case TrackBGPart: result = trackRect(scrollbar, true); break; case ScrollbarBGPart: result = scrollbar->frameRect(); break; default: { IntRect beforeThumbRect, thumbRect, afterThumbRect; splitTrack(scrollbar, trackRect(scrollbar), beforeThumbRect, thumbRect, afterThumbRect); if (part == BackTrackPart) result = beforeThumbRect; else if (part == ForwardTrackPart) result = afterThumbRect; else result = thumbRect; } } result.moveBy(-scrollbar->location()); scrollbar->invalidateRect(result); } void ScrollbarTheme::splitTrack(ScrollbarThemeClient* scrollbar, const IntRect& unconstrainedTrackRect, IntRect& beforeThumbRect, IntRect& thumbRect, IntRect& afterThumbRect) { // This function won't even get called unless we're big enough to have some combination of these three rects where at least // one of them is non-empty. IntRect trackRect = constrainTrackRectToTrackPieces(scrollbar, unconstrainedTrackRect); int thumbPos = thumbPosition(scrollbar); if (scrollbar->orientation() == HorizontalScrollbar) { thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y(), thumbLength(scrollbar), scrollbar->height()); beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos + thumbRect.width() / 2, trackRect.height()); afterThumbRect = IntRect(trackRect.x() + beforeThumbRect.width(), trackRect.y(), trackRect.maxX() - beforeThumbRect.maxX(), trackRect.height()); } else { thumbRect = IntRect(trackRect.x(), trackRect.y() + thumbPos, scrollbar->width(), thumbLength(scrollbar)); beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos + thumbRect.height() / 2); afterThumbRect = IntRect(trackRect.x(), trackRect.y() + beforeThumbRect.height(), trackRect.width(), trackRect.maxY() - beforeThumbRect.maxY()); } } // Returns the size represented by track taking into account scrolling past // the end of the document. static float usedTotalSize(ScrollbarThemeClient* scrollbar) { float overhangAtStart = -scrollbar->currentPos(); float overhangAtEnd = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize(); float overhang = std::max(0.0f, std::max(overhangAtStart, overhangAtEnd)); return scrollbar->totalSize() + overhang; } int ScrollbarTheme::thumbPosition(ScrollbarThemeClient* scrollbar) { if (scrollbar->enabled()) { float size = usedTotalSize(scrollbar) - scrollbar->visibleSize(); // Avoid doing a floating point divide by zero and return 1 when usedTotalSize == visibleSize. if (!size) return 1; float pos = std::max(0.0f, scrollbar->currentPos()) * (trackLength(scrollbar) - thumbLength(scrollbar)) / size; return (pos < 1 && pos > 0) ? 1 : pos; } return 0; } int ScrollbarTheme::thumbLength(ScrollbarThemeClient* scrollbar) { if (!scrollbar->enabled()) return 0; float overhang = 0; if (scrollbar->currentPos() < 0) overhang = -scrollbar->currentPos(); else if (scrollbar->visibleSize() + scrollbar->currentPos() > scrollbar->totalSize()) overhang = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize(); float proportion = (scrollbar->visibleSize() - overhang) / usedTotalSize(scrollbar); int trackLen = trackLength(scrollbar); int length = round(proportion * trackLen); length = std::max(length, minimumThumbLength(scrollbar)); if (length > trackLen) length = 0; // Once the thumb is below the track length, it just goes away (to make more room for the track). return length; } int ScrollbarTheme::minimumThumbLength(ScrollbarThemeClient* scrollbar) { return scrollbarThickness(scrollbar->controlSize()); } int ScrollbarTheme::trackPosition(ScrollbarThemeClient* scrollbar) { IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar)); return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.x() - scrollbar->x() : constrainedTrackRect.y() - scrollbar->y(); } int ScrollbarTheme::trackLength(ScrollbarThemeClient* scrollbar) { IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar)); return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.width() : constrainedTrackRect.height(); } void ScrollbarTheme::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect) { if (cornerRect.isEmpty()) return; #if OS(MACOSX) context->fillRect(cornerRect, Color::white); #else blink::Platform::current()->themeEngine()->paint(context->canvas(), blink::WebThemeEngine::PartScrollbarCorner, blink::WebThemeEngine::StateNormal, blink::WebRect(cornerRect), 0); #endif } IntRect ScrollbarTheme::thumbRect(ScrollbarThemeClient* scrollbar) { if (!hasThumb(scrollbar)) return IntRect(); IntRect track = trackRect(scrollbar); IntRect startTrackRect; IntRect thumbRect; IntRect endTrackRect; splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect); return thumbRect; } int ScrollbarTheme::thumbThickness(ScrollbarThemeClient* scrollbar) { IntRect track = trackRect(scrollbar); return scrollbar->orientation() == HorizontalScrollbar ? track.height() : track.width(); } void ScrollbarTheme::paintOverhangBackground(GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect) { context->setFillColor(Color::white); if (!horizontalOverhangRect.isEmpty()) context->fillRect(intersection(horizontalOverhangRect, dirtyRect)); if (!verticalOverhangRect.isEmpty()) context->fillRect(intersection(verticalOverhangRect, dirtyRect)); } } <|endoftext|>
<commit_before><commit_msg>IWorkController interface<commit_after><|endoftext|>
<commit_before><commit_msg>Improved zlib error message<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #include "Report.h" #include "Util.h" #include "core.h" #include "StringX.h" #include "os/dir.h" #include "os/debug.h" #include "os/file.h" #include "os/utf8conv.h" #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <errno.h> #include <sstream> #include <fstream> const TCHAR *CRLF = _T("\r\n"); /* It writes a header record and a "Start Report" record. */ void CReport::StartReport(LPCTSTR tcAction, const stringT &csDataBase) { m_osxs.str(_T("")); m_tcAction = tcAction; m_csDataBase = csDataBase; stringT cs_title, sTimeStamp; PWSUtil::GetTimeStamp(sTimeStamp); Format(cs_title, IDSC_REPORT_TITLE1, tcAction, sTimeStamp.c_str()); WriteLine(); WriteLine(cs_title); Format(cs_title, IDSC_REPORT_TITLE2, csDataBase.c_str()); WriteLine(cs_title); WriteLine(); LoadAString(cs_title, IDSC_START_REPORT); WriteLine(cs_title); WriteLine(); } static bool isFileUnicode(const stringT &fname) { struct _stat statbuf; int status = _tstat(fname.c_str(), &statbuf); // Need file to exist and length at least 2 for BOM if (status != 0 || statbuf.st_size < 2) return false; const unsigned char BOM[] = {0xff, 0xfe}; unsigned char buffer[] = {0x00, 0x00}; // Check if the first 2 characters are the BOM // Need to use FOpen as cannot pass wchar_t filename to a std::istream // and cannot convert a wchar_t filename/path to char if non-Latin characters // present FILE *fn = pws_os::FOpen(fname.c_str(), _T("rb")); fread(buffer, 1, 2, fn); fclose(fn); return (buffer[0] == BOM[0] && buffer[1] == BOM[1]); } /* SaveToDisk creates a new file of name "<tcAction>_Report.txt" e.g. "Merge_Report.txt" in the same directory as the current database or appends to this file if it already exists. */ bool CReport::SaveToDisk() { FILE *fd; stringT path(m_csDataBase); stringT drive, dir, file, ext; if (!pws_os::splitpath(path, drive, dir, file, ext)) { pws_os::IssueError(_T("StartReport: Finding path to database")); return false; } Format(m_cs_filename, IDSC_REPORTFILENAME, drive.c_str(), dir.c_str(), m_tcAction.c_str()); if ((fd = pws_os::FOpen(m_cs_filename, _T("a+b"))) == NULL) { pws_os::IssueError(_T("StartReport: Opening log file")); return false; } // **** MOST LIKELY ACTION **** // If file is new/emtpy AND we are UNICODE, write BOM, as some text editors insist! // **** LEAST LIKELY ACTIONS as it requires the user to use both U & NU versions **** // Text editors really don't like files with both UNICODE and ASCII characters, so - // If we are UNICODE and file is not, convert file to UNICODE before appending // If we are not UNICODE but file is, convert file to ASCII before appending bool bFileIsUnicode = isFileUnicode(m_cs_filename); #ifdef UNICODE const unsigned int iBOM = 0xFEFF; if (pws_os::fileLength(fd) == 0) { // File is empty - write BOM putwc(iBOM, fd); } else if (!bFileIsUnicode) { // Convert ASCII contents to UNICODE // Close original first fclose(fd); // Open again to read FILE *f_in = pws_os::FOpen(m_cs_filename, _S("rb")); // Open new file stringT cs_out = m_cs_filename + _S(".tmp"); FILE *f_out = pws_os::FOpen(cs_out, _S("wb")); // Write BOM putwc(iBOM, f_out); size_t nBytesRead; unsigned char inbuffer[4096]; wchar_t outwbuffer[4096]; // Now copy do { nBytesRead = fread(inbuffer, sizeof(inbuffer), 1, f_in); if (nBytesRead > 0) { size_t len = pws_os::mbstowcs(outwbuffer, 4096, reinterpret_cast<const char *>(inbuffer), nBytesRead); if (len != 0) fwrite(outwbuffer, sizeof(outwbuffer[0])*len, 1, f_out); } else break; } while(nBytesRead > 0); // Close files fclose(f_in); fclose(f_out); // Swap them pws_os::RenameFile(cs_out, m_cs_filename); // Re-open file if ((fd = pws_os::FOpen(m_cs_filename, _S("ab"))) == NULL) { pws_os::IssueError(_T("StartReport: Opening log file")); return false; } } #else if (bFileIsUnicode) { // Convert UNICODE contents to ASCII // Close original first fclose(fd); // Open again to read FILE *f_in = pws_os::FOpen(m_cs_filename, "rb"); // Open new file stringT cs_out = m_cs_filename + _T(".tmp"); FILE *f_out = pws_os::FOpen(cs_out, "wb"); UINT nBytesRead; WCHAR inwbuffer[4096]; unsigned char outbuffer[4096]; // Skip over BOM fseek(f_in, 2, SEEK_SET); // Now copy do { nBytesRead = fread(inwbuffer, sizeof(inwbuffer[0])*sizeof(inwbuffer), 1, f_in); if (nBytesRead > 0) { size_t len = pws_os::wcstombs((char *)outbuffer, 4096, inwbuffer, nBytesRead); if (len != 0) fwrite(outbuffer, len, 1, f_out); } else break; } while(nBytesRead > 0); // Close files fclose(f_in); fclose(f_out); // Swap them pws_os::RenameFile(cs_out, m_cs_filename); // Re-open file if ((fd = pws_os::FOpen(m_cs_filename, _S("ab"))) == NULL) { pws_os::IssueError(_T("StartReport: Opening log file")); return false; } } #endif StringX sx = m_osxs.rdbuf()->str(); fwrite(reinterpret_cast<const void *>(sx.c_str()), sizeof(BYTE), sx.length() * sizeof(TCHAR), fd); fclose(fd); return true; } // Write a record with(default) or without a CRLF void CReport::WriteLine(const stringT &cs_line, bool bCRLF) { m_osxs << cs_line.c_str(); if (bCRLF) { m_osxs << CRLF; } } // Write a record with (default) or without a CRLF void CReport::WriteLine(const LPTSTR &tc_line, bool bCRLF) { m_osxs << tc_line; if (bCRLF) { m_osxs << CRLF; } } // Write a new line void CReport::WriteLine() { m_osxs << CRLF; } // EndReport writes a "End Report" record and closes the report file. void CReport::EndReport() { WriteLine(); stringT cs_title; LoadAString(cs_title, IDSC_END_REPORT1); WriteLine(cs_title); LoadAString(cs_title, IDSC_END_REPORT2); WriteLine(cs_title); m_osxs.flush(); } <commit_msg>Portability: rev 4211 should compile under Linux too.<commit_after>/* * Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ #include "Report.h" #include "Util.h" #include "core.h" #include "StringX.h" #include "os/dir.h" #include "os/debug.h" #include "os/file.h" #include "os/utf8conv.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sstream> #include <fstream> const TCHAR *CRLF = _T("\r\n"); /* It writes a header record and a "Start Report" record. */ void CReport::StartReport(LPCTSTR tcAction, const stringT &csDataBase) { m_osxs.str(_T("")); m_tcAction = tcAction; m_csDataBase = csDataBase; stringT cs_title, sTimeStamp; PWSUtil::GetTimeStamp(sTimeStamp); Format(cs_title, IDSC_REPORT_TITLE1, tcAction, sTimeStamp.c_str()); WriteLine(); WriteLine(cs_title); Format(cs_title, IDSC_REPORT_TITLE2, csDataBase.c_str()); WriteLine(cs_title); WriteLine(); LoadAString(cs_title, IDSC_START_REPORT); WriteLine(cs_title); WriteLine(); } static bool isFileUnicode(const stringT &fname) { // Check if the first 2 characters are the BOM // (Need file to exist and length at least 2 for BOM) // Need to use FOpen as cannot pass wchar_t filename to a std::istream // and cannot convert a wchar_t filename/path to char if non-Latin characters // present const unsigned char BOM[] = {0xff, 0xfe}; unsigned char buffer[] = {0x00, 0x00}; bool retval = false; FILE *fn = pws_os::FOpen(fname, _T("rb")); if (fn == NULL) return false; if (pws_os::fileLength(fn) < 2) retval = false; else { fread(buffer, 1, 2, fn); retval = (buffer[0] == BOM[0] && buffer[1] == BOM[1]); } fclose(fn); return retval; } /* SaveToDisk creates a new file of name "<tcAction>_Report.txt" e.g. "Merge_Report.txt" in the same directory as the current database or appends to this file if it already exists. */ bool CReport::SaveToDisk() { FILE *fd; stringT path(m_csDataBase); stringT drive, dir, file, ext; if (!pws_os::splitpath(path, drive, dir, file, ext)) { pws_os::IssueError(_T("StartReport: Finding path to database")); return false; } Format(m_cs_filename, IDSC_REPORTFILENAME, drive.c_str(), dir.c_str(), m_tcAction.c_str()); if ((fd = pws_os::FOpen(m_cs_filename, _T("a+b"))) == NULL) { pws_os::IssueError(_T("StartReport: Opening log file")); return false; } // **** MOST LIKELY ACTION **** // If file is new/emtpy AND we are UNICODE, write BOM, as some text editors insist! // **** LEAST LIKELY ACTIONS as it requires the user to use both U & NU versions **** // Text editors really don't like files with both UNICODE and ASCII characters, so - // If we are UNICODE and file is not, convert file to UNICODE before appending // If we are not UNICODE but file is, convert file to ASCII before appending bool bFileIsUnicode = isFileUnicode(m_cs_filename); #ifdef UNICODE const unsigned int iBOM = 0xFEFF; if (pws_os::fileLength(fd) == 0) { // File is empty - write BOM putwc(iBOM, fd); } else if (!bFileIsUnicode) { // Convert ASCII contents to UNICODE // Close original first fclose(fd); // Open again to read FILE *f_in = pws_os::FOpen(m_cs_filename, _S("rb")); // Open new file stringT cs_out = m_cs_filename + _S(".tmp"); FILE *f_out = pws_os::FOpen(cs_out, _S("wb")); // Write BOM putwc(iBOM, f_out); size_t nBytesRead; unsigned char inbuffer[4096]; wchar_t outwbuffer[4096]; // Now copy do { nBytesRead = fread(inbuffer, sizeof(inbuffer), 1, f_in); if (nBytesRead > 0) { size_t len = pws_os::mbstowcs(outwbuffer, 4096, reinterpret_cast<const char *>(inbuffer), nBytesRead); if (len != 0) fwrite(outwbuffer, sizeof(outwbuffer[0])*len, 1, f_out); } else break; } while(nBytesRead > 0); // Close files fclose(f_in); fclose(f_out); // Swap them pws_os::RenameFile(cs_out, m_cs_filename); // Re-open file if ((fd = pws_os::FOpen(m_cs_filename, _S("ab"))) == NULL) { pws_os::IssueError(_T("StartReport: Opening log file")); return false; } } #else if (bFileIsUnicode) { // Convert UNICODE contents to ASCII // Close original first fclose(fd); // Open again to read FILE *f_in = pws_os::FOpen(m_cs_filename, "rb"); // Open new file stringT cs_out = m_cs_filename + _T(".tmp"); FILE *f_out = pws_os::FOpen(cs_out, "wb"); UINT nBytesRead; WCHAR inwbuffer[4096]; unsigned char outbuffer[4096]; // Skip over BOM fseek(f_in, 2, SEEK_SET); // Now copy do { nBytesRead = fread(inwbuffer, sizeof(inwbuffer[0])*sizeof(inwbuffer), 1, f_in); if (nBytesRead > 0) { size_t len = pws_os::wcstombs((char *)outbuffer, 4096, inwbuffer, nBytesRead); if (len != 0) fwrite(outbuffer, len, 1, f_out); } else break; } while(nBytesRead > 0); // Close files fclose(f_in); fclose(f_out); // Swap them pws_os::RenameFile(cs_out, m_cs_filename); // Re-open file if ((fd = pws_os::FOpen(m_cs_filename, _S("ab"))) == NULL) { pws_os::IssueError(_T("StartReport: Opening log file")); return false; } } #endif StringX sx = m_osxs.rdbuf()->str(); fwrite(reinterpret_cast<const void *>(sx.c_str()), sizeof(BYTE), sx.length() * sizeof(TCHAR), fd); fclose(fd); return true; } // Write a record with(default) or without a CRLF void CReport::WriteLine(const stringT &cs_line, bool bCRLF) { m_osxs << cs_line.c_str(); if (bCRLF) { m_osxs << CRLF; } } // Write a record with (default) or without a CRLF void CReport::WriteLine(const LPTSTR &tc_line, bool bCRLF) { m_osxs << tc_line; if (bCRLF) { m_osxs << CRLF; } } // Write a new line void CReport::WriteLine() { m_osxs << CRLF; } // EndReport writes a "End Report" record and closes the report file. void CReport::EndReport() { WriteLine(); stringT cs_title; LoadAString(cs_title, IDSC_END_REPORT1); WriteLine(cs_title); LoadAString(cs_title, IDSC_END_REPORT2); WriteLine(cs_title); m_osxs.flush(); } <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Antonio Recuero, Milad Rakhsha // ============================================================================= // // Unit test for EAS Brick Element // // This unit test checks the dynamics of a beam made up of 10 brick elemnts. // It serves to validate the elastic, isotropic, large deformation internal forces, // the element inertia, and this element'sgravity forces. // // This element is a regular 8-noded trilinear brick element with enhanced assumed // strain that alleviates locking. More information on the validation of this element // may be found in Chrono's documentation. This simulation excites the beam by applying // the sudden action of a gravity field. // ============================================================================= #include "chrono/core/ChFileutils.h" #include "chrono/physics/ChSystem.h" #include "chrono/lcp/ChLcpIterativeMINRES.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_fea/ChElementSpring.h" #include "chrono_fea/ChElementBrick.h" #include "chrono_fea/ChElementBar.h" #include "chrono_fea/ChLinkPointFrame.h" #include "chrono_fea/ChLinkDirFrame.h" #include "chrono_fea/ChVisualizationFEAmesh.h" using namespace chrono; using namespace fea; const double step_size = 1e-3; // Step size double sim_time = 2; // Simulation time for generation of reference file double precision = 1e-6; // Precision value used to assess results double sim_time_UT = 0.1; // Simulation time for unit test 0.05 int main(int argc, char* argv[]) { bool output = 0; // Determines whether it tests (0) or generates golden file (1) ChMatrixDynamic<> FileInputMat(2000, 2); if (output) { GetLog() << "Output file: ../TEST_Brick/UT_EASBrickIso_Grav.txt\n"; } else { // Utils to open/read files: Load reference solution ("golden") file std::string EASBrick_val_file = GetChronoDataPath() + "testing/" + "UT_EASBrickIso_Grav.txt"; std::ifstream fileMid(EASBrick_val_file); if (!fileMid.is_open()) { fileMid.open(EASBrick_val_file); } if (!fileMid) { std::cout << "Cannot open validation file.\n"; exit(1); } for (int x = 0; x < 2000; x++) { fileMid >> FileInputMat[x][0] >> FileInputMat[x][1]; } fileMid.close(); GetLog() << "Running in unit test mode.\n"; } // Create the physical system ChSystem my_system; ChSharedPtr<ChMesh> my_mesh(new ChMesh); // Dimensions of the plate double plate_lenght_x = 1; double plate_lenght_y = 0.1; double plate_lenght_z = 0.01; // small thickness // Specification of the mesh int numDiv_x = 10; // 10 elements along the length of the beam int numDiv_y = 1; int numDiv_z = 1; int N_x = numDiv_x + 1; int N_y = numDiv_y + 1; int N_z = numDiv_z + 1; // Number of elements in the z direction is considered as 1 int TotalNumElements = numDiv_x; int TotalNumNodes = (numDiv_x + 1) * 4; // 4 nodes per brick face // For uniform mesh double dx = plate_lenght_x / numDiv_x; double dy = plate_lenght_y / numDiv_y; double dz = plate_lenght_z / numDiv_z; int MaxMNUM = 1; int MTYPE = 1; int MaxLayNum = 1; ChMatrixDynamic<double> COORDFlex(TotalNumNodes, 3); ChMatrixDynamic<double> VELCYFlex(TotalNumNodes, 3); ChMatrixDynamic<int> NumNodes(TotalNumElements, 8); ChMatrixDynamic<int> LayNum(TotalNumElements, 1); ChMatrixDynamic<int> NDR(TotalNumNodes, 3); ChMatrixDynamic<double> ElemLengthXY(TotalNumElements, 3); ChMatrixNM<double, 10, 12> MPROP; //!------------ Material Data----------------- for (int i = 0; i < MaxMNUM; i++) { MPROP(i, 0) = 500; // Density [kg/m3] MPROP(i, 1) = 2.1E+07; // E (Pa) MPROP(i, 2) = 0.3; // nu } ChSharedPtr<ChContinuumElastic> mmaterial(new ChContinuumElastic); mmaterial->Set_RayleighDampingK(0.0); mmaterial->Set_RayleighDampingM(0.0); mmaterial->Set_density(MPROP(0, 0)); mmaterial->Set_E(MPROP(0, 1)); mmaterial->Set_G(MPROP(0, 1) / (2 + 2 * MPROP(0, 2))); mmaterial->Set_v(MPROP(0, 2)); //!--------------- Element data-------------------- for (int i = 0; i < TotalNumElements; i++) { // All the elements belong to the same layer, e.g layer number 1. LayNum(i, 0) = 1; NumNodes(i, 0) = i; NumNodes(i, 1) = i + 1; NumNodes(i, 2) = i + 1 + N_x; NumNodes(i, 3) = i + N_x; NumNodes(i, 4) = i + 2 * N_x; NumNodes(i, 5) = i + 2 * N_x + 1; NumNodes(i, 6) = i + 3 * N_x + 1; NumNodes(i, 7) = i + 3 * N_x; // Numbering of nodes ElemLengthXY(i, 0) = dx; ElemLengthXY(i, 1) = dy; ElemLengthXY(i, 2) = dz; if (MaxLayNum < LayNum(i, 0)) { MaxLayNum = LayNum(i, 0); } } //!--------- Constraints and initial coordinates/velocities for (int i = 0; i < TotalNumNodes; i++) { // Constrain clamped nodes. Assigns (1) if constrained, (0) otherwise NDR(i, 0) = (i % N_x == 0) ? 1 : 0; NDR(i, 1) = (i % N_x == 0) ? 1 : 0; NDR(i, 2) = (i % N_x == 0) ? 1 : 0; // Coordinates COORDFlex(i, 0) = (i % (N_x)) * dx; if ((i / N_x + 1) % 2 == 0) { COORDFlex(i, 1) = dy; } else { COORDFlex(i, 1) = 0.0; }; COORDFlex(i, 2) = (i) / ((N_x)*2) * dz; // Velocities VELCYFlex(i, 0) = 0; VELCYFlex(i, 1) = 0; VELCYFlex(i, 2) = 0; } // Adding the nodes to the mesh int i = 0; while (i < TotalNumNodes) { ChSharedPtr<ChNodeFEAxyz> node(new ChNodeFEAxyz(ChVector<>(COORDFlex(i, 0), COORDFlex(i, 1), COORDFlex(i, 2)))); node->SetMass(0.0); my_mesh->AddNode(node); if (NDR(i, 0) == 1 && NDR(i, 1) == 1 && NDR(i, 2) == 1) { node->SetFixed(true); } i++; } // Create a node at the tip by dynamic casting ChSharedPtr<ChNodeFEAxyz> nodetip(my_mesh->GetNode(TotalNumNodes - 1).DynamicCastTo<ChNodeFEAxyz>()); int elemcount = 0; while (elemcount < TotalNumElements) { ChSharedPtr<ChElementBrick> element(new ChElementBrick); ChMatrixNM<double, 3, 1> InertFlexVec; // Read element length, used in ChElementBrick InertFlexVec.Reset(); InertFlexVec(0, 0) = ElemLengthXY(elemcount, 0); InertFlexVec(1, 0) = ElemLengthXY(elemcount, 1); InertFlexVec(2, 0) = ElemLengthXY(elemcount, 2); element->SetInertFlexVec(InertFlexVec); // Note we change the order of the nodes to comply with the arrangement of shape functions element->SetNodes(my_mesh->GetNode(NumNodes(elemcount, 0)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 1)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 3)).DynamicCastTo<ChNodeFEAxyz>(), // my_mesh->GetNode(NumNodes(elemcount, 2)).DynamicCastTo<ChNodeFEAxyz>(), // my_mesh->GetNode(NumNodes(elemcount, 4)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 5)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 7)).DynamicCastTo<ChNodeFEAxyz>(), // my_mesh->GetNode(NumNodes(elemcount, 6)).DynamicCastTo<ChNodeFEAxyz>()); // element->SetMaterial(mmaterial); element->SetElemNum(elemcount); element->SetGravityOn(true); // Turn gravity on/off from within the element element->SetMooneyRivlin(false); // Turn on/off Mooney Rivlin (Linear Isotropic by default) // element->SetMRCoefficients(551584.0, 137896.0); // Set two coefficients for Mooney-Rivlin ChMatrixNM<double, 9, 1> stock_alpha_EAS; stock_alpha_EAS.Reset(); element->SetStockAlpha(stock_alpha_EAS(0, 0), stock_alpha_EAS(1, 0), stock_alpha_EAS(2, 0), stock_alpha_EAS(3, 0), stock_alpha_EAS(4, 0), stock_alpha_EAS(5, 0), stock_alpha_EAS(6, 0), stock_alpha_EAS(7, 0), stock_alpha_EAS(8, 0)); my_mesh->AddElement(element); elemcount++; } // This is mandatory my_mesh->SetupInitial(); // Deactivate automatic gravity in mesh my_mesh->SetAutomaticGravity(false); // Remember to add the mesh to the system! my_system.Add(my_mesh); // Perform a dynamic time integration: my_system.SetLcpSolverType( ChSystem::LCP_ITERATIVE_MINRES); // <- NEEDED because other solvers can't handle stiffness matrices chrono::ChLcpIterativeMINRES* msolver = (chrono::ChLcpIterativeMINRES*)my_system.GetLcpSolverSpeed(); msolver->SetDiagonalPreconditioning(true); my_system.SetIterLCPmaxItersSpeed(10000); my_system.SetTolForce(1e-09); my_system.SetIntegrationType(ChSystem::INT_HHT); ChSharedPtr<ChTimestepperHHT> mystepper = my_system.GetTimestepper().DynamicCastTo<ChTimestepperHHT>(); mystepper->SetAlpha(-0.01); mystepper->SetMaxiters(10000); mystepper->SetTolerance(1e-09); mystepper->SetMode(ChTimestepperHHT::POSITION); mystepper->SetScaling(true); // Simulation loop if (output) { // Create output directory (if it does not already exist). if (ChFileutils::MakeDirectory("../TEST_Brick") < 0) { GetLog() << "Error creating directory ../TEST_Brick\n"; return 1; } // Initialize the output stream and set precision. utils::CSV_writer out("\t"); out.stream().setf(std::ios::scientific | std::ios::showpos); out.stream().precision(7); int Iterations = 0; // Simulate to final time, while saving position of tip node. while (my_system.GetChTime() < sim_time) { my_system.DoStepDynamics(step_size); Iterations += mystepper->GetNumIterations(); out << my_system.GetChTime() << nodetip->GetPos().z << std::endl; GetLog() << "time = " << my_system.GetChTime() << "\t" << nodetip->GetPos().z << "\t" << nodetip->GetForce().z << "\t" << Iterations << "\n"; } // Write results to output file. out.write_to_file("../TEST_Brick/UT_EASBrickIso_Grav.txt.txt"); } else { // Initialize total number of iterations and timer. int Iterations = 0; double start = std::clock(); int stepNo = 0; double AbsVal = 0.0; // Simulate to final time, while accumulating number of iterations. while (my_system.GetChTime() < sim_time_UT) { my_system.DoStepDynamics(step_size); AbsVal = abs(nodetip->GetPos().z - FileInputMat[stepNo][1]); GetLog() << "time = " << my_system.GetChTime() << "\t" << nodetip->GetPos().z << "\n"; if (AbsVal > precision) { std::cout << "Unit test check failed \n"; return 1; } stepNo++; Iterations += mystepper->GetNumIterations(); } // Report run time and total number of iterations. double duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; GetLog() << "Computation Time: " << duration << " Number of iterations: " << Iterations << "\n"; std::cout << "Unit test check succeeded \n"; } return 0; } <commit_msg>Reduce simulation time tested in test_EASBrickIso_Grav.cpp<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Antonio Recuero, Milad Rakhsha // ============================================================================= // // Unit test for EAS Brick Element // // This unit test checks the dynamics of a beam made up of 10 brick elemnts. // It serves to validate the elastic, isotropic, large deformation internal forces, // the element inertia, and this element'sgravity forces. // // This element is a regular 8-noded trilinear brick element with enhanced assumed // strain that alleviates locking. More information on the validation of this element // may be found in Chrono's documentation. This simulation excites the beam by applying // the sudden action of a gravity field. // ============================================================================= #include "chrono/core/ChFileutils.h" #include "chrono/physics/ChSystem.h" #include "chrono/lcp/ChLcpIterativeMINRES.h" #include "chrono/utils/ChUtilsInputOutput.h" #include "chrono_fea/ChElementSpring.h" #include "chrono_fea/ChElementBrick.h" #include "chrono_fea/ChElementBar.h" #include "chrono_fea/ChLinkPointFrame.h" #include "chrono_fea/ChLinkDirFrame.h" #include "chrono_fea/ChVisualizationFEAmesh.h" using namespace chrono; using namespace fea; const double step_size = 1e-3; // Step size double sim_time = 2; // Simulation time for generation of reference file double precision = 1e-6; // Precision value used to assess results double sim_time_UT = 0.05; // Simulation time for unit test 0.05 int main(int argc, char* argv[]) { bool output = 0; // Determines whether it tests (0) or generates golden file (1) ChMatrixDynamic<> FileInputMat(2000, 2); if (output) { GetLog() << "Output file: ../TEST_Brick/UT_EASBrickIso_Grav.txt\n"; } else { // Utils to open/read files: Load reference solution ("golden") file std::string EASBrick_val_file = GetChronoDataPath() + "testing/" + "UT_EASBrickIso_Grav.txt"; std::ifstream fileMid(EASBrick_val_file); if (!fileMid.is_open()) { fileMid.open(EASBrick_val_file); } if (!fileMid) { std::cout << "Cannot open validation file.\n"; exit(1); } for (int x = 0; x < 2000; x++) { fileMid >> FileInputMat[x][0] >> FileInputMat[x][1]; } fileMid.close(); GetLog() << "Running in unit test mode.\n"; } // Create the physical system ChSystem my_system; ChSharedPtr<ChMesh> my_mesh(new ChMesh); // Dimensions of the plate double plate_lenght_x = 1; double plate_lenght_y = 0.1; double plate_lenght_z = 0.01; // small thickness // Specification of the mesh int numDiv_x = 10; // 10 elements along the length of the beam int numDiv_y = 1; int numDiv_z = 1; int N_x = numDiv_x + 1; int N_y = numDiv_y + 1; int N_z = numDiv_z + 1; // Number of elements in the z direction is considered as 1 int TotalNumElements = numDiv_x; int TotalNumNodes = (numDiv_x + 1) * 4; // 4 nodes per brick face // For uniform mesh double dx = plate_lenght_x / numDiv_x; double dy = plate_lenght_y / numDiv_y; double dz = plate_lenght_z / numDiv_z; int MaxMNUM = 1; int MTYPE = 1; int MaxLayNum = 1; ChMatrixDynamic<double> COORDFlex(TotalNumNodes, 3); ChMatrixDynamic<double> VELCYFlex(TotalNumNodes, 3); ChMatrixDynamic<int> NumNodes(TotalNumElements, 8); ChMatrixDynamic<int> LayNum(TotalNumElements, 1); ChMatrixDynamic<int> NDR(TotalNumNodes, 3); ChMatrixDynamic<double> ElemLengthXY(TotalNumElements, 3); ChMatrixNM<double, 10, 12> MPROP; //!------------ Material Data----------------- for (int i = 0; i < MaxMNUM; i++) { MPROP(i, 0) = 500; // Density [kg/m3] MPROP(i, 1) = 2.1E+07; // E (Pa) MPROP(i, 2) = 0.3; // nu } ChSharedPtr<ChContinuumElastic> mmaterial(new ChContinuumElastic); mmaterial->Set_RayleighDampingK(0.0); mmaterial->Set_RayleighDampingM(0.0); mmaterial->Set_density(MPROP(0, 0)); mmaterial->Set_E(MPROP(0, 1)); mmaterial->Set_G(MPROP(0, 1) / (2 + 2 * MPROP(0, 2))); mmaterial->Set_v(MPROP(0, 2)); //!--------------- Element data-------------------- for (int i = 0; i < TotalNumElements; i++) { // All the elements belong to the same layer, e.g layer number 1. LayNum(i, 0) = 1; NumNodes(i, 0) = i; NumNodes(i, 1) = i + 1; NumNodes(i, 2) = i + 1 + N_x; NumNodes(i, 3) = i + N_x; NumNodes(i, 4) = i + 2 * N_x; NumNodes(i, 5) = i + 2 * N_x + 1; NumNodes(i, 6) = i + 3 * N_x + 1; NumNodes(i, 7) = i + 3 * N_x; // Numbering of nodes ElemLengthXY(i, 0) = dx; ElemLengthXY(i, 1) = dy; ElemLengthXY(i, 2) = dz; if (MaxLayNum < LayNum(i, 0)) { MaxLayNum = LayNum(i, 0); } } //!--------- Constraints and initial coordinates/velocities for (int i = 0; i < TotalNumNodes; i++) { // Constrain clamped nodes. Assigns (1) if constrained, (0) otherwise NDR(i, 0) = (i % N_x == 0) ? 1 : 0; NDR(i, 1) = (i % N_x == 0) ? 1 : 0; NDR(i, 2) = (i % N_x == 0) ? 1 : 0; // Coordinates COORDFlex(i, 0) = (i % (N_x)) * dx; if ((i / N_x + 1) % 2 == 0) { COORDFlex(i, 1) = dy; } else { COORDFlex(i, 1) = 0.0; }; COORDFlex(i, 2) = (i) / ((N_x)*2) * dz; // Velocities VELCYFlex(i, 0) = 0; VELCYFlex(i, 1) = 0; VELCYFlex(i, 2) = 0; } // Adding the nodes to the mesh int i = 0; while (i < TotalNumNodes) { ChSharedPtr<ChNodeFEAxyz> node(new ChNodeFEAxyz(ChVector<>(COORDFlex(i, 0), COORDFlex(i, 1), COORDFlex(i, 2)))); node->SetMass(0.0); my_mesh->AddNode(node); if (NDR(i, 0) == 1 && NDR(i, 1) == 1 && NDR(i, 2) == 1) { node->SetFixed(true); } i++; } // Create a node at the tip by dynamic casting ChSharedPtr<ChNodeFEAxyz> nodetip(my_mesh->GetNode(TotalNumNodes - 1).DynamicCastTo<ChNodeFEAxyz>()); int elemcount = 0; while (elemcount < TotalNumElements) { ChSharedPtr<ChElementBrick> element(new ChElementBrick); ChMatrixNM<double, 3, 1> InertFlexVec; // Read element length, used in ChElementBrick InertFlexVec.Reset(); InertFlexVec(0, 0) = ElemLengthXY(elemcount, 0); InertFlexVec(1, 0) = ElemLengthXY(elemcount, 1); InertFlexVec(2, 0) = ElemLengthXY(elemcount, 2); element->SetInertFlexVec(InertFlexVec); // Note we change the order of the nodes to comply with the arrangement of shape functions element->SetNodes(my_mesh->GetNode(NumNodes(elemcount, 0)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 1)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 3)).DynamicCastTo<ChNodeFEAxyz>(), // my_mesh->GetNode(NumNodes(elemcount, 2)).DynamicCastTo<ChNodeFEAxyz>(), // my_mesh->GetNode(NumNodes(elemcount, 4)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 5)).DynamicCastTo<ChNodeFEAxyz>(), my_mesh->GetNode(NumNodes(elemcount, 7)).DynamicCastTo<ChNodeFEAxyz>(), // my_mesh->GetNode(NumNodes(elemcount, 6)).DynamicCastTo<ChNodeFEAxyz>()); // element->SetMaterial(mmaterial); element->SetElemNum(elemcount); element->SetGravityOn(true); // Turn gravity on/off from within the element element->SetMooneyRivlin(false); // Turn on/off Mooney Rivlin (Linear Isotropic by default) // element->SetMRCoefficients(551584.0, 137896.0); // Set two coefficients for Mooney-Rivlin ChMatrixNM<double, 9, 1> stock_alpha_EAS; stock_alpha_EAS.Reset(); element->SetStockAlpha(stock_alpha_EAS(0, 0), stock_alpha_EAS(1, 0), stock_alpha_EAS(2, 0), stock_alpha_EAS(3, 0), stock_alpha_EAS(4, 0), stock_alpha_EAS(5, 0), stock_alpha_EAS(6, 0), stock_alpha_EAS(7, 0), stock_alpha_EAS(8, 0)); my_mesh->AddElement(element); elemcount++; } // This is mandatory my_mesh->SetupInitial(); // Deactivate automatic gravity in mesh my_mesh->SetAutomaticGravity(false); // Remember to add the mesh to the system! my_system.Add(my_mesh); // Perform a dynamic time integration: my_system.SetLcpSolverType( ChSystem::LCP_ITERATIVE_MINRES); // <- NEEDED because other solvers can't handle stiffness matrices chrono::ChLcpIterativeMINRES* msolver = (chrono::ChLcpIterativeMINRES*)my_system.GetLcpSolverSpeed(); msolver->SetDiagonalPreconditioning(true); my_system.SetIterLCPmaxItersSpeed(10000); my_system.SetTolForce(1e-09); my_system.SetIntegrationType(ChSystem::INT_HHT); ChSharedPtr<ChTimestepperHHT> mystepper = my_system.GetTimestepper().DynamicCastTo<ChTimestepperHHT>(); mystepper->SetAlpha(-0.01); mystepper->SetMaxiters(10000); mystepper->SetTolerance(1e-09); mystepper->SetMode(ChTimestepperHHT::POSITION); mystepper->SetScaling(true); // Simulation loop if (output) { // Create output directory (if it does not already exist). if (ChFileutils::MakeDirectory("../TEST_Brick") < 0) { GetLog() << "Error creating directory ../TEST_Brick\n"; return 1; } // Initialize the output stream and set precision. utils::CSV_writer out("\t"); out.stream().setf(std::ios::scientific | std::ios::showpos); out.stream().precision(7); int Iterations = 0; // Simulate to final time, while saving position of tip node. while (my_system.GetChTime() < sim_time) { my_system.DoStepDynamics(step_size); Iterations += mystepper->GetNumIterations(); out << my_system.GetChTime() << nodetip->GetPos().z << std::endl; GetLog() << "time = " << my_system.GetChTime() << "\t" << nodetip->GetPos().z << "\t" << nodetip->GetForce().z << "\t" << Iterations << "\n"; } // Write results to output file. out.write_to_file("../TEST_Brick/UT_EASBrickIso_Grav.txt.txt"); } else { // Initialize total number of iterations and timer. int Iterations = 0; double start = std::clock(); int stepNo = 0; double AbsVal = 0.0; // Simulate to final time, while accumulating number of iterations. while (my_system.GetChTime() < sim_time_UT) { my_system.DoStepDynamics(step_size); AbsVal = abs(nodetip->GetPos().z - FileInputMat[stepNo][1]); GetLog() << "time = " << my_system.GetChTime() << "\t" << nodetip->GetPos().z << "\n"; if (AbsVal > precision) { std::cout << "Unit test check failed \n"; return 1; } stepNo++; Iterations += mystepper->GetNumIterations(); } // Report run time and total number of iterations. double duration = (std::clock() - start) / (double)CLOCKS_PER_SEC; GetLog() << "Computation Time: " << duration << " Number of iterations: " << Iterations << "\n"; std::cout << "Unit test check succeeded \n"; } return 0; } <|endoftext|>
<commit_before>// -*-Mode: C++;-*- // $Id$ // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002-2007, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * // ---------------------------------------------------------------------- // // the implementation of evaluation tree nodes // // ---------------------------------------------------------------------- //************************ System Include Files ****************************** #include <iostream> using std::endl; #include <sstream> #include <string> #include <algorithm> #include <cmath> //************************* User Include Files ******************************* #include <include/general.h> #include "Metric-AExpr.hpp" #include <lib/support/NaN.h> #include <lib/support/Trace.hpp> //************************ Forward Declarations ****************************** #define AEXPR_DO_CHECK 0 #if (AEXPR_DO_CHECK) # define AEXPR_CHECK(x) if (!isok(x)) { return c_FP_NAN_d; } #else # define AEXPR_CHECK(x) #endif //**************************************************************************** namespace Prof { namespace Metric { // ---------------------------------------------------------------------- // class AExpr // ---------------------------------------------------------------------- std::string AExpr::toString() const { std::ostringstream os; dump(os); return os.str(); } void AExpr::dump_opands(std::ostream& os, AExpr** opands, int sz, const char* sep) { for (int i = 0; i < sz; ++i) { opands[i]->dump(os); if (i < (sz - 1)) { os << sep; } } } // ---------------------------------------------------------------------- // class Const // ---------------------------------------------------------------------- std::ostream& Const::dump(std::ostream& os) const { os << "(" << m_c << ")"; return os; } // ---------------------------------------------------------------------- // class Neg // ---------------------------------------------------------------------- double Neg::eval(const ScopeInfo* si) const { double result = m_expr->eval(si); //IFTRACE << "neg=" << -result << endl; AEXPR_CHECK(result); return -result; } std::ostream& Neg::dump(std::ostream& os) const { os << "(-"; m_expr->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Var // ---------------------------------------------------------------------- std::ostream& Var::dump(std::ostream& os) const { os << name; return os; } // ---------------------------------------------------------------------- // class Power // ---------------------------------------------------------------------- Power::Power(AExpr* b, AExpr* e) : base(b), exponent(e) { } Power::~Power() { delete base; delete exponent; } double Power::eval(const ScopeInfo* si) const { double b = base->eval(si); double e = exponent->eval(si); double result = pow(b, e); //IFTRACE << "pow=" << pow(b, e) << endl; AEXPR_CHECK(result); return result; } std::ostream& Power::dump(std::ostream& os) const { os << "("; base->dump(os); os << "**"; exponent->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Divide // ---------------------------------------------------------------------- Divide::Divide(AExpr* num, AExpr* denom) : numerator(num), denominator(denom) { } Divide::~Divide() { delete numerator; delete denominator; } double Divide::eval(const ScopeInfo* si) const { double n = numerator->eval(si); double d = denominator->eval(si); double result = n / d; //IFTRACE << "divident=" << n/d << endl; AEXPR_CHECK(result); return result; } std::ostream& Divide::dump(std::ostream& os) const { os << "("; numerator->dump(os); os << " / "; denominator->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Minus // ---------------------------------------------------------------------- Minus::Minus(AExpr* m, AExpr* s) : minuend(m), subtrahend(s) { // if (minuend == NULL || subtrahend == NULL) { ... } } Minus::~Minus() { delete minuend; delete subtrahend; } double Minus::eval(const ScopeInfo* si) const { double m = minuend->eval(si); double s = subtrahend->eval(si); double result = (m - s); //IFTRACE << "diff=" << m-s << endl; AEXPR_CHECK(result); return result; } std::ostream& Minus::dump(std::ostream& os) const { os << "("; minuend->dump(os); os << " - "; subtrahend->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Plus // ---------------------------------------------------------------------- Plus::Plus(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Plus::~Plus() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Plus::eval(const ScopeInfo* si) const { double result = eval_sum(si, m_opands, m_sz); //IFTRACE << "sum=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Plus::dump(std::ostream& os) const { os << "("; dump_opands(os, m_opands, m_sz, " + "); os << ")"; return os; } // ---------------------------------------------------------------------- // class Times // ---------------------------------------------------------------------- Times::Times(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Times::~Times() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Times::eval(const ScopeInfo* si) const { double result = 1.0; for (int i = 0; i < m_sz; ++i) { double x = m_opands[i]->eval(si); result *= x; } //IFTRACE << "result=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Times::dump(std::ostream& os) const { os << "("; dump_opands(os, m_opands, m_sz, " * "); os << ")"; return os; } // ---------------------------------------------------------------------- // class Max // ---------------------------------------------------------------------- Max::Max(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Max::~Max() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Max::eval(const ScopeInfo* si) const { double result = m_opands[0]->eval(si); for (int i = 1; i < m_sz; ++i) { double x = m_opands[i]->eval(si); result = std::max(result, x); } //IFTRACE << "max=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Max::dump(std::ostream& os) const { os << "max("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class Min // ---------------------------------------------------------------------- Min::Min(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Min::~Min() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Min::eval(const ScopeInfo* si) const { double result = m_opands[0]->eval(si); for (int i = 1; i < m_sz; ++i) { double x = m_opands[i]->eval(si); result = std::min(result, x); } //IFTRACE << "min=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Min::dump(std::ostream& os) const { os << "min("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class Mean // ---------------------------------------------------------------------- Mean::Mean(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Mean::~Mean() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Mean::eval(const ScopeInfo* si) const { double result = eval_mean(si, m_opands, m_sz); //IFTRACE << "mean=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Mean::dump(std::ostream& os) const { os << "mean("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class StdDev // ---------------------------------------------------------------------- StdDev::StdDev(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } StdDev::~StdDev() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double StdDev::eval(const ScopeInfo* si) const { std::pair<double, double> v_m = eval_variance(si, m_opands, m_sz); double result = sqrt(v_m.first); //IFTRACE << "stddev=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& StdDev::dump(std::ostream& os) const { os << "stddev("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class RStdDev // ---------------------------------------------------------------------- RStdDev::RStdDev(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } RStdDev::~RStdDev() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double RStdDev::eval(const ScopeInfo* si) const{ std::pair<double, double> v_m = eval_variance(si, m_opands, m_sz); double sdev = sqrt(v_m.first); double result = (sdev / v_m.second) * 100; //IFTRACE << "r-stddev=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& RStdDev::dump(std::ostream& os) const { os << "r-stddev("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } //**************************************************************************** } // namespace Metric } // namespace Prof <commit_msg>Prof::Metric::RStdDev::eval: handle divide by 0<commit_after>// -*-Mode: C++;-*- // $Id$ // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002-2007, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * // ---------------------------------------------------------------------- // // the implementation of evaluation tree nodes // // ---------------------------------------------------------------------- //************************ System Include Files ****************************** #include <iostream> using std::endl; #include <sstream> #include <string> #include <algorithm> #include <cmath> //************************* User Include Files ******************************* #include <include/general.h> #include "Metric-AExpr.hpp" #include <lib/support/NaN.h> #include <lib/support/Trace.hpp> //************************ Forward Declarations ****************************** #define AEXPR_DO_CHECK 0 #if (AEXPR_DO_CHECK) # define AEXPR_CHECK(x) if (!isok(x)) { return c_FP_NAN_d; } #else # define AEXPR_CHECK(x) #endif static double epsilon = 0.000001; //**************************************************************************** namespace Prof { namespace Metric { // ---------------------------------------------------------------------- // class AExpr // ---------------------------------------------------------------------- std::string AExpr::toString() const { std::ostringstream os; dump(os); return os.str(); } void AExpr::dump_opands(std::ostream& os, AExpr** opands, int sz, const char* sep) { for (int i = 0; i < sz; ++i) { opands[i]->dump(os); if (i < (sz - 1)) { os << sep; } } } // ---------------------------------------------------------------------- // class Const // ---------------------------------------------------------------------- std::ostream& Const::dump(std::ostream& os) const { os << "(" << m_c << ")"; return os; } // ---------------------------------------------------------------------- // class Neg // ---------------------------------------------------------------------- double Neg::eval(const ScopeInfo* si) const { double result = m_expr->eval(si); //IFTRACE << "neg=" << -result << endl; AEXPR_CHECK(result); return -result; } std::ostream& Neg::dump(std::ostream& os) const { os << "(-"; m_expr->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Var // ---------------------------------------------------------------------- std::ostream& Var::dump(std::ostream& os) const { os << name; return os; } // ---------------------------------------------------------------------- // class Power // ---------------------------------------------------------------------- Power::Power(AExpr* b, AExpr* e) : base(b), exponent(e) { } Power::~Power() { delete base; delete exponent; } double Power::eval(const ScopeInfo* si) const { double b = base->eval(si); double e = exponent->eval(si); double result = pow(b, e); //IFTRACE << "pow=" << pow(b, e) << endl; AEXPR_CHECK(result); return result; } std::ostream& Power::dump(std::ostream& os) const { os << "("; base->dump(os); os << "**"; exponent->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Divide // ---------------------------------------------------------------------- Divide::Divide(AExpr* num, AExpr* denom) : numerator(num), denominator(denom) { } Divide::~Divide() { delete numerator; delete denominator; } double Divide::eval(const ScopeInfo* si) const { double n = numerator->eval(si); double d = denominator->eval(si); double result = n / d; //IFTRACE << "divident=" << n/d << endl; AEXPR_CHECK(result); return result; } std::ostream& Divide::dump(std::ostream& os) const { os << "("; numerator->dump(os); os << " / "; denominator->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Minus // ---------------------------------------------------------------------- Minus::Minus(AExpr* m, AExpr* s) : minuend(m), subtrahend(s) { // if (minuend == NULL || subtrahend == NULL) { ... } } Minus::~Minus() { delete minuend; delete subtrahend; } double Minus::eval(const ScopeInfo* si) const { double m = minuend->eval(si); double s = subtrahend->eval(si); double result = (m - s); //IFTRACE << "diff=" << m-s << endl; AEXPR_CHECK(result); return result; } std::ostream& Minus::dump(std::ostream& os) const { os << "("; minuend->dump(os); os << " - "; subtrahend->dump(os); os << ")"; return os; } // ---------------------------------------------------------------------- // class Plus // ---------------------------------------------------------------------- Plus::Plus(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Plus::~Plus() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Plus::eval(const ScopeInfo* si) const { double result = eval_sum(si, m_opands, m_sz); //IFTRACE << "sum=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Plus::dump(std::ostream& os) const { os << "("; dump_opands(os, m_opands, m_sz, " + "); os << ")"; return os; } // ---------------------------------------------------------------------- // class Times // ---------------------------------------------------------------------- Times::Times(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Times::~Times() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Times::eval(const ScopeInfo* si) const { double result = 1.0; for (int i = 0; i < m_sz; ++i) { double x = m_opands[i]->eval(si); result *= x; } //IFTRACE << "result=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Times::dump(std::ostream& os) const { os << "("; dump_opands(os, m_opands, m_sz, " * "); os << ")"; return os; } // ---------------------------------------------------------------------- // class Max // ---------------------------------------------------------------------- Max::Max(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Max::~Max() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Max::eval(const ScopeInfo* si) const { double result = m_opands[0]->eval(si); for (int i = 1; i < m_sz; ++i) { double x = m_opands[i]->eval(si); result = std::max(result, x); } //IFTRACE << "max=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Max::dump(std::ostream& os) const { os << "max("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class Min // ---------------------------------------------------------------------- Min::Min(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Min::~Min() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Min::eval(const ScopeInfo* si) const { double result = m_opands[0]->eval(si); for (int i = 1; i < m_sz; ++i) { double x = m_opands[i]->eval(si); result = std::min(result, x); } //IFTRACE << "min=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Min::dump(std::ostream& os) const { os << "min("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class Mean // ---------------------------------------------------------------------- Mean::Mean(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } Mean::~Mean() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double Mean::eval(const ScopeInfo* si) const { double result = eval_mean(si, m_opands, m_sz); //IFTRACE << "mean=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& Mean::dump(std::ostream& os) const { os << "mean("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class StdDev // ---------------------------------------------------------------------- StdDev::StdDev(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } StdDev::~StdDev() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double StdDev::eval(const ScopeInfo* si) const { std::pair<double, double> v_m = eval_variance(si, m_opands, m_sz); double result = sqrt(v_m.first); //IFTRACE << "stddev=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& StdDev::dump(std::ostream& os) const { os << "stddev("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } // ---------------------------------------------------------------------- // class RStdDev // ---------------------------------------------------------------------- RStdDev::RStdDev(AExpr** oprnds, int numOprnds) : m_opands(oprnds), m_sz(numOprnds) { } RStdDev::~RStdDev() { for (int i = 0; i < m_sz; ++i) { delete m_opands[i]; } delete[] m_opands; } double RStdDev::eval(const ScopeInfo* si) const{ std::pair<double, double> v_m = eval_variance(si, m_opands, m_sz); double sdev = sqrt(v_m.first); // always non-negative double mean = v_m.second; double result = 0.0; if (mean > epsilon) { result = (sdev / mean) * 100; } //IFTRACE << "r-stddev=" << result << endl; AEXPR_CHECK(result); return result; } std::ostream& RStdDev::dump(std::ostream& os) const { os << "r-stddev("; dump_opands(os, m_opands, m_sz); os << ")"; return os; } //**************************************************************************** } // namespace Metric } // namespace Prof <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/core/ObjectFactory.h> #include <SofaGeneralLoader/MeshSTLLoader.h> #include <sofa/core/visual/VisualParams.h> #include <sofa/helper/stl.hpp> #include <iostream> //#include <fstream> // we can't use iostream because the windows implementation gets confused by the mix of text and binary #include <cstdio> #include <sstream> #include <string> namespace sofa { namespace component { namespace loader { using namespace sofa::defaulttype; SOFA_DECL_CLASS(MeshSTLLoader) int MeshSTLLoaderClass = core::RegisterObject("Specific mesh loader for STL file format.") .add< MeshSTLLoader >() .addAlias("MeshStlLoader") ; //Base VTK Loader MeshSTLLoader::MeshSTLLoader() : MeshLoader() , _headerSize(initData(&_headerSize, 80u, "headerSize","Size of the header binary file (just before the number of facet).")) , _forceBinary(initData(&_forceBinary, false, "forceBinary","Force reading in binary mode. Even in first keyword of the file is solid.")) , d_mergePositionUsingMap(initData(&d_mergePositionUsingMap, true, "mergePositionUsingMap","Since positions are duplicated in a STL, they have to be merged. Using a map to do so will temporarily duplicate memory but should be more efficient. Disable it if memory is really an issue.")) { } bool MeshSTLLoader::load() { const char* filename = m_filename.getFullPath().c_str(); std::ifstream file(filename); if (!file.good()) { msg_error() << "Cannot read file '" << m_filename; return false; } if( helper::stl::is_binary(file) || _forceBinary.getValue() ) { return this->readBinarySTL(filename); } else { return this->readSTL(file); } } bool MeshSTLLoader::readBinarySTL(const char *filename) { dmsg_info() << "Reading binary STL file..." ; std::ifstream dataFile (filename, std::ios::in | std::ios::binary); helper::vector<sofa::defaulttype::Vector3>& my_positions = *(this->d_positions.beginWriteOnly()); helper::vector<sofa::defaulttype::Vector3>& my_normals = *(this->d_normals.beginWriteOnly()); helper::vector<Triangle >& my_triangles = *(this->d_triangles.beginWriteOnly()); std::map< sofa::defaulttype::Vec3f, core::topology::Topology::index_type > my_map; core::topology::Topology::index_type positionCounter = 0; bool useMap = d_mergePositionUsingMap.getValue(); // Skipping header file char buffer[256]; dataFile.read(buffer, _headerSize.getValue()); // sout << "Header binary file: "<< buffer << sendl; uint32_t nbrFacet; dataFile.read((char*)&nbrFacet, 4); my_triangles.resize( nbrFacet ); // exact size my_normals.resize( nbrFacet ); // exact size my_positions.reserve( nbrFacet * 3 ); // max size #ifndef NDEBUG { // checking that the file is large enough to contain the given nb of facets // store current pos in file std::streampos pos = dataFile.tellg(); // get length of file dataFile.seekg(0, std::ios::end); std::streampos length = dataFile.tellg(); // restore pos in file dataFile.seekg(pos); // check for length assert( length >= _headerSize.getValue() + 4 + nbrFacet * (12 /*normal*/ + 3 * 12 /*points*/ + 2 /*attribute*/ ) ); } #endif // temporaries sofa::defaulttype::Vec3f vertex, normal; // Parsing facets for (uint32_t i = 0; i<nbrFacet; ++i) { Triangle& the_tri = my_triangles[i]; // Normal: dataFile.read((char*)&normal[0], 4); dataFile.read((char*)&normal[1], 4); dataFile.read((char*)&normal[2], 4); my_normals[i] = normal; // Vertices: for (size_t j = 0; j<3; ++j) { dataFile.read((char*)&vertex[0], 4); dataFile.read((char*)&vertex[1], 4); dataFile.read((char*)&vertex[2], 4); if( useMap ) { auto it = my_map.find( vertex ); if( it == my_map.end() ) { the_tri[j] = positionCounter; my_map[vertex] = positionCounter++; my_positions.push_back(vertex); } else { the_tri[j] = it->second; } } else { bool find = false; for (size_t k=0; k<my_positions.size(); ++k) if ( (vertex[0] == my_positions[k][0]) && (vertex[1] == my_positions[k][1]) && (vertex[2] == my_positions[k][2])) { find = true; the_tri[j] = static_cast<core::topology::Topology::PointID>(k); break; } if (!find) { my_positions.push_back(vertex); the_tri[j] = my_positions.size()-1; } } } // Attribute byte count uint16_t count; dataFile.read((char*)&count, 2); // Security: // checked once before reading in debug mode // position = dataFile.tellg(); // if (position == length) // break; } this->d_positions.endEdit(); this->d_triangles.endEdit(); this->d_normals.endEdit(); dmsg_info() << "done!" ; return true; } bool MeshSTLLoader::readSTL(std::ifstream& dataFile) { dmsg_info() << "Reading STL file..." ; // Init std::string buffer; std::string name; // name of the solid, needed? helper::vector<sofa::defaulttype::Vector3>& my_positions = *(d_positions.beginEdit()); helper::vector<sofa::defaulttype::Vector3>& my_normals = *(d_normals.beginEdit()); helper::vector<Triangle >& my_triangles = *(d_triangles.beginEdit()); std::map< sofa::defaulttype::Vec3f, core::topology::Topology::index_type > my_map; core::topology::Topology::index_type positionCounter = 0; bool useMap = d_mergePositionUsingMap.getValue(); // get length of file: dataFile.seekg(0, std::ios::end); std::streampos length = dataFile.tellg(); dataFile.seekg(0, std::ios::beg); // Reading header dataFile >> buffer >> name; Triangle the_tri; size_t cpt = 0; std::streampos position = 0; // Parsing facets while (position < length) { sofa::defaulttype::Vector3 normal, vertex; std::getline(dataFile, buffer); std::stringstream line; std::clog << line.str() << std::endl; std::string bufferWord; line >> bufferWord; if (bufferWord == "facet") { line >> bufferWord >> normal[0] >> normal[1] >> normal[2]; my_normals.push_back(normal); } else if (bufferWord == "vertex") { line >> vertex[0] >> vertex[1] >> vertex[2]; if( useMap ) { auto it = my_map.find( vertex ); if( it == my_map.end() ) { the_tri[cpt] = positionCounter; my_map[vertex] = positionCounter++; my_positions.push_back(vertex); } else { the_tri[cpt] = it->second; } } else { bool find = false; for (size_t i=0; i<my_positions.size(); ++i) if ( (vertex[0] == my_positions[i][0]) && (vertex[1] == my_positions[i][1]) && (vertex[2] == my_positions[i][2])) { find = true; the_tri[cpt] = static_cast<core::topology::Topology::PointID>(i); break; } if (!find) { my_positions.push_back(vertex); the_tri[cpt] = static_cast<core::topology::Topology::PointID>(my_positions.size()-1); } } cpt++; } else if (bufferWord == "endfacet") { my_triangles.push_back(the_tri); cpt = 0; } else if (bufferWord == "endsolid" || bufferWord == "end") { break; } position = dataFile.tellg(); } d_positions.endEdit(); d_triangles.endEdit(); d_normals.endEdit(); dataFile.close(); dmsg_info() << "done!" ; return true; } } // namespace loader } // namespace component } // namespace sofa <commit_msg>fixing ascii stl loading. GRRRRR<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/core/ObjectFactory.h> #include <SofaGeneralLoader/MeshSTLLoader.h> #include <sofa/core/visual/VisualParams.h> #include <sofa/helper/stl.hpp> #include <iostream> //#include <fstream> // we can't use iostream because the windows implementation gets confused by the mix of text and binary #include <cstdio> #include <sstream> #include <string> namespace sofa { namespace component { namespace loader { using namespace sofa::defaulttype; SOFA_DECL_CLASS(MeshSTLLoader) int MeshSTLLoaderClass = core::RegisterObject("Specific mesh loader for STL file format.") .add< MeshSTLLoader >() .addAlias("MeshStlLoader") ; //Base VTK Loader MeshSTLLoader::MeshSTLLoader() : MeshLoader() , _headerSize(initData(&_headerSize, 80u, "headerSize","Size of the header binary file (just before the number of facet).")) , _forceBinary(initData(&_forceBinary, false, "forceBinary","Force reading in binary mode. Even in first keyword of the file is solid.")) , d_mergePositionUsingMap(initData(&d_mergePositionUsingMap, true, "mergePositionUsingMap","Since positions are duplicated in a STL, they have to be merged. Using a map to do so will temporarily duplicate memory but should be more efficient. Disable it if memory is really an issue.")) { } bool MeshSTLLoader::load() { const char* filename = m_filename.getFullPath().c_str(); std::ifstream file(filename); if (!file.good()) { msg_error() << "Cannot read file '" << m_filename; return false; } if( helper::stl::is_binary(file) || _forceBinary.getValue() ) { return this->readBinarySTL(filename); } else { return this->readSTL(file); } } bool MeshSTLLoader::readBinarySTL(const char *filename) { dmsg_info() << "Reading binary STL file..." ; std::ifstream dataFile (filename, std::ios::in | std::ios::binary); helper::vector<sofa::defaulttype::Vector3>& my_positions = *(this->d_positions.beginWriteOnly()); helper::vector<sofa::defaulttype::Vector3>& my_normals = *(this->d_normals.beginWriteOnly()); helper::vector<Triangle >& my_triangles = *(this->d_triangles.beginWriteOnly()); std::map< sofa::defaulttype::Vec3f, core::topology::Topology::index_type > my_map; core::topology::Topology::index_type positionCounter = 0; bool useMap = d_mergePositionUsingMap.getValue(); // Skipping header file char buffer[256]; dataFile.read(buffer, _headerSize.getValue()); // sout << "Header binary file: "<< buffer << sendl; uint32_t nbrFacet; dataFile.read((char*)&nbrFacet, 4); my_triangles.resize( nbrFacet ); // exact size my_normals.resize( nbrFacet ); // exact size my_positions.reserve( nbrFacet * 3 ); // max size #ifndef NDEBUG { // checking that the file is large enough to contain the given nb of facets // store current pos in file std::streampos pos = dataFile.tellg(); // get length of file dataFile.seekg(0, std::ios::end); std::streampos length = dataFile.tellg(); // restore pos in file dataFile.seekg(pos); // check for length assert( length >= _headerSize.getValue() + 4 + nbrFacet * (12 /*normal*/ + 3 * 12 /*points*/ + 2 /*attribute*/ ) ); } #endif // temporaries sofa::defaulttype::Vec3f vertex, normal; // Parsing facets for (uint32_t i = 0; i<nbrFacet; ++i) { Triangle& the_tri = my_triangles[i]; // Normal: dataFile.read((char*)&normal[0], 4); dataFile.read((char*)&normal[1], 4); dataFile.read((char*)&normal[2], 4); my_normals[i] = normal; // Vertices: for (size_t j = 0; j<3; ++j) { dataFile.read((char*)&vertex[0], 4); dataFile.read((char*)&vertex[1], 4); dataFile.read((char*)&vertex[2], 4); if( useMap ) { auto it = my_map.find( vertex ); if( it == my_map.end() ) { the_tri[j] = positionCounter; my_map[vertex] = positionCounter++; my_positions.push_back(vertex); } else { the_tri[j] = it->second; } } else { bool find = false; for (size_t k=0; k<my_positions.size(); ++k) if ( (vertex[0] == my_positions[k][0]) && (vertex[1] == my_positions[k][1]) && (vertex[2] == my_positions[k][2])) { find = true; the_tri[j] = static_cast<core::topology::Topology::PointID>(k); break; } if (!find) { my_positions.push_back(vertex); the_tri[j] = my_positions.size()-1; } } } // Attribute byte count uint16_t count; dataFile.read((char*)&count, 2); // Security: // checked once before reading in debug mode // position = dataFile.tellg(); // if (position == length) // break; } this->d_positions.endEdit(); this->d_triangles.endEdit(); this->d_normals.endEdit(); dmsg_info() << "done!" ; return true; } bool MeshSTLLoader::readSTL(std::ifstream& dataFile) { dmsg_info() << "Reading STL file..." ; // Init std::string buffer; std::string name; // name of the solid, needed? helper::vector<sofa::defaulttype::Vector3>& my_positions = *(d_positions.beginEdit()); helper::vector<sofa::defaulttype::Vector3>& my_normals = *(d_normals.beginEdit()); helper::vector<Triangle >& my_triangles = *(d_triangles.beginEdit()); std::map< sofa::defaulttype::Vec3f, core::topology::Topology::index_type > my_map; core::topology::Topology::index_type positionCounter = 0; bool useMap = d_mergePositionUsingMap.getValue(); // get length of file: dataFile.seekg(0, std::ios::end); std::streampos length = dataFile.tellg(); dataFile.seekg(0, std::ios::beg); // Reading header dataFile >> buffer >> name; Triangle the_tri; size_t cpt = 0; std::streampos position = 0; // Parsing facets while (position < length) { sofa::defaulttype::Vector3 normal, vertex; std::getline(dataFile, buffer); std::stringstream line; line << buffer; std::string bufferWord; line >> bufferWord; if (bufferWord == "facet") { line >> bufferWord >> normal[0] >> normal[1] >> normal[2]; my_normals.push_back(normal); } else if (bufferWord == "vertex") { line >> vertex[0] >> vertex[1] >> vertex[2]; if( useMap ) { auto it = my_map.find( vertex ); if( it == my_map.end() ) { the_tri[cpt] = positionCounter; my_map[vertex] = positionCounter++; my_positions.push_back(vertex); } else { the_tri[cpt] = it->second; } } else { bool find = false; for (size_t i=0; i<my_positions.size(); ++i) if ( (vertex[0] == my_positions[i][0]) && (vertex[1] == my_positions[i][1]) && (vertex[2] == my_positions[i][2])) { find = true; the_tri[cpt] = static_cast<core::topology::Topology::PointID>(i); break; } if (!find) { my_positions.push_back(vertex); the_tri[cpt] = static_cast<core::topology::Topology::PointID>(my_positions.size()-1); } } cpt++; } else if (bufferWord == "endfacet") { my_triangles.push_back(the_tri); cpt = 0; } else if (bufferWord == "endsolid" || bufferWord == "end") { break; } position = dataFile.tellg(); } d_positions.endEdit(); d_triangles.endEdit(); d_normals.endEdit(); dataFile.close(); dmsg_info() << "done!" ; return true; } } // namespace loader } // namespace component } // namespace sofa <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** 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 qt-info@nokia.com. ** **************************************************************************/ #include "tcpportsgatherer.h" #include "qtcassert.h" #include <QFile> #include <QStringList> #include <QProcess> #ifdef Q_OS_WIN #include <QLibrary> #include <winsock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #endif namespace Utils { namespace Internal { class TcpPortsGathererPrivate { public: TcpPortsGathererPrivate(TcpPortsGatherer::ProtocolFlags protocolFlags) : protocolFlags(protocolFlags) {} TcpPortsGatherer::ProtocolFlags protocolFlags; PortList usedPorts; void updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags); void updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags); void updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags); }; #ifdef Q_OS_WIN template <typename Table > QSet<int> usedTcpPorts(ULONG (__stdcall *Func)(Table*, PULONG, BOOL)) { Table *table = static_cast<Table*>(malloc(sizeof(Table))); DWORD dwSize = sizeof(Table); // get the necessary size into the dwSize variable DWORD dwRetVal = Func(table, &dwSize, false); if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) { free(table); table = static_cast<Table*>(malloc(dwSize)); } // get the actual data QSet<int> result; dwRetVal = Func(table, &dwSize, false); if (dwRetVal == NO_ERROR) { for (quint32 i = 0; i < table->dwNumEntries; i++) { quint16 port = ntohs(table->table[i].dwLocalPort); if (!result.contains(port)) result.insert(port); } } else { qWarning() << "TcpPortsGatherer: GetTcpTable failed with" << dwRetVal; } free(table); return result; } #endif void TcpPortsGathererPrivate::updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags) { #ifdef Q_OS_WIN QSet<int> ports; if (protocolFlags & TcpPortsGatherer::IPv4Protocol) ports.unite(usedTcpPorts<MIB_TCPTABLE>(GetTcpTable)); //Dynamically load symbol for GetTcp6Table for systems that dont have support for IPV6, //eg Windows XP typedef ULONG (__stdcall *GetTcp6TablePtr)(PMIB_TCP6TABLE, PULONG, BOOL); static GetTcp6TablePtr getTcp6TablePtr = 0; if (!getTcp6TablePtr) getTcp6TablePtr = (GetTcp6TablePtr)QLibrary::resolve(QLatin1String("Iphlpapi.dll"), "GetTcp6Table"); if (getTcp6TablePtr && (protocolFlags & TcpPortsGatherer::IPv6Protocol)) ports.unite(usedTcpPorts<MIB_TCP6TABLE>(getTcp6TablePtr)); foreach (int port, ports) { if (!usedPorts.contains(port)) usedPorts.addPort(port); } #endif Q_UNUSED(protocolFlags); } void TcpPortsGathererPrivate::updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags) { QStringList filePaths; if (protocolFlags & TcpPortsGatherer::IPv4Protocol) filePaths.append(QLatin1String("/proc/net/tcp")); if (protocolFlags & TcpPortsGatherer::IPv6Protocol) filePaths.append(QLatin1String("/proc/net/tcp6")); foreach (const QString &filePath, filePaths) { QFile file(filePath); if (!file.open(QFile::ReadOnly | QFile::Text)) { qWarning() << "TcpPortsGatherer: Cannot open file" << filePath << ":" << file.errorString(); continue; } if (file.atEnd()) // read first line describing the output file.readLine(); static QRegExp pattern(QLatin1String("^\\s*" // start of line, whitespace "\\d+:\\s*" // integer, colon, space "[0-9A-Fa-f]+:" // hexadecimal number (ip), colon "([0-9A-Fa-f]+)" // hexadecimal number (port!) )); while (!file.atEnd()) { QByteArray line = file.readLine(); if (pattern.indexIn(line) != -1) { bool isNumber; quint16 port = pattern.cap(1).toUShort(&isNumber, 16); QTC_ASSERT(isNumber, continue); if (!usedPorts.contains(port)) usedPorts.addPort(port); } else { qWarning() << "TcpPortsGatherer: File" << filePath << "has unexpected format."; continue; } } } } // Only works with FreeBSD version of netstat like we have on Mac OS X void TcpPortsGathererPrivate::updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags) { QStringList netstatArgs; netstatArgs.append(QLatin1String("-a")); // show also sockets of server processes netstatArgs.append(QLatin1String("-n")); // show network addresses as numbers netstatArgs.append(QLatin1String("-p")); netstatArgs.append(QLatin1String("tcp")); if (protocolFlags != TcpPortsGatherer::AnyIPProcol) { netstatArgs.append(QLatin1String("-f")); // limit to address family if (protocolFlags == TcpPortsGatherer::IPv4Protocol) netstatArgs.append(QLatin1String("inet")); else netstatArgs.append(QLatin1String("inet6")); } QProcess netstatProcess; netstatProcess.start(QLatin1String("netstat"), netstatArgs); if (!netstatProcess.waitForFinished(30000)) { qWarning() << "TcpPortsGatherer: netstat did not return in time."; return; } QList<QByteArray> output = netstatProcess.readAllStandardOutput().split('\n'); foreach (const QByteArray &line, output) { static QRegExp pattern(QLatin1String("^tcp[46]+" // "tcp", followed by "4", "6", "46" "\\s+\\d+" // whitespace, number (Recv-Q) "\\s+\\d+" // whitespace, number (Send-Q) "\\s+(\\S+)")); // whitespace, Local Address if (pattern.indexIn(line) != -1) { QString localAddress = pattern.cap(1); // Examples of local addresses: // '*.56501' , '*.*' 'fe80::1%lo0.123' int portDelimiterPos = localAddress.lastIndexOf("."); if (portDelimiterPos == -1) continue; localAddress = localAddress.mid(portDelimiterPos + 1); bool isNumber; quint16 port = localAddress.toUShort(&isNumber); if (!isNumber) continue; if (!usedPorts.contains(port)) usedPorts.addPort(port); } } } } // namespace Internal /*! \class Utils::TcpPortsGatherer \brief Gather the list of local TCP ports already in use. Query the system for the list of local TCP ports already in use. This information can be used to select a port for use in a range. */ TcpPortsGatherer::TcpPortsGatherer(TcpPortsGatherer::ProtocolFlags protocolFlags) : d(new Internal::TcpPortsGathererPrivate(protocolFlags)) { update(); } TcpPortsGatherer::~TcpPortsGatherer() { delete d; } void TcpPortsGatherer::update() { d->usedPorts = PortList(); #if defined(Q_OS_WIN) d->updateWin(d->protocolFlags); #elif defined(Q_OS_LINUX) d->updateLinux(d->protocolFlags); #else d->updateNetstat(d->protocolFlags); #endif } PortList TcpPortsGatherer::usedPorts() const { return d->usedPorts; } /*! Select a port out of \a freePorts that is not yet used. Returns the port, or 0 if no free port is available. */ quint16 TcpPortsGatherer::getNextFreePort(PortList *freePorts) { QTC_ASSERT(freePorts, return 0); while (freePorts->hasMore()) { const int port = freePorts->getNext(); if (!d->usedPorts.contains(port)) return port; } return 0; } } // namespace Utils <commit_msg>TcpPortsGatherer: Fix compilation with MinGW/4.6.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** 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 qt-info@nokia.com. ** **************************************************************************/ #include "tcpportsgatherer.h" #include "qtcassert.h" #include <QFile> #include <QStringList> #include <QProcess> #ifdef Q_OS_WIN #include <QLibrary> #include <winsock2.h> #include <ws2tcpip.h> #include <iphlpapi.h> #endif #if defined(Q_OS_WIN) && defined(Q_CC_MINGW) // Missing declarations for MinGW. This requires MinGW with gcc 4.6. typedef enum { } MIB_TCP_STATE; typedef struct _MIB_TCP6ROW { MIB_TCP_STATE State; IN6_ADDR LocalAddr; DWORD dwLocalScopeId; DWORD dwLocalPort; IN6_ADDR RemoteAddr; DWORD dwRemoteScopeId; DWORD dwRemotePort; } MIB_TCP6ROW, *PMIB_TCP6ROW; typedef struct _MIB_TCP6TABLE { DWORD dwNumEntries; MIB_TCP6ROW table[ANY_SIZE]; } MIB_TCP6TABLE, *PMIB_TCP6TABLE; #endif // defined(Q_OS_WIN) && defined(Q_CC_MINGW) namespace Utils { namespace Internal { class TcpPortsGathererPrivate { public: TcpPortsGathererPrivate(TcpPortsGatherer::ProtocolFlags protocolFlags) : protocolFlags(protocolFlags) {} TcpPortsGatherer::ProtocolFlags protocolFlags; PortList usedPorts; void updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags); void updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags); void updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags); }; #ifdef Q_OS_WIN template <typename Table > QSet<int> usedTcpPorts(ULONG (__stdcall *Func)(Table*, PULONG, BOOL)) { Table *table = static_cast<Table*>(malloc(sizeof(Table))); DWORD dwSize = sizeof(Table); // get the necessary size into the dwSize variable DWORD dwRetVal = Func(table, &dwSize, false); if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) { free(table); table = static_cast<Table*>(malloc(dwSize)); } // get the actual data QSet<int> result; dwRetVal = Func(table, &dwSize, false); if (dwRetVal == NO_ERROR) { for (quint32 i = 0; i < table->dwNumEntries; i++) { quint16 port = ntohs(table->table[i].dwLocalPort); if (!result.contains(port)) result.insert(port); } } else { qWarning() << "TcpPortsGatherer: GetTcpTable failed with" << dwRetVal; } free(table); return result; } #endif void TcpPortsGathererPrivate::updateWin(TcpPortsGatherer::ProtocolFlags protocolFlags) { #ifdef Q_OS_WIN QSet<int> ports; if (protocolFlags & TcpPortsGatherer::IPv4Protocol) ports.unite(usedTcpPorts<MIB_TCPTABLE>(GetTcpTable)); //Dynamically load symbol for GetTcp6Table for systems that dont have support for IPV6, //eg Windows XP typedef ULONG (__stdcall *GetTcp6TablePtr)(PMIB_TCP6TABLE, PULONG, BOOL); static GetTcp6TablePtr getTcp6TablePtr = 0; if (!getTcp6TablePtr) getTcp6TablePtr = (GetTcp6TablePtr)QLibrary::resolve(QLatin1String("Iphlpapi.dll"), "GetTcp6Table"); if (getTcp6TablePtr && (protocolFlags & TcpPortsGatherer::IPv6Protocol)) ports.unite(usedTcpPorts<MIB_TCP6TABLE>(getTcp6TablePtr)); foreach (int port, ports) { if (!usedPorts.contains(port)) usedPorts.addPort(port); } #endif Q_UNUSED(protocolFlags); } void TcpPortsGathererPrivate::updateLinux(TcpPortsGatherer::ProtocolFlags protocolFlags) { QStringList filePaths; if (protocolFlags & TcpPortsGatherer::IPv4Protocol) filePaths.append(QLatin1String("/proc/net/tcp")); if (protocolFlags & TcpPortsGatherer::IPv6Protocol) filePaths.append(QLatin1String("/proc/net/tcp6")); foreach (const QString &filePath, filePaths) { QFile file(filePath); if (!file.open(QFile::ReadOnly | QFile::Text)) { qWarning() << "TcpPortsGatherer: Cannot open file" << filePath << ":" << file.errorString(); continue; } if (file.atEnd()) // read first line describing the output file.readLine(); static QRegExp pattern(QLatin1String("^\\s*" // start of line, whitespace "\\d+:\\s*" // integer, colon, space "[0-9A-Fa-f]+:" // hexadecimal number (ip), colon "([0-9A-Fa-f]+)" // hexadecimal number (port!) )); while (!file.atEnd()) { QByteArray line = file.readLine(); if (pattern.indexIn(line) != -1) { bool isNumber; quint16 port = pattern.cap(1).toUShort(&isNumber, 16); QTC_ASSERT(isNumber, continue); if (!usedPorts.contains(port)) usedPorts.addPort(port); } else { qWarning() << "TcpPortsGatherer: File" << filePath << "has unexpected format."; continue; } } } } // Only works with FreeBSD version of netstat like we have on Mac OS X void TcpPortsGathererPrivate::updateNetstat(TcpPortsGatherer::ProtocolFlags protocolFlags) { QStringList netstatArgs; netstatArgs.append(QLatin1String("-a")); // show also sockets of server processes netstatArgs.append(QLatin1String("-n")); // show network addresses as numbers netstatArgs.append(QLatin1String("-p")); netstatArgs.append(QLatin1String("tcp")); if (protocolFlags != TcpPortsGatherer::AnyIPProcol) { netstatArgs.append(QLatin1String("-f")); // limit to address family if (protocolFlags == TcpPortsGatherer::IPv4Protocol) netstatArgs.append(QLatin1String("inet")); else netstatArgs.append(QLatin1String("inet6")); } QProcess netstatProcess; netstatProcess.start(QLatin1String("netstat"), netstatArgs); if (!netstatProcess.waitForFinished(30000)) { qWarning() << "TcpPortsGatherer: netstat did not return in time."; return; } QList<QByteArray> output = netstatProcess.readAllStandardOutput().split('\n'); foreach (const QByteArray &line, output) { static QRegExp pattern(QLatin1String("^tcp[46]+" // "tcp", followed by "4", "6", "46" "\\s+\\d+" // whitespace, number (Recv-Q) "\\s+\\d+" // whitespace, number (Send-Q) "\\s+(\\S+)")); // whitespace, Local Address if (pattern.indexIn(line) != -1) { QString localAddress = pattern.cap(1); // Examples of local addresses: // '*.56501' , '*.*' 'fe80::1%lo0.123' int portDelimiterPos = localAddress.lastIndexOf("."); if (portDelimiterPos == -1) continue; localAddress = localAddress.mid(portDelimiterPos + 1); bool isNumber; quint16 port = localAddress.toUShort(&isNumber); if (!isNumber) continue; if (!usedPorts.contains(port)) usedPorts.addPort(port); } } } } // namespace Internal /*! \class Utils::TcpPortsGatherer \brief Gather the list of local TCP ports already in use. Query the system for the list of local TCP ports already in use. This information can be used to select a port for use in a range. */ TcpPortsGatherer::TcpPortsGatherer(TcpPortsGatherer::ProtocolFlags protocolFlags) : d(new Internal::TcpPortsGathererPrivate(protocolFlags)) { update(); } TcpPortsGatherer::~TcpPortsGatherer() { delete d; } void TcpPortsGatherer::update() { d->usedPorts = PortList(); #if defined(Q_OS_WIN) d->updateWin(d->protocolFlags); #elif defined(Q_OS_LINUX) d->updateLinux(d->protocolFlags); #else d->updateNetstat(d->protocolFlags); #endif } PortList TcpPortsGatherer::usedPorts() const { return d->usedPorts; } /*! Select a port out of \a freePorts that is not yet used. Returns the port, or 0 if no free port is available. */ quint16 TcpPortsGatherer::getNextFreePort(PortList *freePorts) { QTC_ASSERT(freePorts, return 0); while (freePorts->hasMore()) { const int port = freePorts->getNext(); if (!d->usedPorts.contains(port)) return port; } return 0; } } // namespace Utils <|endoftext|>
<commit_before>/* */ #include "lineFollowing.h" using namespace std; using namespace cv; ControlMovements lineFollowingControl() { line_main(); return ControlMovements(); } void line_main() { // printf("Hello, this is Caleb\n"); VideoCapture cap("../../tests/videos/top_down_1.m4v"); if (!cap.isOpened()) // check if we succeeded return; namedWindow("edges", CV_WINDOW_NORMAL); // Mat edges; for (; ;) { Mat mask; Mat frame, hsv; cap >> frame; // get a new frame from camera resize(frame, frame, Size(), .2, .2); cvtColor(frame, hsv, CV_BGR2HSV); double minH = 30; double minS = 0; double minV = 240; double maxH = 80; double maxS = 70; double maxV = 255; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, mask); // bitwise_and(frame, frame, frame, mask); vector <Vec4i> lines; HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10); printf("Adding in %d lines\n", (int) lines.size()); for (size_t i = 0; i < lines.size(); i++) { Vec4i l = lines[i]; line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA); // break; } // if (lines.size() < 1) continue; imshow("edges", frame); if (waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return; } <commit_msg>size changes<commit_after>/* */ #include "lineFollowing.h" using namespace std; using namespace cv; ControlMovements lineFollowingControl() { line_main(); return ControlMovements(); } void line_main() { // printf("Hello, this is Caleb\n"); VideoCapture cap("../../tests/videos/top_down_1.m4v"); if (!cap.isOpened()) // check if we succeeded return; namedWindow("edges", CV_WINDOW_NORMAL); // Mat edges; for (; ;) { Mat mask; Mat frame, hsv; cap >> frame; // get a new frame from camera resize(frame, frame, Size(), .2, .2); cvtColor(frame, hsv, CV_BGR2HSV); double minH = 30; double minS = 0; double minV = 240; double maxH = 80; double maxS = 70; double maxV = 255; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, mask); // bitwise_and(frame, frame, frame, mask); vector <Vec4i> lines; HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10); printf("Adding in %d lines\n", (int) lines.size()); for (size_t i = 0; i < lines.size(); i++) { Vec4i l = lines[i]; line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA); // break; } // if (lines.size() < 1) continue; imshow("edges", frame); if (waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return; } <|endoftext|>
<commit_before>//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. All rights reserved. // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains definition of class ossimXmlAttribute. // //***************************************************************************** // $Id: ossimXmlAttribute.cpp 23503 2015-09-08 07:07:51Z rashadkm $ #include <iostream> #include <sstream> #include <ossim/base/ossimXmlAttribute.h> #include <ossim/base/ossimNotifyContext.h> RTTI_DEF2(ossimXmlAttribute, "ossimXmlAttribute", ossimObject, ossimErrorStatusInterface) static std::istream& xmlskipws(std::istream& in) { int c = in.peek(); while((!in.fail())&& ((c == ' ') || (c == '\t') || (c == '\n')|| (c == '\r'))) { in.ignore(1); c = in.peek(); } return in; } ossimXmlAttribute::ossimXmlAttribute(ossimString& spec) { std::stringstream in(spec); read(in); } ossimXmlAttribute::ossimXmlAttribute(const ossimXmlAttribute& src) :theName(src.theName), theValue(src.theValue) { } bool ossimXmlAttribute::read(std::istream& in) { xmlskipws(in); if(in.fail()) return false; if(readName(in)) { xmlskipws(in); if((in.peek() != '=')|| (in.fail())) { setErrorStatus(); return false; } in.ignore(1); if(readValue(in)) { return true; } else { setErrorStatus(); return false; } } return false; #if 0 // // Pull out name: // theName = spec.before('='); theName = theName.trim(); if (theName.empty()) { ossimNotify(ossimNotifyLevel_FATAL) << "ossimXmlAttribute::ossimXmlAttribute \n" << "Bad attribute format encountered near:\n\""<< spec<<"\"\n" << "Parsing aborted...\n"; setErrorStatus(); return; } spec = spec.after('='); //*** // Read value: //*** char quote_char = spec[0]; spec = spec.after(quote_char); // after first quote theValue = spec.before(quote_char); // before second quote // // Reposition attribute specification to the start of next attribute or end // of tag: // spec = spec.after(quote_char); // after second quote ossimString next_entry ("-?[+0-9A-Za-z<>]+"); spec = spec.fromRegExp(next_entry.c_str()); #endif } ossimXmlAttribute::~ossimXmlAttribute() { } ossimXmlAttribute::ossimXmlAttribute() { } ossimXmlAttribute::ossimXmlAttribute(const ossimString& name, const ossimString& value) { setNameValue(name, value); } const ossimString& ossimXmlAttribute::getName() const { return theName; } const ossimString& ossimXmlAttribute::getValue() const { return theValue; } void ossimXmlAttribute::setNameValue(const ossimString& name, const ossimString& value) { theName = name; theValue = value; } void ossimXmlAttribute::setName(const ossimString& name) { theName = name; } void ossimXmlAttribute::setValue(const ossimString& value) { theValue = value; } std::ostream& operator << (std::ostream& os, const ossimXmlAttribute* xml_attr) { os << " " << xml_attr->theName << "=\"" << xml_attr->theValue << "\""; return os; } bool ossimXmlAttribute::readName(std::istream& in) { xmlskipws(in); theName = ""; char c = in.peek(); while((c != ' ')&& (c != '\n')&& (c != '\r')&& (c != '\t')&& (c != '=')&& (c != '<')&& (c != '/')&& (c != '>')&& (!in.fail())) { theName += (char)in.get(); c = in.peek(); } return ((!in.fail())&& (theName != "")); } bool ossimXmlAttribute::readValue(std::istream& in) { xmlskipws(in); if(in.fail()) return false; theValue = ""; char c = in.peek(); bool done = false; char startQuote = '\0'; if((c == '\'')|| (c == '"')) { startQuote = c; theValue += in.get(); while(!done&&!in.fail()) { c = in.peek(); if(c==startQuote) { theValue += c; done = true; in.ignore(1); } else if(c == '\n') { done = true; } else { theValue += in.get(); } } } bool is_empty = false; //then this could be empty with two qoutes if(theValue.size() == 2 && theValue[0] == startQuote && theValue[1] == startQuote) { theValue = ""; is_empty = true; } if(theValue != "") { std::string::iterator startIter = theValue.begin(); std::string::iterator endIter = theValue.end(); --endIter; if(*startIter == startQuote) { ++startIter; } else { return false; setErrorStatus(); } if(*endIter != startQuote) { return false; setErrorStatus(); } theValue = ossimString(startIter, endIter); } return ((!in.bad())&& (is_empty || theValue !="")); } <commit_msg>build fails on msvc. error C2999<commit_after>//******************************************************************* // Copyright (C) 2001 ImageLinks Inc. All rights reserved. // // License: See top level LICENSE.txt file. // // Author: Oscar Kramer (ossim port by D. Burken) // // Description: // // Contains definition of class ossimXmlAttribute. // //***************************************************************************** // $Id: ossimXmlAttribute.cpp 23503 2015-09-08 07:07:51Z rashadkm $ #include <iostream> #include <sstream> #include <ossim/base/ossimXmlAttribute.h> #include <ossim/base/ossimNotifyContext.h> RTTI_DEF2(ossimXmlAttribute, "ossimXmlAttribute", ossimObject, ossimErrorStatusInterface) static std::istream& xmlskipws(std::istream& in) { int c = in.peek(); while((!in.fail())&& ((c == ' ') || (c == '\t') || (c == '\n')|| (c == '\r'))) { in.ignore(1); c = in.peek(); } return in; } ossimXmlAttribute::ossimXmlAttribute(ossimString& spec) { std::stringstream in(spec); read(in); } ossimXmlAttribute::ossimXmlAttribute(const ossimXmlAttribute& src) :theName(src.theName), theValue(src.theValue) { } bool ossimXmlAttribute::read(std::istream& in) { xmlskipws(in); if(in.fail()) return false; if(readName(in)) { xmlskipws(in); if((in.peek() != '=')|| (in.fail())) { setErrorStatus(); return false; } in.ignore(1); if(readValue(in)) { return true; } else { setErrorStatus(); return false; } } return false; #if 0 // // Pull out name: // theName = spec.before('='); theName = theName.trim(); if (theName.empty()) { ossimNotify(ossimNotifyLevel_FATAL) << "ossimXmlAttribute::ossimXmlAttribute \n" << "Bad attribute format encountered near:\n\""<< spec<<"\"\n" << "Parsing aborted...\n"; setErrorStatus(); return; } spec = spec.after('='); //*** // Read value: //*** char quote_char = spec[0]; spec = spec.after(quote_char); // after first quote theValue = spec.before(quote_char); // before second quote // // Reposition attribute specification to the start of next attribute or end // of tag: // spec = spec.after(quote_char); // after second quote ossimString next_entry ("-?[+0-9A-Za-z<>]+"); spec = spec.fromRegExp(next_entry.c_str()); #endif } ossimXmlAttribute::~ossimXmlAttribute() { } ossimXmlAttribute::ossimXmlAttribute() { } ossimXmlAttribute::ossimXmlAttribute(const ossimString& name, const ossimString& value) { setNameValue(name, value); } const ossimString& ossimXmlAttribute::getName() const { return theName; } const ossimString& ossimXmlAttribute::getValue() const { return theValue; } void ossimXmlAttribute::setNameValue(const ossimString& name, const ossimString& value) { theName = name; theValue = value; } void ossimXmlAttribute::setName(const ossimString& name) { theName = name; } void ossimXmlAttribute::setValue(const ossimString& value) { theValue = value; } std::ostream& operator << (std::ostream& os, const ossimXmlAttribute* xml_attr) { os << " " << xml_attr->theName << "=\"" << xml_attr->theValue << "\""; return os; } bool ossimXmlAttribute::readName(std::istream& in) { xmlskipws(in); theName = ""; char c = in.peek(); while((c != ' ')&& (c != '\n')&& (c != '\r')&& (c != '\t')&& (c != '=')&& (c != '<')&& (c != '/')&& (c != '>')&& (!in.fail())) { theName += (char)in.get(); c = in.peek(); } return ((!in.fail())&& (theName != "")); } bool ossimXmlAttribute::readValue(std::istream& in) { xmlskipws(in); if(in.fail()) return false; theValue = ""; char c = in.peek(); bool done = false; char startQuote = '\0'; if((c == '\'')|| (c == '"')) { startQuote = c; theValue += in.get(); while(!done&&!in.fail()) { c = in.peek(); if(c==startQuote) { theValue += c; done = true; in.ignore(1); } else if(c == '\n') { done = true; } else { theValue += in.get(); } } } bool is_empty = false; //then this could be empty with two qoutes std::string::size_type p = 0; //then this could be empty with two qoutes if(theValue.size() == 2 && theValue[p] == startQuote && theValue[p+1] == startQuote) { theValue = ""; is_empty = true; } if(theValue != "") { std::string::iterator startIter = theValue.begin(); std::string::iterator endIter = theValue.end(); --endIter; if(*startIter == startQuote) { ++startIter; } else { return false; setErrorStatus(); } if(*endIter != startQuote) { return false; setErrorStatus(); } theValue = ossimString(startIter, endIter); } return ((!in.bad())&& (is_empty || theValue !="")); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * 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/base/test/vm_test_utils.h" #include "perfetto/base/build_config.h" #include "perfetto/ext/base/utils.h" #include <memory> #include <errno.h> #include <string.h> #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <Windows.h> #include <Psapi.h> #else #include <sys/mman.h> #include <sys/stat.h> #endif #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" namespace perfetto { namespace base { namespace vm_test_utils { bool IsMapped(void* start, size_t size) { PERFETTO_CHECK(size % kPageSize == 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) int retries = 5; int number_of_entries = 4000; // Just a guess. PSAPI_WORKING_SET_INFORMATION* ws_info = nullptr; std::vector<char> buffer; for (;;) { size_t buffer_size = sizeof(PSAPI_WORKING_SET_INFORMATION) + (number_of_entries * sizeof(PSAPI_WORKING_SET_BLOCK)); buffer.resize(buffer_size); ws_info = reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(&buffer[0]); // On success, |buffer_| is populated with info about the working set of // |process|. On ERROR_BAD_LENGTH failure, increase the size of the // buffer and try again. if (QueryWorkingSet(GetCurrentProcess(), &buffer[0], buffer_size)) break; // Success PERFETTO_CHECK(GetLastError() == ERROR_BAD_LENGTH); number_of_entries = ws_info->NumberOfEntries; // Maybe some entries are being added right now. Increase the buffer to // take that into account. Increasing by 10% should generally be enough. number_of_entries *= 1.1; PERFETTO_CHECK(--retries > 0); // If we're looping, eventually fail. } void* end = reinterpret_cast<char*>(start) + size; // Now scan the working-set information looking for the addresses. unsigned pages_found = 0; for (unsigned i = 0; i < ws_info->NumberOfEntries; ++i) { void* address = reinterpret_cast<void*>(ws_info->WorkingSetInfo[i].VirtualPage * kPageSize); if (address >= start && address < end) ++pages_found; } if (pages_found * kPageSize == size) return true; return false; #elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Fuchsia doesn't yet support paging (b/119503290). return true; #else #if PERFETTO_BUILDFLAG(PERFETTO_OS_MACOSX) using PageState = char; static constexpr PageState kIncoreMask = MINCORE_INCORE; #else using PageState = unsigned char; static constexpr PageState kIncoreMask = 1; #endif const size_t num_pages = size / kPageSize; std::unique_ptr<PageState[]> page_states(new PageState[num_pages]); memset(page_states.get(), 0, num_pages * sizeof(PageState)); int res = mincore(start, size, page_states.get()); // Linux returns ENOMEM when an unmapped memory range is passed. // MacOS instead returns 0 but leaves the page_states empty. if (res == -1 && errno == ENOMEM) return false; PERFETTO_CHECK(res == 0); for (size_t i = 0; i < num_pages; i++) { if (!(page_states[i] & kIncoreMask)) return false; } return true; #endif } } // namespace vm_test_utils } // namespace base } // namespace perfetto <commit_msg>base: Fix windows build am: 65c898e6e2 am: 58ee913c1b am: 1ad8925c7b am: 4f441f1176<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * 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/base/test/vm_test_utils.h" #include "perfetto/base/build_config.h" #include "perfetto/ext/base/utils.h" #include <memory> #include <errno.h> #include <string.h> #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <vector> #include <Windows.h> #include <Psapi.h> #else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include <sys/mman.h> #include <sys/stat.h> #endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) #include "perfetto/base/build_config.h" #include "perfetto/base/logging.h" namespace perfetto { namespace base { namespace vm_test_utils { bool IsMapped(void* start, size_t size) { PERFETTO_CHECK(size % kPageSize == 0); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) int retries = 5; int number_of_entries = 4000; // Just a guess. PSAPI_WORKING_SET_INFORMATION* ws_info = nullptr; std::vector<char> buffer; for (;;) { size_t buffer_size = sizeof(PSAPI_WORKING_SET_INFORMATION) + (number_of_entries * sizeof(PSAPI_WORKING_SET_BLOCK)); buffer.resize(buffer_size); ws_info = reinterpret_cast<PSAPI_WORKING_SET_INFORMATION*>(&buffer[0]); // On success, |buffer_| is populated with info about the working set of // |process|. On ERROR_BAD_LENGTH failure, increase the size of the // buffer and try again. if (QueryWorkingSet(GetCurrentProcess(), &buffer[0], buffer_size)) break; // Success PERFETTO_CHECK(GetLastError() == ERROR_BAD_LENGTH); number_of_entries = ws_info->NumberOfEntries; // Maybe some entries are being added right now. Increase the buffer to // take that into account. Increasing by 10% should generally be enough. number_of_entries *= 1.1; PERFETTO_CHECK(--retries > 0); // If we're looping, eventually fail. } void* end = reinterpret_cast<char*>(start) + size; // Now scan the working-set information looking for the addresses. unsigned pages_found = 0; for (unsigned i = 0; i < ws_info->NumberOfEntries; ++i) { void* address = reinterpret_cast<void*>(ws_info->WorkingSetInfo[i].VirtualPage * kPageSize); if (address >= start && address < end) ++pages_found; } if (pages_found * kPageSize == size) return true; return false; #elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Fuchsia doesn't yet support paging (b/119503290). return true; #else #if PERFETTO_BUILDFLAG(PERFETTO_OS_MACOSX) using PageState = char; static constexpr PageState kIncoreMask = MINCORE_INCORE; #else using PageState = unsigned char; static constexpr PageState kIncoreMask = 1; #endif const size_t num_pages = size / kPageSize; std::unique_ptr<PageState[]> page_states(new PageState[num_pages]); memset(page_states.get(), 0, num_pages * sizeof(PageState)); int res = mincore(start, size, page_states.get()); // Linux returns ENOMEM when an unmapped memory range is passed. // MacOS instead returns 0 but leaves the page_states empty. if (res == -1 && errno == ENOMEM) return false; PERFETTO_CHECK(res == 0); for (size_t i = 0; i < num_pages; i++) { if (!(page_states[i] & kIncoreMask)) return false; } return true; #endif } } // namespace vm_test_utils } // namespace base } // namespace perfetto <|endoftext|>
<commit_before>/* * File: ScanLineEdgelDetector.cpp * Author: claas * Author: Heinrich Mellmann * * Created on 14. march 2011, 14:22 */ #include "ScanLineEdgelDetector.h" // debug #include "Tools/Debug/DebugModify.h" #include "Tools/Debug/DebugRequest.h" #include "Tools/Debug/DebugImageDrawings.h" #include "Tools/Debug/DebugDrawings.h" #include "Tools/Debug/Stopwatch.h" // tools #include "Tools/ImageProcessing/BresenhamLineScan.h" #include "Tools/CameraGeometry.h" ScanLineEdgelDetector::ScanLineEdgelDetector() : cameraID(CameraInfo::Top) { DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:scanlines", "mark the scan lines", false); DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_edgels", "mark the edgels on the image", false); DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels", "mark the edgels on the image", false); DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints", "mark the endpints on the image", false); } ScanLineEdgelDetector::~ScanLineEdgelDetector() {} void ScanLineEdgelDetector::execute(CameraInfo::CameraID id) { cameraID = id; CANVAS_PX(cameraID); getScanLineEdgelPercept().reset(); // TODO: implement a general validation for timestamps if(getBodyContour().timestamp != getFrameInfo().getTime()) { return; } int horizon_height = (int)(std::min(getArtificialHorizon().begin().y, getArtificialHorizon().end().y)+0.5); // clamp it to the image horizon_height = Math::clamp(horizon_height,0,(int)getImage().height()); // scan only inside the estimated field region //horizon_height = getFieldPerceptRaw().getValidField().points[0].y; // horizontal stepsize between the scanlines int step = (getImage().width() - 1) / (theParameters.scanline_count - 1); // don't scan the lower lines in the image int borderY = getImage().height() - theParameters.pixel_border_y - 1; // start and endpoints for the scanlines Vector2i start(step / 2, borderY); Vector2i end(step / 2, horizon_height ); for (int i = 0; i < theParameters.scanline_count - 1; i++) { ASSERT(getImage().isInside(start.x, start.y)); // don't scan the own body start = getBodyContour().getFirstFreeCell(start); // execute the scan ScanLineEdgelPercept::EndPoint endPoint = scanForEdgels(i, start, end); // check if endpoint is not same as the begin of the scanline if(endPoint.posInImage == start) { endPoint.color = ColorClasses::none; endPoint.posInImage.y = borderY; } // try to project it on the ground endPoint.valid = CameraGeometry::imagePixelToFieldCoord( getCameraMatrix(), getCameraInfo(), endPoint.posInImage.x, endPoint.posInImage.y, 0.0, endPoint.posOnField); // getScanLineEdgelPercept().endPoints.push_back(endPoint); start.y = borderY; start.x += step; end.x = start.x; }//end for DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_edgels", for(size_t i = 0; i < getScanLineEdgelPercept().edgels.size(); i++) { const Edgel& edgel = getScanLineEdgelPercept().edgels[i]; LINE_PX(ColorClasses::black,edgel.point.x, edgel.point.y, edgel.point.x + (int)(edgel.direction.x*10), edgel.point.y + (int)(edgel.direction.y*10)); } ); // mark finished valid edgels DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels", for(size_t i = 0; i < getScanLineEdgelPercept().pairs.size(); i++) { const ScanLineEdgelPercept::EdgelPair& pair = getScanLineEdgelPercept().pairs[i]; CIRCLE_PX(ColorClasses::black, (int)pair.point.x, (int)pair.point.y, 3); LINE_PX(ColorClasses::red ,(int)pair.point.x, (int)pair.point.y, (int)(pair.point.x + pair.direction.x*10), (int)(pair.point.y + pair.direction.y*10)); } ); DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints", for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++) { const ScanLineEdgelPercept::EndPoint& point_two = getScanLineEdgelPercept().endPoints[i]; CIRCLE_PX(point_two.color, point_two.posInImage.x, point_two.posInImage.y, 5); if(i > 0) { const ScanLineEdgelPercept::EndPoint& point_one = getScanLineEdgelPercept().endPoints[i-1]; LINE_PX(point_one.color, point_one.posInImage.x, point_one.posInImage.y, point_two.posInImage.x, point_two.posInImage.y); } } ); }//end execute ScanLineEdgelPercept::EndPoint ScanLineEdgelDetector::scanForEdgels(int scan_id, const Vector2i& start, const Vector2i& end) { ScanLineEdgelPercept::EndPoint endPoint; endPoint.posInImage = start; endPoint.color = ColorClasses::none; endPoint.ScanLineID = scan_id; const int step = 2; // no scan if the start is at the top of the image if(start.y <= step) { return endPoint; } Vector2i point(start); point.y -= step; // make one step Vector2i last_down_point(point); // needed for the endpoint bool begin_found = false; // calculate the threashold int t_edge = theParameters.brightness_threshold * 2; // HACK (TEST): make it dependend on the angle of the camera in the future if(cameraID == CameraInfo::Bottom) { t_edge *= 4; } // initialize the scanner Vector2i peak_point_max(point); Vector2i peak_point_min(point); MaximumScan<int,int> positiveScan(peak_point_max.y, t_edge); MaximumScan<int,int> negativeScan(peak_point_min.y, t_edge); int f_last = getImage().getY(point.x, point.y); // scan the first point // just go up for(;point.y >= end.y + step; point.y -= step) { // get the brightness chanel int f_y = getImage().getY(point.x, point.y); int g = f_y - f_last; f_last = f_y; // begin found if(positiveScan.addValue(point.y+1, g)) { // refine the position of the peak int f_2 = getImage().getY(point.x, peak_point_max.y-2); int f0 = getImage().getY(point.x, peak_point_max.y); int f2 = getImage().getY(point.x, peak_point_max.y+2); if(f_2-f0 > positiveScan.maxValue()) peak_point_max.y -= 1; if(f0 -f2 > positiveScan.maxValue()) peak_point_max.y += 1; if(estimateColorOfSegment(last_down_point, peak_point_max) == ColorClasses::green) { endPoint.color = ColorClasses::green; endPoint.posInImage = peak_point_max; } add_edgel(peak_point_max); begin_found = true; last_down_point.y = peak_point_max.y; }//end if // end found if(negativeScan.addValue(point.y+1, -g)) { // refine the position of the peak int f_2 = getImage().getY(point.x, peak_point_min.y-2); int f0 = getImage().getY(point.x, peak_point_min.y); int f2 = getImage().getY(point.x, peak_point_min.y+2); if(f_2-f0 < negativeScan.maxValue()) peak_point_min.y -= 1; if(f0 -f2 < negativeScan.maxValue()) peak_point_min.y += 1; if(estimateColorOfSegment(last_down_point, peak_point_min) == ColorClasses::green) { endPoint.color = ColorClasses::green; endPoint.posInImage = peak_point_min; } // new end edgel // found a new double edgel if(begin_found) { add_double_edgel(peak_point_min, scan_id); begin_found = false; } else { add_edgel(peak_point_min); } last_down_point.y = peak_point_min.y; }//end if DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:scanlines", Pixel pixel = getImage().get(point.x, point.y); ColorClasses::Color thisPixelColor = (getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c))?ColorClasses::green:ColorClasses::none; POINT_PX(thisPixelColor, point.x, point.y); ); }//end for if(point.y < end.y + step) { if(estimateColorOfSegment(last_down_point, end) == ColorClasses::green) { endPoint.color = ColorClasses::green; endPoint.posInImage = end; } } return endPoint; }//end scanForEdgels ColorClasses::Color ScanLineEdgelDetector::estimateColorOfSegment(const Vector2i& begin, const Vector2i& end) const { ASSERT(begin.x == end.x && end.y <= begin.y); const int numberOfSamples = theParameters.green_sampling_points; int length = begin.y - end.y; int numberOfGreen = 0; Vector2i point(begin); Pixel pixel; if(numberOfSamples >= length) { for(; point.y > end.y; point.y--) { getImage().get(point.x, point.y, pixel); numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c); } } else { int step = length / numberOfSamples; int offset = Math::random(length); // number in [0,length-1] for(int i = 0; i < numberOfSamples; i++) { int k = (offset + i*step) % length; point.y = end.y + k; getImage().get(point.x, point.y, pixel); numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c); } } return (numberOfGreen > numberOfSamples/2) ? ColorClasses::green : ColorClasses::none; }//end estimateColorOfSegment Vector2d ScanLineEdgelDetector::calculateGradient(const Vector2i& point) const { Vector2d gradient; // no angle at the border (shouldn't happen) if( point.x < 1 || point.x + 2 > (int)getImage().width() || point.y < 1 || point.y + 2 > (int)getImage().height() ) { return gradient; } //apply Sobel Operator on (pointX, pointY) //and calculate gradient in x and y direction by that means gradient.x = getImage().getY(point.x-1, point.y+1) +2*getImage().getY(point.x , point.y+1) + getImage().getY(point.x+1, point.y+1) - getImage().getY(point.x-1, point.y-1) -2*getImage().getY(point.x , point.y-1) - getImage().getY(point.x+1, point.y-1); gradient.y = getImage().getY(point.x-1, point.y-1) +2*getImage().getY(point.x-1, point.y ) + getImage().getY(point.x-1, point.y+1) - getImage().getY(point.x+1, point.y-1) -2*getImage().getY(point.x+1, point.y ) - getImage().getY(point.x+1, point.y+1); //calculate the angle of the gradient return gradient.normalize(); }//end calculateGradient <commit_msg>bugfix: check if start and end point are valid<commit_after>/* * File: ScanLineEdgelDetector.cpp * Author: claas * Author: Heinrich Mellmann * * Created on 14. march 2011, 14:22 */ #include "ScanLineEdgelDetector.h" // debug #include "Tools/Debug/DebugModify.h" #include "Tools/Debug/DebugRequest.h" #include "Tools/Debug/DebugImageDrawings.h" #include "Tools/Debug/DebugDrawings.h" #include "Tools/Debug/Stopwatch.h" // tools #include "Tools/ImageProcessing/BresenhamLineScan.h" #include "Tools/CameraGeometry.h" ScanLineEdgelDetector::ScanLineEdgelDetector() : cameraID(CameraInfo::Top) { DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:scanlines", "mark the scan lines", false); DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_edgels", "mark the edgels on the image", false); DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels", "mark the edgels on the image", false); DEBUG_REQUEST_REGISTER("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints", "mark the endpints on the image", false); } ScanLineEdgelDetector::~ScanLineEdgelDetector() {} void ScanLineEdgelDetector::execute(CameraInfo::CameraID id) { cameraID = id; CANVAS_PX(cameraID); getScanLineEdgelPercept().reset(); // TODO: implement a general validation for timestamps if(getBodyContour().timestamp != getFrameInfo().getTime()) { return; } int horizon_height = (int)(std::min(getArtificialHorizon().begin().y, getArtificialHorizon().end().y)+0.5); // clamp it to the image horizon_height = Math::clamp(horizon_height,0,(int)getImage().height()); // scan only inside the estimated field region //horizon_height = getFieldPerceptRaw().getValidField().points[0].y; // horizontal stepsize between the scanlines int step = (getImage().width() - 1) / (theParameters.scanline_count - 1); // don't scan the lower lines in the image int borderY = getImage().height() - theParameters.pixel_border_y - 1; // start and endpoints for the scanlines Vector2i start(step / 2, borderY); Vector2i end(step / 2, horizon_height ); for (int i = 0; i < theParameters.scanline_count - 1; i++) { ASSERT(getImage().isInside(start.x, start.y)); // don't scan the own body start = getBodyContour().getFirstFreeCell(start); // execute the scan ScanLineEdgelPercept::EndPoint endPoint = scanForEdgels(i, start, end); // check if endpoint is not same as the begin of the scanline if(endPoint.posInImage == start) { endPoint.color = ColorClasses::none; endPoint.posInImage.y = borderY; } // try to project it on the ground endPoint.valid = CameraGeometry::imagePixelToFieldCoord( getCameraMatrix(), getCameraInfo(), endPoint.posInImage.x, endPoint.posInImage.y, 0.0, endPoint.posOnField); // getScanLineEdgelPercept().endPoints.push_back(endPoint); start.y = borderY; start.x += step; end.x = start.x; }//end for DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_edgels", for(size_t i = 0; i < getScanLineEdgelPercept().edgels.size(); i++) { const Edgel& edgel = getScanLineEdgelPercept().edgels[i]; LINE_PX(ColorClasses::black,edgel.point.x, edgel.point.y, edgel.point.x + (int)(edgel.direction.x*10), edgel.point.y + (int)(edgel.direction.y*10)); } ); // mark finished valid edgels DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_double_edgels", for(size_t i = 0; i < getScanLineEdgelPercept().pairs.size(); i++) { const ScanLineEdgelPercept::EdgelPair& pair = getScanLineEdgelPercept().pairs[i]; CIRCLE_PX(ColorClasses::black, (int)pair.point.x, (int)pair.point.y, 3); LINE_PX(ColorClasses::red ,(int)pair.point.x, (int)pair.point.y, (int)(pair.point.x + pair.direction.x*10), (int)(pair.point.y + pair.direction.y*10)); } ); DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:mark_endpoints", for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++) { const ScanLineEdgelPercept::EndPoint& point_two = getScanLineEdgelPercept().endPoints[i]; CIRCLE_PX(point_two.color, point_two.posInImage.x, point_two.posInImage.y, 5); if(i > 0) { const ScanLineEdgelPercept::EndPoint& point_one = getScanLineEdgelPercept().endPoints[i-1]; LINE_PX(point_one.color, point_one.posInImage.x, point_one.posInImage.y, point_two.posInImage.x, point_two.posInImage.y); } } ); }//end execute ScanLineEdgelPercept::EndPoint ScanLineEdgelDetector::scanForEdgels(int scan_id, const Vector2i& start, const Vector2i& end) { ScanLineEdgelPercept::EndPoint endPoint; endPoint.posInImage = start; endPoint.color = ColorClasses::none; endPoint.ScanLineID = scan_id; const int step = 2; if(end.y + step > start.y || end.y + step >= (int)getImage().height()) { endPoint.posInImage.y = end.y; return endPoint; } // no scan if the start is at the top of the image if(start.y <= step) { return endPoint; } Vector2i point(start); point.y -= step; // make one step Vector2i last_down_point(point); // needed for the endpoint bool begin_found = false; // calculate the threashold int t_edge = theParameters.brightness_threshold * 2; // HACK (TEST): make it dependend on the angle of the camera in the future if(cameraID == CameraInfo::Bottom) { t_edge *= 4; } // initialize the scanner Vector2i peak_point_max(point); Vector2i peak_point_min(point); MaximumScan<int,int> positiveScan(peak_point_max.y, t_edge); MaximumScan<int,int> negativeScan(peak_point_min.y, t_edge); int f_last = getImage().getY(point.x, point.y); // scan the first point // just go up for(;point.y >= end.y + step; point.y -= step) { // get the brightness chanel int f_y = getImage().getY(point.x, point.y); int g = f_y - f_last; f_last = f_y; // begin found if(positiveScan.addValue(point.y+1, g)) { // refine the position of the peak int f_2 = getImage().getY(point.x, peak_point_max.y-2); int f0 = getImage().getY(point.x, peak_point_max.y); int f2 = getImage().getY(point.x, peak_point_max.y+2); if(f_2-f0 > positiveScan.maxValue()) peak_point_max.y -= 1; if(f0 -f2 > positiveScan.maxValue()) peak_point_max.y += 1; if(estimateColorOfSegment(last_down_point, peak_point_max) == ColorClasses::green) { endPoint.color = ColorClasses::green; endPoint.posInImage = peak_point_max; } add_edgel(peak_point_max); begin_found = true; last_down_point.y = peak_point_max.y; }//end if // end found if(negativeScan.addValue(point.y+1, -g)) { // refine the position of the peak int f_2 = getImage().getY(point.x, peak_point_min.y-2); int f0 = getImage().getY(point.x, peak_point_min.y); int f2 = getImage().getY(point.x, peak_point_min.y+2); if(f_2-f0 < negativeScan.maxValue()) peak_point_min.y -= 1; if(f0 -f2 < negativeScan.maxValue()) peak_point_min.y += 1; if(estimateColorOfSegment(last_down_point, peak_point_min) == ColorClasses::green) { endPoint.color = ColorClasses::green; endPoint.posInImage = peak_point_min; } // new end edgel // found a new double edgel if(begin_found) { add_double_edgel(peak_point_min, scan_id); begin_found = false; } else { add_edgel(peak_point_min); } last_down_point.y = peak_point_min.y; }//end if DEBUG_REQUEST("Vision:Detectors:ScanLineEdgelDetector:scanlines", Pixel pixel = getImage().get(point.x, point.y); ColorClasses::Color thisPixelColor = (getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c))?ColorClasses::green:ColorClasses::none; POINT_PX(thisPixelColor, point.x, point.y); ); }//end for if(point.y < end.y + step) { if(estimateColorOfSegment(last_down_point, end) == ColorClasses::green) { endPoint.color = ColorClasses::green; endPoint.posInImage = end; } } return endPoint; }//end scanForEdgels ColorClasses::Color ScanLineEdgelDetector::estimateColorOfSegment(const Vector2i& begin, const Vector2i& end) const { ASSERT(begin.x == end.x && end.y <= begin.y); const int numberOfSamples = theParameters.green_sampling_points; int length = begin.y - end.y; int numberOfGreen = 0; Vector2i point(begin); Pixel pixel; if(numberOfSamples >= length) { for(; point.y > end.y; point.y--) { getImage().get(point.x, point.y, pixel); numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c); } } else { int step = length / numberOfSamples; int offset = Math::random(length); // number in [0,length-1] for(int i = 0; i < numberOfSamples; i++) { int k = (offset + i*step) % length; point.y = end.y + k; getImage().get(point.x, point.y, pixel); numberOfGreen += getFieldColorPercept().isFieldColor(pixel.a, pixel.b, pixel.c); } } return (numberOfGreen > numberOfSamples/2) ? ColorClasses::green : ColorClasses::none; }//end estimateColorOfSegment Vector2d ScanLineEdgelDetector::calculateGradient(const Vector2i& point) const { Vector2d gradient; // no angle at the border (shouldn't happen) if( point.x < 1 || point.x + 2 > (int)getImage().width() || point.y < 1 || point.y + 2 > (int)getImage().height() ) { return gradient; } //apply Sobel Operator on (pointX, pointY) //and calculate gradient in x and y direction by that means gradient.x = getImage().getY(point.x-1, point.y+1) +2*getImage().getY(point.x , point.y+1) + getImage().getY(point.x+1, point.y+1) - getImage().getY(point.x-1, point.y-1) -2*getImage().getY(point.x , point.y-1) - getImage().getY(point.x+1, point.y-1); gradient.y = getImage().getY(point.x-1, point.y-1) +2*getImage().getY(point.x-1, point.y ) + getImage().getY(point.x-1, point.y+1) - getImage().getY(point.x+1, point.y-1) -2*getImage().getY(point.x+1, point.y ) - getImage().getY(point.x+1, point.y+1); //calculate the angle of the gradient return gradient.normalize(); }//end calculateGradient <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. //M*/ #include "test_precomp.hpp" TEST(SoftCascade, readCascade) { std::string xml = cvtest::TS::ptr()->get_data_path() + "cascadeandhog/icf-template.xml"; cv::SoftCascade cascade; cv::FileStorage fs(xml, cv::FileStorage::READ); ASSERT_TRUE(cascade.read(fs)); } TEST(SoftCascade, detect) { typedef cv::SoftCascade::Detection detection_t; std::string xml = cvtest::TS::ptr()->get_data_path() + "cascadeandhog/sc_cvpr_2012_to_opencv.xml"; cv::SoftCascade cascade; cv::FileStorage fs(xml, cv::FileStorage::READ); ASSERT_TRUE(cascade.read(fs)); cv::Mat colored = cv::imread(cvtest::TS::ptr()->get_data_path() + "cascadeandhog/bahnhof/image_00000000_0.png"); ASSERT_FALSE(colored.empty()); std::vector<detection_t> objects; std::vector<cv::Rect> rois; rois.push_back(cv::Rect(0, 0, 640, 480)); cascade.detectMultiScale(colored, rois, objects); cv::Mat out = colored.clone(); int level = 0, total = 0; int levelWidth = objects[0].rect.width; for(int i = 0 ; i < (int)objects.size(); ++i) { if (objects[i].rect.width != levelWidth) { std::cout << "Level: " << level << " total " << total << std::endl; cv::imshow("out", out); cv::waitKey(0); out = colored.clone(); levelWidth = objects[i].rect.width; total = 0; level++; } cv::rectangle(out, objects[i].rect, cv::Scalar(255, 0, 0, 255), 1); std::cout << "detection: " << objects[i].rect.x << " " << objects[i].rect.y << " " << objects[i].rect.width << " " << objects[i].rect.height << std::endl; total++; } std::cout << "detected: " << (int)objects.size() << std::endl; ASSERT_EQ((int)objects.size(), 1501); }<commit_msg>test update because changed Sobel Normalization<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. //M*/ #include "test_precomp.hpp" TEST(SoftCascade, readCascade) { std::string xml = cvtest::TS::ptr()->get_data_path() + "cascadeandhog/icf-template.xml"; cv::SoftCascade cascade; cv::FileStorage fs(xml, cv::FileStorage::READ); ASSERT_TRUE(cascade.read(fs)); } TEST(SoftCascade, detect) { typedef cv::SoftCascade::Detection detection_t; std::string xml = cvtest::TS::ptr()->get_data_path() + "cascadeandhog/sc_cvpr_2012_to_opencv.xml"; cv::SoftCascade cascade; cv::FileStorage fs(xml, cv::FileStorage::READ); ASSERT_TRUE(cascade.read(fs)); cv::Mat colored = cv::imread(cvtest::TS::ptr()->get_data_path() + "cascadeandhog/bahnhof/image_00000000_0.png"); ASSERT_FALSE(colored.empty()); std::vector<detection_t> objects; std::vector<cv::Rect> rois; rois.push_back(cv::Rect(0, 0, 640, 480)); cascade.detectMultiScale(colored, rois, objects); cv::Mat out = colored.clone(); int level = 0, total = 0; int levelWidth = objects[0].rect.width; for(int i = 0 ; i < (int)objects.size(); ++i) { if (objects[i].rect.width != levelWidth) { std::cout << "Level: " << level << " total " << total << std::endl; cv::imshow("out", out); cv::waitKey(0); out = colored.clone(); levelWidth = objects[i].rect.width; total = 0; level++; } cv::rectangle(out, objects[i].rect, cv::Scalar(255, 0, 0, 255), 1); std::cout << "detection: " << objects[i].rect.x << " " << objects[i].rect.y << " " << objects[i].rect.width << " " << objects[i].rect.height << std::endl; total++; } std::cout << "detected: " << (int)objects.size() << std::endl; ASSERT_EQ((int)objects.size(), 1469); }<|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * 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 <cmath> #include <memory> #include <string> #include <unordered_set> #include <vector> #include <iomanip> #include "modules/common/math/linear_interpolation.h" #include "modules/common/math/vec2d.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/proto/map_id.pb.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" namespace apollo { namespace prediction { using apollo::hdmap::LaneInfo; using apollo::hdmap::Id; using apollo::hdmap::MapPathPoint; PredictionMap::PredictionMap() : hdmap_(nullptr) { LoadMap(); } PredictionMap::~PredictionMap() { Clear(); } void PredictionMap::LoadMap() { hdmap_.reset(new apollo::hdmap::HDMap()); CHECK(hdmap_ != nullptr); hdmap_->load_map_from_file(FLAGS_map_file); AINFO << "Succeeded in loading map file: " << FLAGS_map_file << "."; } void PredictionMap::Clear() { hdmap_.reset(); } Id PredictionMap::id(const std::string& str_id) { Id id; id.set_id(str_id); return id; } Eigen::Vector2d PredictionMap::PositionOnLane( std::shared_ptr<const LaneInfo> lane_info, const double s) { apollo::common::PointENU point = lane_info->get_smooth_point(s); return {point.x(), point.y()}; } double PredictionMap::HeadingOnLane(std::shared_ptr<const LaneInfo> lane_info, const double s) { const std::vector<double>& headings = lane_info->headings(); const std::vector<double>& accumulated_s = lane_info->accumulate_s(); CHECK(headings.size() == accumulated_s.size()); size_t size = headings.size(); if (size == 0) { return 0.0; } if (size == 1) { return headings[0]; } const auto low_itr = std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s); CHECK(low_itr != accumulated_s.end()); size_t index = low_itr - accumulated_s.begin(); if (index == size - 1) { return headings.back(); } return apollo::common::math::slerp(headings[index], accumulated_s[index], headings[index + 1], accumulated_s[index + 1], s); } double PredictionMap::LaneTotalWidth( std::shared_ptr<const apollo::hdmap::LaneInfo> lane_info_ptr, const double s) { double left = 0.0; double right = 0.0; lane_info_ptr->get_width(s, &left, &right); return left + right; } std::shared_ptr<const LaneInfo> PredictionMap::LaneById(const Id& id) { return hdmap_->get_lane_by_id(id); } std::shared_ptr<const LaneInfo> PredictionMap::LaneById( const std::string& str_id) { Id id; id.set_id(str_id); return LaneById(id); } void PredictionMap::GetProjection(const Eigen::Vector2d& position, std::shared_ptr<const LaneInfo> lane_info_ptr, double* s, double* l) { if (lane_info_ptr == nullptr) { return; } apollo::common::math::Vec2d pos(position[0], position[1]); lane_info_ptr->get_projection(pos, s, l); } bool PredictionMap::ProjectionFromLane( std::shared_ptr<const LaneInfo> lane_info_ptr, double s, MapPathPoint* path_point) { if (lane_info_ptr == nullptr) { return false; } apollo::common::PointENU point = lane_info_ptr->get_smooth_point(s); double heading = HeadingOnLane(lane_info_ptr, s); path_point->set_x(point.x()); path_point->set_y(point.y()); path_point->set_heading(heading); return true; } void PredictionMap::OnLane( const std::vector<std::shared_ptr<const LaneInfo>>& prev_lanes, const Eigen::Vector2d& point, const double heading, const double radius, std::vector<std::shared_ptr<const LaneInfo>>* lanes) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; // TODO(kechxu) clean the messy code of this function apollo::common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); apollo::common::math::Vec2d vec_point; vec_point.set_x(point[0]); vec_point.set_y(point[1]); if (hdmap_->get_lanes_with_heading(hdmap_point, radius, heading, M_PI, &candidate_lanes) != 0) { return; } for (auto candidate_lane : candidate_lanes) { if (candidate_lane == nullptr) { continue; } else if (!candidate_lane->is_on_lane(vec_point)) { continue; } else if (!IsIdenticalLane(candidate_lane, prev_lanes) && !IsSuccessorLane(candidate_lane, prev_lanes) && !IsLeftNeighborLane(candidate_lane, prev_lanes) && !IsRightNeighborLane(candidate_lane, prev_lanes)) { continue; } else { double distance = 0.0; apollo::common::PointENU nearest_point = candidate_lane->get_nearest_point(vec_point, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); AINFO << "heading = " << heading; AINFO << "nearest point heading = " << nearest_point_heading; double diff = std::fabs( apollo::common::math::AngleDiff(heading, nearest_point_heading)); AINFO << "angle diff = " << diff; if (diff <= FLAGS_max_lane_angle_diff) { lanes->push_back(candidate_lane); } } } } double PredictionMap::PathHeading(std::shared_ptr<const LaneInfo> lane_info_ptr, const apollo::common::PointENU& point) { apollo::common::math::Vec2d vec_point; vec_point.set_x(point.x()); vec_point.set_y(point.y()); double s = -1.0; double l = 0.0; lane_info_ptr->get_projection(vec_point, &s, &l); return HeadingOnLane(lane_info_ptr, s); } int PredictionMap::SmoothPointFromLane(const apollo::hdmap::Id& id, const double s, const double l, Eigen::Vector2d* point, double* heading) { // TODO(kechxu) Double check this implement if (point == nullptr || heading == nullptr) { return -1; } std::shared_ptr<const LaneInfo> lane = LaneById(id); apollo::common::PointENU hdmap_point = lane->get_smooth_point(s); *heading = PathHeading(lane, hdmap_point); AINFO << "lane_s = [" << std::fixed << std::setprecision(6) << s << "], " << "hdmap pt = [" << std::fixed << std::setprecision(6) << hdmap_point.x() << ", " << hdmap_point.y() << "]"; point->operator[](0) = hdmap_point.x() - std::sin(*heading) * l; point->operator[](1) = hdmap_point.y() + std::cos(*heading) * l; return 0; } void PredictionMap::NearbyLanesByCurrentLanes( const Eigen::Vector2d& point, const std::vector<std::shared_ptr<const LaneInfo>>& lanes, std::vector<std::shared_ptr<const LaneInfo>>* nearby_lanes) { std::unordered_set<std::string> lane_ids; for (auto& lane_ptr : lanes) { if (lane_ptr == nullptr) { continue; } for (auto& lane_id : lane_ptr->lane().left_neighbor_forward_lane_id()) { if (lane_ids.find(lane_id.id()) != lane_ids.end()) { continue; } lane_ids.insert(lane_id.id()); std::shared_ptr<const LaneInfo> nearby_lane = LaneById(lane_id); nearby_lanes->push_back(nearby_lane); } for (auto& lane_id : lane_ptr->lane().right_neighbor_forward_lane_id()) { if (lane_ids.find(lane_id.id()) != lane_ids.end()) { continue; } lane_ids.insert(lane_id.id()); std::shared_ptr<const LaneInfo> nearby_lane = LaneById(lane_id); nearby_lanes->push_back(nearby_lane); } } } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (left_lane == nullptr) { return false; } for (auto& left_lane_id : curr_lane->lane().left_neighbor_forward_lane_id()) { if (id_string(left_lane) == left_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsLeftNeighborLane(left_lane, lane)) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (right_lane == nullptr) { return false; } for (auto& right_lane_id : curr_lane->lane().right_neighbor_forward_lane_id()) { if (id_string(right_lane) == right_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsRightNeighborLane(right_lane, lane)) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (succ_lane == nullptr) { return false; } for (auto& successor_lane_id : curr_lane->lane().successor_id()) { if (id_string(succ_lane) == successor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsSuccessorLane(succ_lane, lane)) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (pred_lane == nullptr) { return false; } for (auto& predecessor_lane_id : curr_lane->lane().predecessor_id()) { if (id_string(pred_lane) == predecessor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsPredecessorLane(pred_lane, lane)) { return true; } } return false; } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr || other_lane == nullptr) { return false; } return id_string(other_lane) == id_string(curr_lane); } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsIdenticalLane(other_lane, lane)) { return true; } } return false; } int PredictionMap::LaneTurnType(const Id& id) { std::shared_ptr<const LaneInfo> lane = LaneById(id); if (lane != nullptr) { return static_cast<int>(lane->lane().turn()); } return 1; } int PredictionMap::LaneTurnType(const std::string& lane_id) { return LaneTurnType(id(lane_id)); } } // namespace prediction } // namespace apollo <commit_msg>small change on log in prediction module<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * 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 <cmath> #include <memory> #include <string> #include <unordered_set> #include <vector> #include <iomanip> #include "modules/common/math/linear_interpolation.h" #include "modules/common/math/vec2d.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/proto/map_id.pb.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" namespace apollo { namespace prediction { using apollo::hdmap::LaneInfo; using apollo::hdmap::Id; using apollo::hdmap::MapPathPoint; PredictionMap::PredictionMap() : hdmap_(nullptr) { LoadMap(); } PredictionMap::~PredictionMap() { Clear(); } void PredictionMap::LoadMap() { hdmap_.reset(new apollo::hdmap::HDMap()); CHECK(hdmap_ != nullptr); hdmap_->load_map_from_file(FLAGS_map_file); AINFO << "Succeeded in loading map file: " << FLAGS_map_file << "."; } void PredictionMap::Clear() { hdmap_.reset(); } Id PredictionMap::id(const std::string& str_id) { Id id; id.set_id(str_id); return id; } Eigen::Vector2d PredictionMap::PositionOnLane( std::shared_ptr<const LaneInfo> lane_info, const double s) { apollo::common::PointENU point = lane_info->get_smooth_point(s); return {point.x(), point.y()}; } double PredictionMap::HeadingOnLane(std::shared_ptr<const LaneInfo> lane_info, const double s) { const std::vector<double>& headings = lane_info->headings(); const std::vector<double>& accumulated_s = lane_info->accumulate_s(); CHECK(headings.size() == accumulated_s.size()); size_t size = headings.size(); if (size == 0) { return 0.0; } if (size == 1) { return headings[0]; } const auto low_itr = std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s); CHECK(low_itr != accumulated_s.end()); size_t index = low_itr - accumulated_s.begin(); if (index == size - 1) { return headings.back(); } return apollo::common::math::slerp(headings[index], accumulated_s[index], headings[index + 1], accumulated_s[index + 1], s); } double PredictionMap::LaneTotalWidth( std::shared_ptr<const apollo::hdmap::LaneInfo> lane_info_ptr, const double s) { double left = 0.0; double right = 0.0; lane_info_ptr->get_width(s, &left, &right); return left + right; } std::shared_ptr<const LaneInfo> PredictionMap::LaneById(const Id& id) { return hdmap_->get_lane_by_id(id); } std::shared_ptr<const LaneInfo> PredictionMap::LaneById( const std::string& str_id) { Id id; id.set_id(str_id); return LaneById(id); } void PredictionMap::GetProjection(const Eigen::Vector2d& position, std::shared_ptr<const LaneInfo> lane_info_ptr, double* s, double* l) { if (lane_info_ptr == nullptr) { return; } apollo::common::math::Vec2d pos(position[0], position[1]); lane_info_ptr->get_projection(pos, s, l); } bool PredictionMap::ProjectionFromLane( std::shared_ptr<const LaneInfo> lane_info_ptr, double s, MapPathPoint* path_point) { if (lane_info_ptr == nullptr) { return false; } apollo::common::PointENU point = lane_info_ptr->get_smooth_point(s); double heading = HeadingOnLane(lane_info_ptr, s); path_point->set_x(point.x()); path_point->set_y(point.y()); path_point->set_heading(heading); return true; } void PredictionMap::OnLane( const std::vector<std::shared_ptr<const LaneInfo>>& prev_lanes, const Eigen::Vector2d& point, const double heading, const double radius, std::vector<std::shared_ptr<const LaneInfo>>* lanes) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; // TODO(kechxu) clean the messy code of this function apollo::common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); apollo::common::math::Vec2d vec_point; vec_point.set_x(point[0]); vec_point.set_y(point[1]); if (hdmap_->get_lanes_with_heading(hdmap_point, radius, heading, M_PI, &candidate_lanes) != 0) { return; } for (auto candidate_lane : candidate_lanes) { if (candidate_lane == nullptr) { continue; } else if (!candidate_lane->is_on_lane(vec_point)) { continue; } else if (!IsIdenticalLane(candidate_lane, prev_lanes) && !IsSuccessorLane(candidate_lane, prev_lanes) && !IsLeftNeighborLane(candidate_lane, prev_lanes) && !IsRightNeighborLane(candidate_lane, prev_lanes)) { continue; } else { double distance = 0.0; apollo::common::PointENU nearest_point = candidate_lane->get_nearest_point(vec_point, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); double diff = std::fabs( apollo::common::math::AngleDiff(heading, nearest_point_heading)); if (diff <= FLAGS_max_lane_angle_diff) { lanes->push_back(candidate_lane); } } } } double PredictionMap::PathHeading(std::shared_ptr<const LaneInfo> lane_info_ptr, const apollo::common::PointENU& point) { apollo::common::math::Vec2d vec_point; vec_point.set_x(point.x()); vec_point.set_y(point.y()); double s = -1.0; double l = 0.0; lane_info_ptr->get_projection(vec_point, &s, &l); return HeadingOnLane(lane_info_ptr, s); } int PredictionMap::SmoothPointFromLane(const apollo::hdmap::Id& id, const double s, const double l, Eigen::Vector2d* point, double* heading) { // TODO(kechxu) Double check this implement if (point == nullptr || heading == nullptr) { return -1; } std::shared_ptr<const LaneInfo> lane = LaneById(id); apollo::common::PointENU hdmap_point = lane->get_smooth_point(s); *heading = PathHeading(lane, hdmap_point); AINFO << "lane_id = " << id.id() << ", " << "lane_s = [" << std::fixed << std::setprecision(6) << s << "], " << "hdmap pt = [" << std::fixed << std::setprecision(6) << hdmap_point.x() << ", " << hdmap_point.y() << "]"; point->operator[](0) = hdmap_point.x() - std::sin(*heading) * l; point->operator[](1) = hdmap_point.y() + std::cos(*heading) * l; return 0; } void PredictionMap::NearbyLanesByCurrentLanes( const Eigen::Vector2d& point, const std::vector<std::shared_ptr<const LaneInfo>>& lanes, std::vector<std::shared_ptr<const LaneInfo>>* nearby_lanes) { std::unordered_set<std::string> lane_ids; for (auto& lane_ptr : lanes) { if (lane_ptr == nullptr) { continue; } for (auto& lane_id : lane_ptr->lane().left_neighbor_forward_lane_id()) { if (lane_ids.find(lane_id.id()) != lane_ids.end()) { continue; } lane_ids.insert(lane_id.id()); std::shared_ptr<const LaneInfo> nearby_lane = LaneById(lane_id); nearby_lanes->push_back(nearby_lane); } for (auto& lane_id : lane_ptr->lane().right_neighbor_forward_lane_id()) { if (lane_ids.find(lane_id.id()) != lane_ids.end()) { continue; } lane_ids.insert(lane_id.id()); std::shared_ptr<const LaneInfo> nearby_lane = LaneById(lane_id); nearby_lanes->push_back(nearby_lane); } } } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (left_lane == nullptr) { return false; } for (auto& left_lane_id : curr_lane->lane().left_neighbor_forward_lane_id()) { if (id_string(left_lane) == left_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsLeftNeighborLane(left_lane, lane)) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (right_lane == nullptr) { return false; } for (auto& right_lane_id : curr_lane->lane().right_neighbor_forward_lane_id()) { if (id_string(right_lane) == right_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsRightNeighborLane(right_lane, lane)) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (succ_lane == nullptr) { return false; } for (auto& successor_lane_id : curr_lane->lane().successor_id()) { if (id_string(succ_lane) == successor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsSuccessorLane(succ_lane, lane)) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (pred_lane == nullptr) { return false; } for (auto& predecessor_lane_id : curr_lane->lane().predecessor_id()) { if (id_string(pred_lane) == predecessor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsPredecessorLane(pred_lane, lane)) { return true; } } return false; } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr || other_lane == nullptr) { return false; } return id_string(other_lane) == id_string(curr_lane); } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsIdenticalLane(other_lane, lane)) { return true; } } return false; } int PredictionMap::LaneTurnType(const Id& id) { std::shared_ptr<const LaneInfo> lane = LaneById(id); if (lane != nullptr) { return static_cast<int>(lane->lane().turn()); } return 1; } int PredictionMap::LaneTurnType(const std::string& lane_id) { return LaneTurnType(id(lane_id)); } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * 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 "modules/prediction/common/prediction_map.h" #include <cmath> #include <iomanip> #include <memory> #include <string> #include <unordered_set> #include <vector> #include "modules/common/configs/config_gflags.h" #include "modules/common/math/linear_interpolation.h" #include "modules/common/math/vec2d.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/map/proto/map_id.pb.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::hdmap::LaneInfo; using apollo::hdmap::Id; using apollo::hdmap::MapPathPoint; using apollo::hdmap::HDMapUtil; PredictionMap::PredictionMap() {} Eigen::Vector2d PredictionMap::PositionOnLane( std::shared_ptr<const LaneInfo> lane_info, const double s) { apollo::common::PointENU point = lane_info->get_smooth_point(s); return {point.x(), point.y()}; } double PredictionMap::HeadingOnLane(std::shared_ptr<const LaneInfo> lane_info, const double s) { const std::vector<double>& headings = lane_info->headings(); const std::vector<double>& accumulated_s = lane_info->accumulate_s(); CHECK(headings.size() == accumulated_s.size()); size_t size = headings.size(); if (size == 0) { return 0.0; } if (size == 1) { return headings[0]; } const auto low_itr = std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s); // CHECK(low_itr != accumulated_s.end()); size_t index = low_itr - accumulated_s.begin(); if (index >= size - 1) { return headings.back(); } return apollo::common::math::slerp(headings[index], accumulated_s[index], headings[index + 1], accumulated_s[index + 1], s); } double PredictionMap::LaneTotalWidth( std::shared_ptr<const apollo::hdmap::LaneInfo> lane_info, const double s) { double left = 0.0; double right = 0.0; lane_info->get_width(s, &left, &right); return left + right; } std::shared_ptr<const LaneInfo> PredictionMap::LaneById( const std::string& str_id) { return HDMapUtil::instance()->BaseMapRef().get_lane_by_id( apollo::hdmap::MakeMapId(str_id)); } void PredictionMap::GetProjection(const Eigen::Vector2d& position, std::shared_ptr<const LaneInfo> lane_info, double* s, double* l) { if (lane_info == nullptr) { return; } apollo::common::math::Vec2d pos(position[0], position[1]); lane_info->get_projection(pos, s, l); } bool PredictionMap::ProjectionFromLane( std::shared_ptr<const LaneInfo> lane_info, double s, MapPathPoint* path_point) { if (lane_info == nullptr) { return false; } apollo::common::PointENU point = lane_info->get_smooth_point(s); double heading = HeadingOnLane(lane_info, s); path_point->set_x(point.x()); path_point->set_y(point.y()); path_point->set_heading(heading); return true; } void PredictionMap::OnLane( const std::vector<std::shared_ptr<const LaneInfo>>& prev_lanes, const Eigen::Vector2d& point, const double heading, const double radius, const bool on_lane, std::vector<std::shared_ptr<const LaneInfo>>* lanes) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; apollo::common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); if (HDMapUtil::instance()->BaseMapRef().get_lanes_with_heading( hdmap_point, radius, heading, M_PI, &candidate_lanes) != 0) { return; } apollo::common::math::Vec2d vec_point(point[0], point[1]); for (const auto &candidate_lane : candidate_lanes) { if (candidate_lane == nullptr) { continue; } if (on_lane && !candidate_lane->is_on_lane(vec_point)) { continue; } if (!IsIdenticalLane(candidate_lane, prev_lanes) && !IsSuccessorLane(candidate_lane, prev_lanes) && !IsLeftNeighborLane(candidate_lane, prev_lanes) && !IsRightNeighborLane(candidate_lane, prev_lanes)) { continue; } double distance = 0.0; apollo::common::PointENU nearest_point = candidate_lane->get_nearest_point(vec_point, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); double diff = std::fabs( apollo::common::math::AngleDiff(heading, nearest_point_heading)); if (diff <= FLAGS_max_lane_angle_diff) { lanes->push_back(candidate_lane); } } } double PredictionMap::PathHeading(std::shared_ptr<const LaneInfo> lane_info, const apollo::common::PointENU& point) { apollo::common::math::Vec2d vec_point = {point.x(), point.y()}; double s = -1.0; double l = 0.0; lane_info->get_projection(vec_point, &s, &l); return HeadingOnLane(lane_info, s); } int PredictionMap::SmoothPointFromLane(const std::string& id, const double s, const double l, Eigen::Vector2d* point, double* heading) { if (point == nullptr || heading == nullptr) { return -1; } std::shared_ptr<const LaneInfo> lane = LaneById(id); apollo::common::PointENU hdmap_point = lane->get_smooth_point(s); *heading = PathHeading(lane, hdmap_point); point->operator[](0) = hdmap_point.x() - std::sin(*heading) * l; point->operator[](1) = hdmap_point.y() + std::cos(*heading) * l; return 0; } void PredictionMap::NearbyLanesByCurrentLanes( const Eigen::Vector2d& point, double heading, double radius, const std::vector<std::shared_ptr<const LaneInfo>>& lanes, std::vector<std::shared_ptr<const LaneInfo>>* nearby_lanes) { if (lanes.size() == 0) { std::vector<std::shared_ptr<const LaneInfo>> prev_lanes(0); OnLane(prev_lanes, point, heading, radius, false, nearby_lanes); } else { std::unordered_set<std::string> lane_ids; for (auto& lane_ptr : lanes) { if (lane_ptr == nullptr) { continue; } for (auto& lane_id : lane_ptr->lane().left_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (::apollo::common::math::DoubleCompare(s, 0.0) >= 0 && ::apollo::common::math::DoubleCompare(std::fabs(l), radius) > 0) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } for (auto& lane_id : lane_ptr->lane().right_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (::apollo::common::math::DoubleCompare(s, 0.0) >= 0 && ::apollo::common::math::DoubleCompare(std::fabs(l), radius) > 0) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } } } } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (left_lane == nullptr) { return false; } for (auto& left_lane_id : curr_lane->lane().left_neighbor_forward_lane_id()) { if (left_lane->id().id() == left_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsLeftNeighborLane(left_lane, lane)) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (right_lane == nullptr) { return false; } for (auto& right_lane_id : curr_lane->lane().right_neighbor_forward_lane_id()) { if (right_lane->id().id() == right_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsRightNeighborLane(right_lane, lane)) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (succ_lane == nullptr) { return false; } for (auto& successor_lane_id : curr_lane->lane().successor_id()) { if (succ_lane->id().id() == successor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsSuccessorLane(succ_lane, lane)) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (pred_lane == nullptr) { return false; } for (auto& predecessor_lane_id : curr_lane->lane().predecessor_id()) { if (pred_lane->id().id() == predecessor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsPredecessorLane(pred_lane, lane)) { return true; } } return false; } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr || other_lane == nullptr) { return true; } return other_lane->id().id() == curr_lane->id().id(); } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsIdenticalLane(other_lane, lane)) { return true; } } return false; } int PredictionMap::LaneTurnType(const std::string& lane_id) { std::shared_ptr<const LaneInfo> lane = LaneById(lane_id); if (lane != nullptr) { return static_cast<int>(lane->lane().turn()); } return 1; } } // namespace prediction } // namespace apollo <commit_msg>Prediction: reformatting<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * 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 "modules/prediction/common/prediction_map.h" #include <cmath> #include <iomanip> #include <memory> #include <string> #include <unordered_set> #include <vector> #include "modules/common/configs/config_gflags.h" #include "modules/common/math/linear_interpolation.h" #include "modules/common/math/vec2d.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/map/proto/map_id.pb.h" #include "modules/prediction/common/prediction_gflags.h" namespace apollo { namespace prediction { using apollo::hdmap::LaneInfo; using apollo::hdmap::Id; using apollo::hdmap::MapPathPoint; using apollo::hdmap::HDMapUtil; PredictionMap::PredictionMap() {} Eigen::Vector2d PredictionMap::PositionOnLane( std::shared_ptr<const LaneInfo> lane_info, const double s) { apollo::common::PointENU point = lane_info->get_smooth_point(s); return {point.x(), point.y()}; } double PredictionMap::HeadingOnLane( std::shared_ptr<const LaneInfo> lane_info, const double s) { const std::vector<double>& headings = lane_info->headings(); const std::vector<double>& accumulated_s = lane_info->accumulate_s(); CHECK(headings.size() == accumulated_s.size()); size_t size = headings.size(); if (size == 0) { return 0.0; } if (size == 1) { return headings[0]; } const auto low_itr = std::lower_bound(accumulated_s.begin(), accumulated_s.end(), s); size_t index = low_itr - accumulated_s.begin(); if (index >= size - 1) { return headings.back(); } else { return apollo::common::math::slerp(headings[index], accumulated_s[index], headings[index + 1], accumulated_s[index + 1], s); } } double PredictionMap::LaneTotalWidth( std::shared_ptr<const apollo::hdmap::LaneInfo> lane_info, const double s) { double left = 0.0; double right = 0.0; lane_info->get_width(s, &left, &right); return left + right; } std::shared_ptr<const LaneInfo> PredictionMap::LaneById( const std::string& str_id) { return HDMapUtil::instance()->BaseMapRef().get_lane_by_id( apollo::hdmap::MakeMapId(str_id)); } void PredictionMap::GetProjection( const Eigen::Vector2d& position, std::shared_ptr<const LaneInfo> lane_info, double* s, double* l) { if (lane_info == nullptr) { return; } apollo::common::math::Vec2d pos(position[0], position[1]); lane_info->get_projection(pos, s, l); } bool PredictionMap::ProjectionFromLane( std::shared_ptr<const LaneInfo> lane_info, double s, MapPathPoint* path_point) { if (lane_info == nullptr) { return false; } apollo::common::PointENU point = lane_info->get_smooth_point(s); double heading = HeadingOnLane(lane_info, s); path_point->set_x(point.x()); path_point->set_y(point.y()); path_point->set_heading(heading); return true; } void PredictionMap::OnLane( const std::vector<std::shared_ptr<const LaneInfo>>& prev_lanes, const Eigen::Vector2d& point, const double heading, const double radius, const bool on_lane, std::vector<std::shared_ptr<const LaneInfo>>* lanes) { std::vector<std::shared_ptr<const LaneInfo>> candidate_lanes; apollo::common::PointENU hdmap_point; hdmap_point.set_x(point[0]); hdmap_point.set_y(point[1]); if (HDMapUtil::instance()->BaseMapRef().get_lanes_with_heading( hdmap_point, radius, heading, M_PI, &candidate_lanes) != 0) { return; } apollo::common::math::Vec2d vec_point(point[0], point[1]); for (const auto &candidate_lane : candidate_lanes) { if (candidate_lane == nullptr) { continue; } if (on_lane && !candidate_lane->is_on_lane(vec_point)) { continue; } if (!IsIdenticalLane(candidate_lane, prev_lanes) && !IsSuccessorLane(candidate_lane, prev_lanes) && !IsLeftNeighborLane(candidate_lane, prev_lanes) && !IsRightNeighborLane(candidate_lane, prev_lanes)) { continue; } double distance = 0.0; apollo::common::PointENU nearest_point = candidate_lane->get_nearest_point(vec_point, &distance); double nearest_point_heading = PathHeading(candidate_lane, nearest_point); double diff = std::fabs( apollo::common::math::AngleDiff(heading, nearest_point_heading)); if (diff <= FLAGS_max_lane_angle_diff) { lanes->push_back(candidate_lane); } } } double PredictionMap::PathHeading( std::shared_ptr<const LaneInfo> lane_info, const apollo::common::PointENU& point) { apollo::common::math::Vec2d vec_point = {point.x(), point.y()}; double s = -1.0; double l = 0.0; lane_info->get_projection(vec_point, &s, &l); return HeadingOnLane(lane_info, s); } int PredictionMap::SmoothPointFromLane( const std::string& id, const double s, const double l, Eigen::Vector2d* point, double* heading) { if (point == nullptr || heading == nullptr) { return -1; } std::shared_ptr<const LaneInfo> lane = LaneById(id); apollo::common::PointENU hdmap_point = lane->get_smooth_point(s); *heading = PathHeading(lane, hdmap_point); point->operator[](0) = hdmap_point.x() - std::sin(*heading) * l; point->operator[](1) = hdmap_point.y() + std::cos(*heading) * l; return 0; } void PredictionMap::NearbyLanesByCurrentLanes( const Eigen::Vector2d& point, double heading, double radius, const std::vector<std::shared_ptr<const LaneInfo>>& lanes, std::vector<std::shared_ptr<const LaneInfo>>* nearby_lanes) { if (lanes.size() == 0) { std::vector<std::shared_ptr<const LaneInfo>> prev_lanes(0); OnLane(prev_lanes, point, heading, radius, false, nearby_lanes); } else { std::unordered_set<std::string> lane_ids; for (auto& lane_ptr : lanes) { if (lane_ptr == nullptr) { continue; } for (auto& lane_id : lane_ptr->lane().left_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (::apollo::common::math::DoubleCompare(s, 0.0) >= 0 && ::apollo::common::math::DoubleCompare(std::fabs(l), radius) > 0) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } for (auto& lane_id : lane_ptr->lane().right_neighbor_forward_lane_id()) { const std::string& id = lane_id.id(); if (lane_ids.find(id) != lane_ids.end()) { continue; } std::shared_ptr<const LaneInfo> nearby_lane = LaneById(id); double s = -1.0; double l = 0.0; GetProjection(point, nearby_lane, &s, &l); if (::apollo::common::math::DoubleCompare(s, 0.0) >= 0 && ::apollo::common::math::DoubleCompare(std::fabs(l), radius) > 0) { continue; } lane_ids.insert(id); nearby_lanes->push_back(nearby_lane); } } } } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (left_lane == nullptr) { return false; } for (auto& left_lane_id : curr_lane->lane().left_neighbor_forward_lane_id()) { if (left_lane->id().id() == left_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsLeftNeighborLane( std::shared_ptr<const LaneInfo> left_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsLeftNeighborLane(left_lane, lane)) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (right_lane == nullptr) { return false; } for (auto& right_lane_id : curr_lane->lane().right_neighbor_forward_lane_id()) { if (right_lane->id().id() == right_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsRightNeighborLane( std::shared_ptr<const LaneInfo> right_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsRightNeighborLane(right_lane, lane)) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (succ_lane == nullptr) { return false; } for (auto& successor_lane_id : curr_lane->lane().successor_id()) { if (succ_lane->id().id() == successor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsSuccessorLane( std::shared_ptr<const LaneInfo> succ_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsSuccessorLane(succ_lane, lane)) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr) { return true; } if (pred_lane == nullptr) { return false; } for (auto& predecessor_lane_id : curr_lane->lane().predecessor_id()) { if (pred_lane->id().id() == predecessor_lane_id.id()) { return true; } } return false; } bool PredictionMap::IsPredecessorLane( std::shared_ptr<const LaneInfo> pred_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsPredecessorLane(pred_lane, lane)) { return true; } } return false; } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, std::shared_ptr<const LaneInfo> curr_lane) { if (curr_lane == nullptr || other_lane == nullptr) { return true; } return other_lane->id().id() == curr_lane->id().id(); } bool PredictionMap::IsIdenticalLane( std::shared_ptr<const LaneInfo> other_lane, const std::vector<std::shared_ptr<const LaneInfo>>& lanes) { if (lanes.size() == 0) { return true; } for (auto& lane : lanes) { if (IsIdenticalLane(other_lane, lane)) { return true; } } return false; } int PredictionMap::LaneTurnType(const std::string& lane_id) { std::shared_ptr<const LaneInfo> lane = LaneById(lane_id); if (lane != nullptr) { return static_cast<int>(lane->lane().turn()); } return 1; } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before><commit_msg>created function to get only overloads<commit_after><|endoftext|>
<commit_before><commit_msg>Replace IMPL_STATIC_LINK[_TYPED] with more useful variants<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** 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. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeotilecache_p.h" #include "qgeotilespec.h" #include "qgeomappingmanager.h" #include <QDir> #include <QMetaType> #include <QPixmap> #include <QDebug> #include <Qt3D/qgltexture2d.h> Q_DECLARE_METATYPE(QList<QGeoTileSpec>) Q_DECLARE_METATYPE(QSet<QGeoTileSpec>) QT_BEGIN_NAMESPACE class QGeoCachedTileMemory { public: ~QGeoCachedTileMemory() { if (cache) cache->evictFromMemoryCache(this); } QGeoTileSpec spec; QGeoTileCache *cache; QByteArray bytes; QString format; }; QGeoTileTexture::QGeoTileTexture() : texture(0), cache(0), textureBound(false) {} void QCache3QTileEvictionPolicy::aboutToBeRemoved(const QGeoTileSpec &key, QSharedPointer<QGeoCachedTileDisk> obj) { Q_UNUSED(key); // set the cache pointer to zero so we can't call evictFromDiskCache obj->cache = 0; } void QCache3QTileEvictionPolicy::aboutToBeEvicted(const QGeoTileSpec &key, QSharedPointer<QGeoCachedTileDisk> obj) { Q_UNUSED(key); Q_UNUSED(obj); // leave the pointer set if it's a real eviction } QGeoCachedTileDisk::~QGeoCachedTileDisk() { if (cache) cache->evictFromDiskCache(this); } QGeoTileTexture::~QGeoTileTexture() { if (cache) cache->evictFromTextureCache(this); } QGeoTileCache::QGeoTileCache(const QString &directory, QObject *parent) : QObject(parent), directory_(directory), minTextureUsage_(0), extraTextureUsage_(0) { qRegisterMetaType<QGeoTileSpec>(); qRegisterMetaType<QList<QGeoTileSpec> >(); qRegisterMetaType<QSet<QGeoTileSpec> >(); // We keep default values here so that they are in one place // rather than in each individual plugin (the plugins can // of course override them) if (directory_.isEmpty()) { QString dirname = QLatin1String(".tilecache"); QDir home = QDir::home(); if (!home.exists(dirname)) home.mkdir(dirname); directory_ = home.filePath(dirname); } // default values setMaxDiskUsage(20 * 1024 * 1024); setMaxMemoryUsage(4 * 1024 * 1024); setExtraTextureUsage(12 * 1024 * 1024); loadTiles(); } QGeoTileCache::~QGeoTileCache() {} void QGeoTileCache::printStats() { textureCache_.printStats(); memoryCache_.printStats(); diskCache_.printStats(); } void QGeoTileCache::setMaxDiskUsage(int diskUsage) { diskCache_.setMaxCost(diskUsage); } int QGeoTileCache::maxDiskUsage() const { return diskCache_.maxCost(); } int QGeoTileCache::diskUsage() const { return diskCache_.totalCost(); } void QGeoTileCache::setMaxMemoryUsage(int memoryUsage) { memoryCache_.setMaxCost(memoryUsage); } int QGeoTileCache::maxMemoryUsage() const { return memoryCache_.maxCost(); } int QGeoTileCache::memoryUsage() const { return memoryCache_.totalCost(); } void QGeoTileCache::setExtraTextureUsage(int textureUsage) { extraTextureUsage_ = textureUsage; textureCache_.setMaxCost(minTextureUsage_ + extraTextureUsage_); } void QGeoTileCache::setMinTextureUsage(int textureUsage) { minTextureUsage_ = textureUsage; textureCache_.setMaxCost(minTextureUsage_ + extraTextureUsage_); } int QGeoTileCache::maxTextureUsage() const { return textureCache_.maxCost(); } int QGeoTileCache::minTextureUsage() const { return minTextureUsage_; } int QGeoTileCache::textureUsage() const { return textureCache_.totalCost(); } void QGeoTileCache::GLContextAvailable() { QMutexLocker ml(&cleanupMutex_); /* Throttle the cleanup to 10 items/frame to avoid blocking the render * for too long. Normally only 6-20 tiles are on screen at a time so * eviction rates shouldn't be much higher than this. */ int todo = qMin(cleanupList_.size(), 10); for (int i = 0; i < todo; ++i) { QGLTexture2D *texture = cleanupList_.front(); if (texture) { texture->release(); texture->cleanupResources(); delete texture; } cleanupList_.pop_front(); } } QSharedPointer<QGeoTileTexture> QGeoTileCache::get(const QGeoTileSpec &spec) { QSharedPointer<QGeoTileTexture> tt = textureCache_.object(spec); if (tt) return tt; QSharedPointer<QGeoCachedTileMemory> tm = memoryCache_.object(spec); if (tm) { QPixmap pixmap; if (!pixmap.loadFromData(tm->bytes)) { handleError(spec, QLatin1String("Problem with tile image")); return QSharedPointer<QGeoTileTexture>(0); } QSharedPointer<QGeoTileTexture> tt = addToTextureCache(spec, pixmap); if (tt) return tt; } QSharedPointer<QGeoCachedTileDisk> td = diskCache_.object(spec); if (td) { QStringList parts = td->filename.split('.'); QFile file(td->filename); file.open(QIODevice::ReadOnly); QByteArray bytes = file.readAll(); file.close(); QPixmap pixmap; const char *format = (parts.size() == 2 ? parts.at(1).toLocal8Bit().constData() : 0); if (!pixmap.loadFromData(bytes, format)) { handleError(spec, QLatin1String("Problem with tile image")); return QSharedPointer<QGeoTileTexture>(0); } addToMemoryCache(spec, bytes, (parts.size() == 2 ? parts.at(1) : QLatin1String(""))); QSharedPointer<QGeoTileTexture> tt = addToTextureCache(td->spec, pixmap); if (tt) return tt; } return QSharedPointer<QGeoTileTexture>(); } void QGeoTileCache::insert(const QGeoTileSpec &spec, const QByteArray &bytes, const QString &format, QGeoTiledMappingManagerEngine::CacheAreas areas) { if (areas & QGeoTiledMappingManagerEngine::DiskCache) { QString filename = tileSpecToFilename(spec, format, directory_); QFile file(filename); file.open(QIODevice::WriteOnly); file.write(bytes); file.close(); addToDiskCache(spec, filename); } if (areas & QGeoTiledMappingManagerEngine::MemoryCache) { addToMemoryCache(spec, bytes, format); } /* inserts do not hit the texture cache -- this actually reduces overall * cache hit rates because many tiles come too late to be useful * and act as a poison */ } void QGeoTileCache::evictFromDiskCache(QGeoCachedTileDisk *td) { QFile::remove(td->filename); } void QGeoTileCache::evictFromMemoryCache(QGeoCachedTileMemory * /* tm */) { } void QGeoTileCache::evictFromTextureCache(QGeoTileTexture *tt) { QMutexLocker ml(&cleanupMutex_); cleanupList_ << tt->texture; } QSharedPointer<QGeoCachedTileDisk> QGeoTileCache::addToDiskCache(const QGeoTileSpec &spec, const QString &filename) { QSharedPointer<QGeoCachedTileDisk> td(new QGeoCachedTileDisk); td->spec = spec; td->filename = filename; td->cache = this; QFileInfo fi(filename); int diskCost = fi.size(); diskCache_.insert(spec, td, diskCost); return td; } QSharedPointer<QGeoCachedTileMemory> QGeoTileCache::addToMemoryCache(const QGeoTileSpec &spec, const QByteArray &bytes, const QString &format) { QSharedPointer<QGeoCachedTileMemory> tm(new QGeoCachedTileMemory); tm->spec = spec; tm->cache = this; tm->bytes = bytes; tm->format = format; int cost = bytes.size(); memoryCache_.insert(spec, tm, cost); return tm; } QSharedPointer<QGeoTileTexture> QGeoTileCache::addToTextureCache(const QGeoTileSpec &spec, const QPixmap &pixmap) { QSharedPointer<QGeoTileTexture> tt(new QGeoTileTexture); tt->spec = spec; tt->texture = new QGLTexture2D(); tt->texture->setPixmap(pixmap); tt->texture->setHorizontalWrap(QGL::ClampToEdge); tt->texture->setVerticalWrap(QGL::ClampToEdge); tt->cache = this; /* Do not bind/cleanImage on the texture here -- it needs to be done * in the render thread (by qgeomapgeometry) */ int textureCost = pixmap.width() * pixmap.height() * pixmap.depth() / 8; textureCache_.insert(spec, tt, textureCost); return tt; } void QGeoTileCache::handleError(const QGeoTileSpec &, const QString &error) { qWarning() << "tile request error " << error; } void QGeoTileCache::loadTiles() { QStringList formats; //formats << QLatin1String("*.png"); formats << QLatin1String("*.*"); QDir dir(directory_); //QStringList files = dir.entryList(formats, QDir::Files, QDir::Time | QDir::Reversed); QStringList files = dir.entryList(formats, QDir::Files); int tiles = 0; for (int i = 0; i < files.size(); ++i) { QGeoTileSpec spec = filenameToTileSpec(files.at(i)); if (spec.zoom() == -1) continue; QString filename = dir.filePath(files.at(i)); addToDiskCache(spec, filename); tiles++; } } QString QGeoTileCache::tileSpecToFilename(const QGeoTileSpec &spec, const QString &format, const QString &directory) { QString filename = spec.plugin(); filename += QLatin1String("-"); filename += QString::number(spec.mapId()); filename += QLatin1String("-"); filename += QString::number(spec.zoom()); filename += QLatin1String("-"); filename += QString::number(spec.x()); filename += QLatin1String("-"); filename += QString::number(spec.y()); filename += QLatin1String("."); filename += format; QDir dir = QDir(directory); return dir.filePath(filename); } QGeoTileSpec QGeoTileCache::filenameToTileSpec(const QString &filename) { QGeoTileSpec emptySpec; QStringList parts = filename.split('.'); if (parts.length() != 2) return emptySpec; QString name = parts.at(0); QStringList fields = name.split('-'); if (fields.length() != 5) return emptySpec; QList<int> numbers; bool ok = false; for (int i = 1; i < 5; ++i) { ok = false; int value = fields.at(i).toInt(&ok); if (!ok) return emptySpec; numbers.append(value); } return QGeoTileSpec(fields.at(0), numbers.at(0), numbers.at(1), numbers.at(2), numbers.at(3)); } QT_END_NAMESPACE <commit_msg>Reduce default tile+texture cache size to 9Mb (was 16Mb)<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** 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. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeotilecache_p.h" #include "qgeotilespec.h" #include "qgeomappingmanager.h" #include <QDir> #include <QMetaType> #include <QPixmap> #include <QDebug> #include <Qt3D/qgltexture2d.h> Q_DECLARE_METATYPE(QList<QGeoTileSpec>) Q_DECLARE_METATYPE(QSet<QGeoTileSpec>) QT_BEGIN_NAMESPACE class QGeoCachedTileMemory { public: ~QGeoCachedTileMemory() { if (cache) cache->evictFromMemoryCache(this); } QGeoTileSpec spec; QGeoTileCache *cache; QByteArray bytes; QString format; }; QGeoTileTexture::QGeoTileTexture() : texture(0), cache(0), textureBound(false) {} void QCache3QTileEvictionPolicy::aboutToBeRemoved(const QGeoTileSpec &key, QSharedPointer<QGeoCachedTileDisk> obj) { Q_UNUSED(key); // set the cache pointer to zero so we can't call evictFromDiskCache obj->cache = 0; } void QCache3QTileEvictionPolicy::aboutToBeEvicted(const QGeoTileSpec &key, QSharedPointer<QGeoCachedTileDisk> obj) { Q_UNUSED(key); Q_UNUSED(obj); // leave the pointer set if it's a real eviction } QGeoCachedTileDisk::~QGeoCachedTileDisk() { if (cache) cache->evictFromDiskCache(this); } QGeoTileTexture::~QGeoTileTexture() { if (cache) cache->evictFromTextureCache(this); } QGeoTileCache::QGeoTileCache(const QString &directory, QObject *parent) : QObject(parent), directory_(directory), minTextureUsage_(0), extraTextureUsage_(0) { qRegisterMetaType<QGeoTileSpec>(); qRegisterMetaType<QList<QGeoTileSpec> >(); qRegisterMetaType<QSet<QGeoTileSpec> >(); // We keep default values here so that they are in one place // rather than in each individual plugin (the plugins can // of course override them) if (directory_.isEmpty()) { QString dirname = QLatin1String(".tilecache"); QDir home = QDir::home(); if (!home.exists(dirname)) home.mkdir(dirname); directory_ = home.filePath(dirname); } // default values setMaxDiskUsage(20 * 1024 * 1024); setMaxMemoryUsage(3 * 1024 * 1024); setExtraTextureUsage(6 * 1024 * 1024); loadTiles(); } QGeoTileCache::~QGeoTileCache() {} void QGeoTileCache::printStats() { textureCache_.printStats(); memoryCache_.printStats(); diskCache_.printStats(); } void QGeoTileCache::setMaxDiskUsage(int diskUsage) { diskCache_.setMaxCost(diskUsage); } int QGeoTileCache::maxDiskUsage() const { return diskCache_.maxCost(); } int QGeoTileCache::diskUsage() const { return diskCache_.totalCost(); } void QGeoTileCache::setMaxMemoryUsage(int memoryUsage) { memoryCache_.setMaxCost(memoryUsage); } int QGeoTileCache::maxMemoryUsage() const { return memoryCache_.maxCost(); } int QGeoTileCache::memoryUsage() const { return memoryCache_.totalCost(); } void QGeoTileCache::setExtraTextureUsage(int textureUsage) { extraTextureUsage_ = textureUsage; textureCache_.setMaxCost(minTextureUsage_ + extraTextureUsage_); } void QGeoTileCache::setMinTextureUsage(int textureUsage) { minTextureUsage_ = textureUsage; textureCache_.setMaxCost(minTextureUsage_ + extraTextureUsage_); } int QGeoTileCache::maxTextureUsage() const { return textureCache_.maxCost(); } int QGeoTileCache::minTextureUsage() const { return minTextureUsage_; } int QGeoTileCache::textureUsage() const { return textureCache_.totalCost(); } void QGeoTileCache::GLContextAvailable() { QMutexLocker ml(&cleanupMutex_); /* Throttle the cleanup to 10 items/frame to avoid blocking the render * for too long. Normally only 6-20 tiles are on screen at a time so * eviction rates shouldn't be much higher than this. */ int todo = qMin(cleanupList_.size(), 10); for (int i = 0; i < todo; ++i) { QGLTexture2D *texture = cleanupList_.front(); if (texture) { texture->release(); texture->cleanupResources(); delete texture; } cleanupList_.pop_front(); } } QSharedPointer<QGeoTileTexture> QGeoTileCache::get(const QGeoTileSpec &spec) { QSharedPointer<QGeoTileTexture> tt = textureCache_.object(spec); if (tt) return tt; QSharedPointer<QGeoCachedTileMemory> tm = memoryCache_.object(spec); if (tm) { QPixmap pixmap; if (!pixmap.loadFromData(tm->bytes)) { handleError(spec, QLatin1String("Problem with tile image")); return QSharedPointer<QGeoTileTexture>(0); } QSharedPointer<QGeoTileTexture> tt = addToTextureCache(spec, pixmap); if (tt) return tt; } QSharedPointer<QGeoCachedTileDisk> td = diskCache_.object(spec); if (td) { QStringList parts = td->filename.split('.'); QFile file(td->filename); file.open(QIODevice::ReadOnly); QByteArray bytes = file.readAll(); file.close(); QPixmap pixmap; const char *format = (parts.size() == 2 ? parts.at(1).toLocal8Bit().constData() : 0); if (!pixmap.loadFromData(bytes, format)) { handleError(spec, QLatin1String("Problem with tile image")); return QSharedPointer<QGeoTileTexture>(0); } addToMemoryCache(spec, bytes, (parts.size() == 2 ? parts.at(1) : QLatin1String(""))); QSharedPointer<QGeoTileTexture> tt = addToTextureCache(td->spec, pixmap); if (tt) return tt; } return QSharedPointer<QGeoTileTexture>(); } void QGeoTileCache::insert(const QGeoTileSpec &spec, const QByteArray &bytes, const QString &format, QGeoTiledMappingManagerEngine::CacheAreas areas) { if (areas & QGeoTiledMappingManagerEngine::DiskCache) { QString filename = tileSpecToFilename(spec, format, directory_); QFile file(filename); file.open(QIODevice::WriteOnly); file.write(bytes); file.close(); addToDiskCache(spec, filename); } if (areas & QGeoTiledMappingManagerEngine::MemoryCache) { addToMemoryCache(spec, bytes, format); } /* inserts do not hit the texture cache -- this actually reduces overall * cache hit rates because many tiles come too late to be useful * and act as a poison */ } void QGeoTileCache::evictFromDiskCache(QGeoCachedTileDisk *td) { QFile::remove(td->filename); } void QGeoTileCache::evictFromMemoryCache(QGeoCachedTileMemory * /* tm */) { } void QGeoTileCache::evictFromTextureCache(QGeoTileTexture *tt) { QMutexLocker ml(&cleanupMutex_); cleanupList_ << tt->texture; } QSharedPointer<QGeoCachedTileDisk> QGeoTileCache::addToDiskCache(const QGeoTileSpec &spec, const QString &filename) { QSharedPointer<QGeoCachedTileDisk> td(new QGeoCachedTileDisk); td->spec = spec; td->filename = filename; td->cache = this; QFileInfo fi(filename); int diskCost = fi.size(); diskCache_.insert(spec, td, diskCost); return td; } QSharedPointer<QGeoCachedTileMemory> QGeoTileCache::addToMemoryCache(const QGeoTileSpec &spec, const QByteArray &bytes, const QString &format) { QSharedPointer<QGeoCachedTileMemory> tm(new QGeoCachedTileMemory); tm->spec = spec; tm->cache = this; tm->bytes = bytes; tm->format = format; int cost = bytes.size(); memoryCache_.insert(spec, tm, cost); return tm; } QSharedPointer<QGeoTileTexture> QGeoTileCache::addToTextureCache(const QGeoTileSpec &spec, const QPixmap &pixmap) { QSharedPointer<QGeoTileTexture> tt(new QGeoTileTexture); tt->spec = spec; tt->texture = new QGLTexture2D(); tt->texture->setPixmap(pixmap); tt->texture->setHorizontalWrap(QGL::ClampToEdge); tt->texture->setVerticalWrap(QGL::ClampToEdge); tt->cache = this; /* Do not bind/cleanImage on the texture here -- it needs to be done * in the render thread (by qgeomapgeometry) */ int textureCost = pixmap.width() * pixmap.height() * pixmap.depth() / 8; textureCache_.insert(spec, tt, textureCost); return tt; } void QGeoTileCache::handleError(const QGeoTileSpec &, const QString &error) { qWarning() << "tile request error " << error; } void QGeoTileCache::loadTiles() { QStringList formats; //formats << QLatin1String("*.png"); formats << QLatin1String("*.*"); QDir dir(directory_); //QStringList files = dir.entryList(formats, QDir::Files, QDir::Time | QDir::Reversed); QStringList files = dir.entryList(formats, QDir::Files); int tiles = 0; for (int i = 0; i < files.size(); ++i) { QGeoTileSpec spec = filenameToTileSpec(files.at(i)); if (spec.zoom() == -1) continue; QString filename = dir.filePath(files.at(i)); addToDiskCache(spec, filename); tiles++; } } QString QGeoTileCache::tileSpecToFilename(const QGeoTileSpec &spec, const QString &format, const QString &directory) { QString filename = spec.plugin(); filename += QLatin1String("-"); filename += QString::number(spec.mapId()); filename += QLatin1String("-"); filename += QString::number(spec.zoom()); filename += QLatin1String("-"); filename += QString::number(spec.x()); filename += QLatin1String("-"); filename += QString::number(spec.y()); filename += QLatin1String("."); filename += format; QDir dir = QDir(directory); return dir.filePath(filename); } QGeoTileSpec QGeoTileCache::filenameToTileSpec(const QString &filename) { QGeoTileSpec emptySpec; QStringList parts = filename.split('.'); if (parts.length() != 2) return emptySpec; QString name = parts.at(0); QStringList fields = name.split('-'); if (fields.length() != 5) return emptySpec; QList<int> numbers; bool ok = false; for (int i = 1; i < 5; ++i) { ok = false; int value = fields.at(i).toInt(&ok); if (!ok) return emptySpec; numbers.append(value); } return QGeoTileSpec(fields.at(0), numbers.at(0), numbers.at(1), numbers.at(2), numbers.at(3)); } QT_END_NAMESPACE <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkAnalyzeImageIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <fstream> #include "itkImageFileReader.h" #include "itkImage.h" #include <itksys/SystemTools.hxx> #include "itkImageRegionIterator.h" #include <iostream> #include <fstream> #include "itkImageFileWriter.h" #include "itkImageIOFactory.h" #include "itkAnalyzeImageIOFactory.h" #include "itkNiftiImageIOFactory.h" #include "itkAnalyzeImageIO.h" #include "itkNiftiImageIO.h" #include "itkSpatialOrientationAdapter.h" #include <stdio.h> #include "itkMetaDataObject.h" #include "itkIOCommon.h" #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__)) #include <stdlib.h> #define _unlink unlink #else #include <unistd.h> #endif static inline int Remove(const char *fname) { return unlink(fname); } const unsigned char RPI=16; /*Bit pattern 0 0 0 10000*/ const unsigned char LEFT=128; /*Bit pattern 1 0 0 00000*/ const unsigned char ANTERIOR=64; /*Bit pattern 0 1 0 00000*/ const unsigned char SUPERIOR=32; /*Bit pattern 0 0 1 00000*/ static int WriteTestFiles(const std::string AugmentName) { #include "LittleEndian_hdr.h" #include "LittleEndian_img.h" #include "BigEndian_hdr.h" #include "BigEndian_img.h" std::string LittleEndianHdrName=AugmentName+"LittleEndian.hdr"; std::ofstream little_hdr(LittleEndianHdrName.c_str(), std::ios::binary | std::ios::out); if(!little_hdr.is_open()) { return EXIT_FAILURE; } //std::cout << LittleEndianHdrName << " written" << std::endl; little_hdr.write(reinterpret_cast<const char *>(LittleEndian_hdr),sizeof(LittleEndian_hdr)); little_hdr.close(); std::string LittleEndianImgName=AugmentName+"LittleEndian.img"; std::ofstream little_img(LittleEndianImgName.c_str(), std::ios::binary | std::ios::out); if(!little_img.is_open()) { return EXIT_FAILURE; } little_img.write(reinterpret_cast<const char *>(LittleEndian_img),sizeof(LittleEndian_img)); little_img.close(); std::string BigEndianHdrName=AugmentName+"BigEndian.hdr"; std::ofstream big_hdr(BigEndianHdrName.c_str(), std::ios::binary | std::ios::out); if(!big_hdr.is_open()) { return EXIT_FAILURE; } big_hdr.write(reinterpret_cast<const char *>(BigEndian_hdr),sizeof(BigEndian_hdr)); big_hdr.close(); std::string BigEndianImgName=AugmentName+"BigEndian.img"; std::ofstream big_img(BigEndianImgName.c_str(), std::ios::binary | std::ios::out); if(!big_img.is_open()) { return EXIT_FAILURE; } big_img.write(reinterpret_cast<const char *>(BigEndian_img),sizeof(BigEndian_img)); big_img.close(); return EXIT_SUCCESS; } static void RemoveByteSwapTestFiles(const std::string AugmentName) { //--// Remove(AugmentName+"LittleEndian.hdr"); //--// Remove(AugmentName+"LittleEndian.img"); //--// Remove(AugmentName+"BigEndian.hdr"); //--// Remove(AugmentName+"BigEndian.img"); } static int TestByteSwap(const std::string AugmentName) { int rval; typedef itk::Image<double, 3> ImageType ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; if(WriteTestFiles(AugmentName) == -1) { return EXIT_FAILURE; } ImageType::Pointer little; ImageType::Pointer big; itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); try { imageReader->SetFileName(AugmentName+"LittleEndian.hdr") ; imageReader->Update() ; little = imageReader->GetOutput() ; imageReader->SetFileName(AugmentName+"BigEndian.hdr") ; imageReader->Update() ; big = imageReader->GetOutput(); std::cout << "Printing Dictionary" << std::endl; big->GetMetaDataDictionary().Print(std::cout); } catch (itk::ExceptionObject &e) { e.Print(std::cerr) ; RemoveByteSwapTestFiles(AugmentName); return EXIT_FAILURE; } rval = 0; try { itk::ImageRegionConstIterator<ImageType> littleIter(little, little->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<ImageType> bigIter(big, big->GetLargestPossibleRegion()); while(!littleIter.IsAtEnd()) { if(littleIter.Get() != bigIter.Get()) break; ++littleIter; ++bigIter; } if(!littleIter.IsAtEnd() || !bigIter.IsAtEnd()) rval = -1; } catch ( itk::ExceptionObject & ex ) { std::cerr << "Error filling array" << ex.GetDescription() << std::endl; rval= -1; } RemoveByteSwapTestFiles(AugmentName); return rval; } template <typename T> int MakeImage(const std::string AugmentName) { typedef itk::Image<T, 3> ImageType ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; const std::string filename=std::string(typeid(T).name()) +"_"+AugmentName+"_" +std::string("test.hdr"); //Allocate Images enum { ImageDimension = ImageType::ImageDimension }; typename ImageType::Pointer img; const typename ImageType::SizeType size = {{10,10,10}}; const typename ImageType::IndexType index = {{0,0,0}}; typename ImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); img = ImageType::New(); img->SetLargestPossibleRegion( region ); img->SetBufferedRegion( region ); img->SetRequestedRegion( region ); typename itk::SpatialOrientationAdapter::DirectionType CORdir= itk::SpatialOrientationAdapter().ToDirectionCosines(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP); img->SetDirection(CORdir); img->Allocate(); { //Fill in entire image itk::ImageRegionIterator<ImageType> ri(img,region); try { while(!ri.IsAtEnd()) { ri.Set( RPI ); ++ri; } } catch ( itk::ExceptionObject & ex ) { std::cerr << "Error filling array" << ex.GetDescription() << std::endl; return EXIT_FAILURE; } } { //Fill in left half const typename ImageType::IndexType RPIindex = {{0,0,0}}; const typename ImageType::SizeType RPIsize = {{5,10,10}}; typename ImageType::RegionType RPIregion; RPIregion.SetSize( RPIsize ); RPIregion.SetIndex( RPIindex ); itk::ImageRegionIterator<ImageType > RPIiterator(img,RPIregion); while(!RPIiterator.IsAtEnd()) { RPIiterator.Set( RPIiterator.Get() + LEFT ); ++RPIiterator; } } { //Fill in anterior half const typename ImageType::IndexType RPIindex = {{0,5,0}}; const typename ImageType::SizeType RPIsize = {{10,5,10}}; typename ImageType::RegionType RPIregion; RPIregion.SetSize( RPIsize ); RPIregion.SetIndex( RPIindex ); itk::ImageRegionIterator<ImageType > RPIiterator(img,RPIregion); while(!RPIiterator.IsAtEnd()) { RPIiterator.Set( RPIiterator.Get() + ANTERIOR ); ++RPIiterator; } } { //Fill in superior half const typename ImageType::IndexType RPIindex = {{0,0,5}}; const typename ImageType::SizeType RPIsize = {{10,10,5}}; typename ImageType::RegionType RPIregion; RPIregion.SetSize( RPIsize ); RPIregion.SetIndex( RPIindex ); itk::ImageRegionIterator<ImageType > RPIiterator(img,RPIregion); while(!RPIiterator.IsAtEnd()) { RPIiterator.Set( RPIiterator.Get() + SUPERIOR ); ++RPIiterator; } } typedef itk::ImageFileWriter< ImageType > ImageWriterType; typename ImageWriterType::Pointer ImageWriterPointer = ImageWriterType::New(); //Set the output filename ImageWriterPointer->SetFileName(filename); //Attach input image to the writer. ImageWriterPointer->SetInput( img ); //Determine file type and instantiate appropriate ImageIO class if not //explicitly stated with SetImageIO, then write to disk. try { ImageWriterPointer->Write(); } catch ( itk::ExceptionObject & ex ) { std::string message; message = "Problem found while writing image "; message += filename; message += "\n"; message += ex.GetLocation(); message += "\n"; message += ex.GetDescription(); std::cerr << message << std::endl; //--// Remove(filename); return EXIT_FAILURE; } //typedef itk::ImageFileReader< ImageType > ImageReaderType ; typename ImageType::Pointer input; typename itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); try { imageReader->SetFileName(filename) ; imageReader->Update() ; input = imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { e.Print(std::cerr) ; //--// Remove(filename); return EXIT_FAILURE; } //--// Remove(filename); return EXIT_SUCCESS; } //template int MakeImage<char>(); int itkAnalyzeImageIOTest(int ac, char* av[]) { int rval = 0; //Have two loops through the code, the first one //reads and writes with the legacy AnalyzeIO, and //the second reads a writes with the NiftiIO mechanism. for(int loops=0;loops<2;loops++) { std::string AugmentName="NoneGiven"; if(loops==1) { itk::ObjectFactoryBase::UnRegisterAllFactories(); itk::AnalyzeImageIOFactory::RegisterOneFactory(); //itk::AnalyzeImageIOFactory::Pointer myAnalyzeIOFactory = itk::AnalyzeImageIOFactory::New(); //itk::ObjectFactoryBase::UnRegisterFactory(myAnalyzeIOFactory.GetPointer()); AugmentName="Analyze"; } else { itk::ObjectFactoryBase::UnRegisterAllFactories(); itk::NiftiImageIOFactory::RegisterOneFactory(); //itk::NiftiImageIOFactory::Pointer myNiftiIOFactory = itk::NiftiImageIOFactory::New(); //itk::ObjectFactoryBase::UnRegisterFactory(myNiftiIOFactory.GetPointer()); AugmentName="Nifti"; } // // first argument is passing in the writable directory to do all testing if(ac > 1) { char *testdir = *++av; --ac; itksys::SystemTools::ChangeDirectory(testdir); } if(ac > 1) //This is a mechanism for reading unsigned char images for testing. { typedef itk::Image<unsigned char, 3> ImageType ; ImageType::Pointer input; itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); for(int imagenameindex=1; imagenameindex < ac; imagenameindex++) { //std::cout << "Attempting to read " << av[imagenameindex] << std::endl; try { imageReader->SetFileName(av[imagenameindex]) ; imageReader->Update() ; input=imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { e.Print(std::cerr) ; rval = 1; } } } else //This is the mechanism for doing internal testing of all data types. { int cur_return; cur_return = MakeImage<char>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type char" << std::endl; rval += cur_return; } cur_return = MakeImage<unsigned char>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type unsigned char" << std::endl; rval += cur_return; } cur_return = MakeImage<short>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type short" << std::endl; rval += cur_return; } cur_return = MakeImage<unsigned short>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type unsigned short" << std::endl; rval += cur_return; } cur_return = MakeImage<int>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type int" << std::endl; rval += cur_return; } cur_return = MakeImage<float>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type float" << std::endl; rval += cur_return; } // awaiting a double precision byte swapper cur_return = MakeImage<double>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type double" << std::endl; rval += cur_return; } rval += TestByteSwap(AugmentName); } } return rval; } int itkAnalyzeImageIOTest2(int ac, char* av[]) { // // first argument is passing in the writable directory to do all testing if(ac > 1) { char *testdir = *++av; --ac; itksys::SystemTools::ChangeDirectory(testdir); } if(ac != 3) return EXIT_FAILURE; char *arg1 = av[1]; char *arg2 = av[2]; int test_success = 0; typedef itk::Image<signed short, 3> ImageType ; typedef ImageType::Pointer ImagePointer ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; itk::AnalyzeImageIO::Pointer io = itk::AnalyzeImageIO::New(); ImageReaderType::Pointer imageReader = ImageReaderType::New(); ImagePointer input; try { imageReader->SetImageIO(io); imageReader->SetFileName(arg2); imageReader->Update(); input = imageReader->GetOutput(); } catch (itk::ExceptionObject &) { test_success = 1; } if(strcmp(arg1, "true") == 0) { return test_success; } else { return !test_success; } } <commit_msg>COMP: Fixing warnings related to unused variable in function argument. Now using itkNotUsed() macro.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkAnalyzeImageIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <fstream> #include "itkImageFileReader.h" #include "itkImage.h" #include <itksys/SystemTools.hxx> #include "itkImageRegionIterator.h" #include <iostream> #include <fstream> #include "itkImageFileWriter.h" #include "itkImageIOFactory.h" #include "itkAnalyzeImageIOFactory.h" #include "itkNiftiImageIOFactory.h" #include "itkAnalyzeImageIO.h" #include "itkNiftiImageIO.h" #include "itkSpatialOrientationAdapter.h" #include <stdio.h> #include "itkMetaDataObject.h" #include "itkIOCommon.h" #if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__)) #include <stdlib.h> #define _unlink unlink #else #include <unistd.h> #endif static inline int Remove(const char *fname) { return unlink(fname); } const unsigned char RPI=16; /*Bit pattern 0 0 0 10000*/ const unsigned char LEFT=128; /*Bit pattern 1 0 0 00000*/ const unsigned char ANTERIOR=64; /*Bit pattern 0 1 0 00000*/ const unsigned char SUPERIOR=32; /*Bit pattern 0 0 1 00000*/ static int WriteTestFiles(const std::string AugmentName) { #include "LittleEndian_hdr.h" #include "LittleEndian_img.h" #include "BigEndian_hdr.h" #include "BigEndian_img.h" std::string LittleEndianHdrName=AugmentName+"LittleEndian.hdr"; std::ofstream little_hdr(LittleEndianHdrName.c_str(), std::ios::binary | std::ios::out); if(!little_hdr.is_open()) { return EXIT_FAILURE; } //std::cout << LittleEndianHdrName << " written" << std::endl; little_hdr.write(reinterpret_cast<const char *>(LittleEndian_hdr),sizeof(LittleEndian_hdr)); little_hdr.close(); std::string LittleEndianImgName=AugmentName+"LittleEndian.img"; std::ofstream little_img(LittleEndianImgName.c_str(), std::ios::binary | std::ios::out); if(!little_img.is_open()) { return EXIT_FAILURE; } little_img.write(reinterpret_cast<const char *>(LittleEndian_img),sizeof(LittleEndian_img)); little_img.close(); std::string BigEndianHdrName=AugmentName+"BigEndian.hdr"; std::ofstream big_hdr(BigEndianHdrName.c_str(), std::ios::binary | std::ios::out); if(!big_hdr.is_open()) { return EXIT_FAILURE; } big_hdr.write(reinterpret_cast<const char *>(BigEndian_hdr),sizeof(BigEndian_hdr)); big_hdr.close(); std::string BigEndianImgName=AugmentName+"BigEndian.img"; std::ofstream big_img(BigEndianImgName.c_str(), std::ios::binary | std::ios::out); if(!big_img.is_open()) { return EXIT_FAILURE; } big_img.write(reinterpret_cast<const char *>(BigEndian_img),sizeof(BigEndian_img)); big_img.close(); return EXIT_SUCCESS; } static void RemoveByteSwapTestFiles(const std::string & itkNotUsed(AugmentName) ) { //--// Remove(AugmentName+"LittleEndian.hdr"); //--// Remove(AugmentName+"LittleEndian.img"); //--// Remove(AugmentName+"BigEndian.hdr"); //--// Remove(AugmentName+"BigEndian.img"); } static int TestByteSwap(const std::string & AugmentName) { int rval; typedef itk::Image<double, 3> ImageType ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; if(WriteTestFiles(AugmentName) == -1) { return EXIT_FAILURE; } ImageType::Pointer little; ImageType::Pointer big; itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); try { imageReader->SetFileName(AugmentName+"LittleEndian.hdr") ; imageReader->Update() ; little = imageReader->GetOutput() ; imageReader->SetFileName(AugmentName+"BigEndian.hdr") ; imageReader->Update() ; big = imageReader->GetOutput(); std::cout << "Printing Dictionary" << std::endl; big->GetMetaDataDictionary().Print(std::cout); } catch (itk::ExceptionObject &e) { e.Print(std::cerr) ; RemoveByteSwapTestFiles(AugmentName); return EXIT_FAILURE; } rval = 0; try { itk::ImageRegionConstIterator<ImageType> littleIter(little, little->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<ImageType> bigIter(big, big->GetLargestPossibleRegion()); while(!littleIter.IsAtEnd()) { if(littleIter.Get() != bigIter.Get()) break; ++littleIter; ++bigIter; } if(!littleIter.IsAtEnd() || !bigIter.IsAtEnd()) rval = -1; } catch ( itk::ExceptionObject & ex ) { std::cerr << "Error filling array" << ex.GetDescription() << std::endl; rval= -1; } RemoveByteSwapTestFiles(AugmentName); return rval; } template <typename T> int MakeImage(const std::string & AugmentName) { typedef itk::Image<T, 3> ImageType ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; const std::string filename=std::string(typeid(T).name()) +"_"+AugmentName+"_" +std::string("test.hdr"); //Allocate Images enum { ImageDimension = ImageType::ImageDimension }; typename ImageType::Pointer img; const typename ImageType::SizeType size = {{10,10,10}}; const typename ImageType::IndexType index = {{0,0,0}}; typename ImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); img = ImageType::New(); img->SetLargestPossibleRegion( region ); img->SetBufferedRegion( region ); img->SetRequestedRegion( region ); typename itk::SpatialOrientationAdapter::DirectionType CORdir= itk::SpatialOrientationAdapter().ToDirectionCosines(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RIP); img->SetDirection(CORdir); img->Allocate(); { //Fill in entire image itk::ImageRegionIterator<ImageType> ri(img,region); try { while(!ri.IsAtEnd()) { ri.Set( RPI ); ++ri; } } catch ( itk::ExceptionObject & ex ) { std::cerr << "Error filling array" << ex.GetDescription() << std::endl; return EXIT_FAILURE; } } { //Fill in left half const typename ImageType::IndexType RPIindex = {{0,0,0}}; const typename ImageType::SizeType RPIsize = {{5,10,10}}; typename ImageType::RegionType RPIregion; RPIregion.SetSize( RPIsize ); RPIregion.SetIndex( RPIindex ); itk::ImageRegionIterator<ImageType > RPIiterator(img,RPIregion); while(!RPIiterator.IsAtEnd()) { RPIiterator.Set( RPIiterator.Get() + LEFT ); ++RPIiterator; } } { //Fill in anterior half const typename ImageType::IndexType RPIindex = {{0,5,0}}; const typename ImageType::SizeType RPIsize = {{10,5,10}}; typename ImageType::RegionType RPIregion; RPIregion.SetSize( RPIsize ); RPIregion.SetIndex( RPIindex ); itk::ImageRegionIterator<ImageType > RPIiterator(img,RPIregion); while(!RPIiterator.IsAtEnd()) { RPIiterator.Set( RPIiterator.Get() + ANTERIOR ); ++RPIiterator; } } { //Fill in superior half const typename ImageType::IndexType RPIindex = {{0,0,5}}; const typename ImageType::SizeType RPIsize = {{10,10,5}}; typename ImageType::RegionType RPIregion; RPIregion.SetSize( RPIsize ); RPIregion.SetIndex( RPIindex ); itk::ImageRegionIterator<ImageType > RPIiterator(img,RPIregion); while(!RPIiterator.IsAtEnd()) { RPIiterator.Set( RPIiterator.Get() + SUPERIOR ); ++RPIiterator; } } typedef itk::ImageFileWriter< ImageType > ImageWriterType; typename ImageWriterType::Pointer ImageWriterPointer = ImageWriterType::New(); //Set the output filename ImageWriterPointer->SetFileName(filename); //Attach input image to the writer. ImageWriterPointer->SetInput( img ); //Determine file type and instantiate appropriate ImageIO class if not //explicitly stated with SetImageIO, then write to disk. try { ImageWriterPointer->Write(); } catch ( itk::ExceptionObject & ex ) { std::string message; message = "Problem found while writing image "; message += filename; message += "\n"; message += ex.GetLocation(); message += "\n"; message += ex.GetDescription(); std::cerr << message << std::endl; //--// Remove(filename); return EXIT_FAILURE; } //typedef itk::ImageFileReader< ImageType > ImageReaderType ; typename ImageType::Pointer input; typename itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); try { imageReader->SetFileName(filename) ; imageReader->Update() ; input = imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { e.Print(std::cerr) ; //--// Remove(filename); return EXIT_FAILURE; } //--// Remove(filename); return EXIT_SUCCESS; } //template int MakeImage<char>(); int itkAnalyzeImageIOTest(int ac, char* av[]) { int rval = 0; //Have two loops through the code, the first one //reads and writes with the legacy AnalyzeIO, and //the second reads a writes with the NiftiIO mechanism. for(int loops=0;loops<2;loops++) { std::string AugmentName="NoneGiven"; if(loops==1) { itk::ObjectFactoryBase::UnRegisterAllFactories(); itk::AnalyzeImageIOFactory::RegisterOneFactory(); //itk::AnalyzeImageIOFactory::Pointer myAnalyzeIOFactory = itk::AnalyzeImageIOFactory::New(); //itk::ObjectFactoryBase::UnRegisterFactory(myAnalyzeIOFactory.GetPointer()); AugmentName="Analyze"; } else { itk::ObjectFactoryBase::UnRegisterAllFactories(); itk::NiftiImageIOFactory::RegisterOneFactory(); //itk::NiftiImageIOFactory::Pointer myNiftiIOFactory = itk::NiftiImageIOFactory::New(); //itk::ObjectFactoryBase::UnRegisterFactory(myNiftiIOFactory.GetPointer()); AugmentName="Nifti"; } // // first argument is passing in the writable directory to do all testing if(ac > 1) { char *testdir = *++av; --ac; itksys::SystemTools::ChangeDirectory(testdir); } if(ac > 1) //This is a mechanism for reading unsigned char images for testing. { typedef itk::Image<unsigned char, 3> ImageType ; ImageType::Pointer input; itk::ImageFileReader<ImageType>::Pointer imageReader = itk::ImageFileReader<ImageType>::New(); for(int imagenameindex=1; imagenameindex < ac; imagenameindex++) { //std::cout << "Attempting to read " << av[imagenameindex] << std::endl; try { imageReader->SetFileName(av[imagenameindex]) ; imageReader->Update() ; input=imageReader->GetOutput() ; } catch (itk::ExceptionObject &e) { e.Print(std::cerr) ; rval = 1; } } } else //This is the mechanism for doing internal testing of all data types. { int cur_return; cur_return = MakeImage<char>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type char" << std::endl; rval += cur_return; } cur_return = MakeImage<unsigned char>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type unsigned char" << std::endl; rval += cur_return; } cur_return = MakeImage<short>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type short" << std::endl; rval += cur_return; } cur_return = MakeImage<unsigned short>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type unsigned short" << std::endl; rval += cur_return; } cur_return = MakeImage<int>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type int" << std::endl; rval += cur_return; } cur_return = MakeImage<float>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type float" << std::endl; rval += cur_return; } // awaiting a double precision byte swapper cur_return = MakeImage<double>(AugmentName); if(cur_return != 0) { std::cerr << "Error writing Analyze file type double" << std::endl; rval += cur_return; } rval += TestByteSwap(AugmentName); } } return rval; } int itkAnalyzeImageIOTest2(int ac, char* av[]) { // // first argument is passing in the writable directory to do all testing if(ac > 1) { char *testdir = *++av; --ac; itksys::SystemTools::ChangeDirectory(testdir); } if(ac != 3) return EXIT_FAILURE; char *arg1 = av[1]; char *arg2 = av[2]; int test_success = 0; typedef itk::Image<signed short, 3> ImageType ; typedef ImageType::Pointer ImagePointer ; typedef itk::ImageFileReader< ImageType > ImageReaderType ; itk::AnalyzeImageIO::Pointer io = itk::AnalyzeImageIO::New(); ImageReaderType::Pointer imageReader = ImageReaderType::New(); ImagePointer input; try { imageReader->SetImageIO(io); imageReader->SetFileName(arg2); imageReader->Update(); input = imageReader->GetOutput(); } catch (itk::ExceptionObject &) { test_success = 1; } if(strcmp(arg1, "true") == 0) { return test_success; } else { return !test_success; } } <|endoftext|>
<commit_before>// this file defines the itkFEMTests for the test driver // and all it expects is that you have a function called RegisterTests #include <iostream> #include "itkTestMain.h" // Register all *.cxx files that do the testing with the REGISTER_TEST // macro. void RegisterTests() { //REGISTER_TEST(itkFEMElementTestMenu); REGISTER_TEST(itkFEMElementTest); REGISTER_TEST(itkFEMLinearSystemWrapperItpackTest); REGISTER_TEST(itkFEMLinearSystemWrapperVNLTest); REGISTER_TEST(itkFEMLinearSystemWrapperDenseVNLTest); //REGISTER_TEST( itkFEMBar2DTest ); } <commit_msg>FIX: Warnings on MSVS.<commit_after>// this file defines the itkFEMTests for the test driver // and all it expects is that you have a function called RegisterTests // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include <iostream> #include "itkTestMain.h" // Register all *.cxx files that do the testing with the REGISTER_TEST // macro. void RegisterTests() { //REGISTER_TEST(itkFEMElementTestMenu); REGISTER_TEST(itkFEMElementTest); REGISTER_TEST(itkFEMLinearSystemWrapperItpackTest); REGISTER_TEST(itkFEMLinearSystemWrapperVNLTest); REGISTER_TEST(itkFEMLinearSystemWrapperDenseVNLTest); //REGISTER_TEST( itkFEMBar2DTest ); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: output.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2004-08-02 17:02:56 $ * * 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 SC_OUTPUT_HXX #define SC_OUTPUT_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef _FRACT_HXX //autogen #include <tools/fract.hxx> #endif class Rectangle; class Font; class OutputDevice; class Window; class EditEngine; class ScDocument; class ScBaseCell; class ScPatternAttr; class SvxMarginItem; class SdrObject; class SdrOle2Obj; struct RowInfo; struct ScTableInfo; class ScTabViewShell; class SvInPlaceObjectRef; class ScPageBreakData; class FmFormView; // --------------------------------------------------------------------------- #define SC_SCENARIO_HSPACE 60 #define SC_SCENARIO_VSPACE 50 // --------------------------------------------------------------------------- #define SC_OBJECTS_NONE 0 #define SC_OBJECTS_DRAWING 1 #define SC_OBJECTS_OLE 2 #define SC_OBJECTS_CHARTS 4 #define SC_OBJECTS_ALL ( SC_OBJECTS_DRAWING | SC_OBJECTS_OLE | SC_OBJECTS_CHARTS ) enum ScOutputType { OUTTYPE_WINDOW, OUTTYPE_PRINTER }; class ScOutputData { friend class ScDrawStringsVars; private: OutputDevice* pDev; // Device OutputDevice* pRefDevice; // printer if used for preview OutputDevice* pFmtDevice; // reference for text formatting ScTableInfo& mrTabInfo; RowInfo* pRowInfo; // Info-Block SCSIZE nArrCount; // belegte Zeilen im Info-Block ScDocument* pDoc; // Dokument SCTAB nTab; // Tabelle long nScrX; // Ausgabe Startpos. (Pixel) long nScrY; long nScrW; // Ausgabe Groesse (Pixel) long nScrH; long nMirrorW; // Visible output width for mirroring (default: nScrW) SCCOL nX1; // Start-/Endkoordinaten SCROW nY1; // ( incl. versteckte ) SCCOL nX2; SCROW nY2; SCCOL nVisX1; // Start-/Endkoordinaten SCROW nVisY1; // ( sichtbarer Bereich ) SCCOL nVisX2; SCROW nVisY2; ScOutputType eType; // Bildschirm/Drucker ... double nPPTX; // Pixel per Twips double nPPTY; // USHORT nZoom; // Zoom-Faktor (Prozent) - fuer GetFont Fraction aZoomX; Fraction aZoomY; SdrObject* pEditObj; // beim Painten auslassen ScTabViewShell* pViewShell; // zum Connecten von sichtbaren Plug-Ins // #114135# FmFormView* pDrawView; // SdrView to paint to BOOL bEditMode; // InPlace editierte Zelle - nicht ausgeben SCCOL nEditCol; SCROW nEditRow; BOOL bMetaFile; // Ausgabe auf Metafile (nicht in Pixeln!) BOOL bSingleGrid; // beim Gitter bChanged auswerten BOOL bPagebreakMode; // Seitenumbruch-Vorschau BOOL bSolidBackground; // weiss statt transparent BOOL bUseStyleColor; BOOL bForceAutoColor; BOOL bSyntaxMode; // Syntax-Highlighting Color* pValueColor; Color* pTextColor; Color* pFormulaColor; Color aGridColor; BOOL bShowNullValues; BOOL bShowFormulas; BOOL bShowSpellErrors; // Spell-Errors in EditObjekten anzeigen BOOL bMarkClipped; BOOL bSnapPixel; BOOL bAnyRotated; // intern BOOL bAnyClipped; // intern BOOL bTabProtected; BYTE nTabTextDirection; // EEHorizontalTextDirection values BOOL bLayoutRTL; // private methods BOOL GetMergeOrigin( SCCOL nX, SCROW nY, SCSIZE nArrY, SCCOL& rOverX, SCROW& rOverY, BOOL bVisRowChanged ); BOOL IsEmptyCellText( RowInfo* pThisRowInfo, SCCOL nX, SCROW nY ); void GetVisibleCell( SCCOL nCol, SCROW nRow, SCTAB nTab, ScBaseCell*& rpCell ); BOOL IsAvailable( SCCOL nX, SCROW nY ); long GetAvailableWidth( SCCOL nX, SCROW nY, long nNeeded ); void GetOutputArea( SCCOL nX, SCSIZE nArrY, long nPosX, long nPosY, SCCOL nCellX, SCROW nCellY, long nNeeded, const ScPatternAttr& rPattern, USHORT nHorJustify, BOOL bCellIsValue, BOOL bBreak, BOOL bOverwrite, Rectangle& rAlignRect, Rectangle& rClipRect, BOOL& rLeftClip, BOOL& rRightClip ); void SetSyntaxColor( Font* pFont, ScBaseCell* pCell ); void SetEditSyntaxColor( EditEngine& rEngine, ScBaseCell* pCell ); void ConnectObject( const SvInPlaceObjectRef& rRef, SdrOle2Obj* pOleObj ); double GetStretch(); void DrawRotatedFrame( const Color* pForceColor ); // pixel public: ScOutputData( OutputDevice* pNewDev, ScOutputType eNewType, ScTableInfo& rTabInfo, ScDocument* pNewDoc, SCTAB nNewTab, long nNewScrX, long nNewScrY, SCCOL nNewX1, SCROW nNewY1, SCCOL nNewX2, SCROW nNewY2, double nPixelPerTwipsX, double nPixelPerTwipsY, const Fraction* pZoomX = NULL, const Fraction* pZoomY = NULL ); ~ScOutputData(); void SetRefDevice( OutputDevice* pRDev ) { pRefDevice = pFmtDevice = pRDev; } void SetFmtDevice( OutputDevice* pRDev ) { pFmtDevice = pRDev; } void SetEditObject( SdrObject* pObj ) { pEditObj = pObj; } void SetViewShell( ScTabViewShell* pSh ) { pViewShell = pSh; } // #114135# void SetDrawView( FmFormView* pNew ) { pDrawView = pNew; } void SetSolidBackground( BOOL bSet ) { bSolidBackground = bSet; } void SetUseStyleColor( BOOL bSet ) { bUseStyleColor = bSet; } void SetEditCell( SCCOL nCol, SCROW nRow ); void SetSyntaxMode( BOOL bNewMode ); void SetMetaFileMode( BOOL bNewMode ); void SetSingleGrid( BOOL bNewMode ); void SetGridColor( const Color& rColor ); void SetMarkClipped( BOOL bSet ); void SetShowNullValues ( BOOL bSet = TRUE ); void SetShowFormulas ( BOOL bSet = TRUE ); void SetShowSpellErrors( BOOL bSet = TRUE ); void SetMirrorWidth( long nNew ); long GetScrW() const { return nScrW; } long GetScrH() const { return nScrH; } void SetSnapPixel( BOOL bSet = TRUE ); void DrawGrid( BOOL bGrid, BOOL bPage ); void DrawStrings( BOOL bPixelToLogic = FALSE ); void DrawBackground(); void DrawShadow(); void DrawExtraShadow(BOOL bLeft, BOOL bTop, BOOL bRight, BOOL bBottom); void DrawFrame(); // with logic MapMode set! void DrawEdit(BOOL bPixelToLogic); void FindRotated(); void DrawRotated(BOOL bPixelToLogic); // logisch void DrawClear(); void DrawPageBorder( SCCOL nStartX, SCROW nStartY, SCCOL nEndX, SCROW nEndY ); // #109985# //void DrawingLayer( USHORT nLayer, USHORT nObjectFlags, long nLogStX, long nLogStY ); void DrawingLayer(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode, long nLogStX, long nLogStY ); // nur Bildschirm: // #109985# //void DrawingSingle( USHORT nLayer, USHORT nObjectFlags, USHORT nDummyFlags ); void DrawingSingle(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode); // #109985# //void DrawSelectiveObjects( USHORT nLayer, const Rectangle& rRect, USHORT nObjectFlags, USHORT nDummyFlags = 0 ); void DrawSelectiveObjects(const sal_uInt16 nLayer, const Rectangle& rRect, const sal_uInt16 nPaintMode); BOOL SetChangedClip(); // FALSE = nix void FindChanged(); void SetPagebreakMode( ScPageBreakData* pPageData ); void DrawMark( Window* pWin ); void DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY, SCCOL nRefEndX, SCROW nRefEndY, const Color& rColor, BOOL bHandle ); void DrawOneChange( SCCOL nRefStartX, SCROW nRefStartY, SCCOL nRefEndX, SCROW nRefEndY, const Color& rColor, USHORT nType ); void DrawChangeTrack(); void DrawClipMarks(); void DrawNoteMarks(); void PrintNoteMarks( const List& rPosList ); // Liste of ScAddress }; #endif <commit_msg>INTEGRATION: CWS pdf01 (1.10.110); FILE MERGED 2004/08/06 19:48:52 pl 1.10.110.2: RESYNC: (1.10-1.11); FILE MERGED 2004/07/22 14:50:39 nn 1.10.110.1: #i31946# handle notes in PDF export<commit_after>/************************************************************************* * * $RCSfile: output.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: hr $ $Date: 2004-09-08 16:04:26 $ * * 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 SC_OUTPUT_HXX #define SC_OUTPUT_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _LIST_HXX //autogen #include <tools/list.hxx> #endif #ifndef _TOOLS_COLOR_HXX #include <tools/color.hxx> #endif #ifndef _FRACT_HXX //autogen #include <tools/fract.hxx> #endif class Rectangle; class Font; class OutputDevice; class Window; class EditEngine; class ScDocument; class ScBaseCell; class ScPatternAttr; class SvxMarginItem; class SdrObject; class SdrOle2Obj; struct RowInfo; struct ScTableInfo; class ScTabViewShell; class SvInPlaceObjectRef; class ScPageBreakData; class FmFormView; // --------------------------------------------------------------------------- #define SC_SCENARIO_HSPACE 60 #define SC_SCENARIO_VSPACE 50 // --------------------------------------------------------------------------- #define SC_OBJECTS_NONE 0 #define SC_OBJECTS_DRAWING 1 #define SC_OBJECTS_OLE 2 #define SC_OBJECTS_CHARTS 4 #define SC_OBJECTS_ALL ( SC_OBJECTS_DRAWING | SC_OBJECTS_OLE | SC_OBJECTS_CHARTS ) enum ScOutputType { OUTTYPE_WINDOW, OUTTYPE_PRINTER }; class ScOutputData { friend class ScDrawStringsVars; private: OutputDevice* pDev; // Device OutputDevice* pRefDevice; // printer if used for preview OutputDevice* pFmtDevice; // reference for text formatting ScTableInfo& mrTabInfo; RowInfo* pRowInfo; // Info-Block SCSIZE nArrCount; // belegte Zeilen im Info-Block ScDocument* pDoc; // Dokument SCTAB nTab; // Tabelle long nScrX; // Ausgabe Startpos. (Pixel) long nScrY; long nScrW; // Ausgabe Groesse (Pixel) long nScrH; long nMirrorW; // Visible output width for mirroring (default: nScrW) SCCOL nX1; // Start-/Endkoordinaten SCROW nY1; // ( incl. versteckte ) SCCOL nX2; SCROW nY2; SCCOL nVisX1; // Start-/Endkoordinaten SCROW nVisY1; // ( sichtbarer Bereich ) SCCOL nVisX2; SCROW nVisY2; ScOutputType eType; // Bildschirm/Drucker ... double nPPTX; // Pixel per Twips double nPPTY; // USHORT nZoom; // Zoom-Faktor (Prozent) - fuer GetFont Fraction aZoomX; Fraction aZoomY; SdrObject* pEditObj; // beim Painten auslassen ScTabViewShell* pViewShell; // zum Connecten von sichtbaren Plug-Ins // #114135# FmFormView* pDrawView; // SdrView to paint to BOOL bEditMode; // InPlace editierte Zelle - nicht ausgeben SCCOL nEditCol; SCROW nEditRow; BOOL bMetaFile; // Ausgabe auf Metafile (nicht in Pixeln!) BOOL bSingleGrid; // beim Gitter bChanged auswerten BOOL bPagebreakMode; // Seitenumbruch-Vorschau BOOL bSolidBackground; // weiss statt transparent BOOL bUseStyleColor; BOOL bForceAutoColor; BOOL bSyntaxMode; // Syntax-Highlighting Color* pValueColor; Color* pTextColor; Color* pFormulaColor; Color aGridColor; BOOL bShowNullValues; BOOL bShowFormulas; BOOL bShowSpellErrors; // Spell-Errors in EditObjekten anzeigen BOOL bMarkClipped; BOOL bSnapPixel; BOOL bAnyRotated; // intern BOOL bAnyClipped; // intern BOOL bTabProtected; BYTE nTabTextDirection; // EEHorizontalTextDirection values BOOL bLayoutRTL; // private methods BOOL GetMergeOrigin( SCCOL nX, SCROW nY, SCSIZE nArrY, SCCOL& rOverX, SCROW& rOverY, BOOL bVisRowChanged ); BOOL IsEmptyCellText( RowInfo* pThisRowInfo, SCCOL nX, SCROW nY ); void GetVisibleCell( SCCOL nCol, SCROW nRow, SCTAB nTab, ScBaseCell*& rpCell ); BOOL IsAvailable( SCCOL nX, SCROW nY ); long GetAvailableWidth( SCCOL nX, SCROW nY, long nNeeded ); void GetOutputArea( SCCOL nX, SCSIZE nArrY, long nPosX, long nPosY, SCCOL nCellX, SCROW nCellY, long nNeeded, const ScPatternAttr& rPattern, USHORT nHorJustify, BOOL bCellIsValue, BOOL bBreak, BOOL bOverwrite, Rectangle& rAlignRect, Rectangle& rClipRect, BOOL& rLeftClip, BOOL& rRightClip ); void SetSyntaxColor( Font* pFont, ScBaseCell* pCell ); void SetEditSyntaxColor( EditEngine& rEngine, ScBaseCell* pCell ); void ConnectObject( const SvInPlaceObjectRef& rRef, SdrOle2Obj* pOleObj ); double GetStretch(); void DrawRotatedFrame( const Color* pForceColor ); // pixel public: ScOutputData( OutputDevice* pNewDev, ScOutputType eNewType, ScTableInfo& rTabInfo, ScDocument* pNewDoc, SCTAB nNewTab, long nNewScrX, long nNewScrY, SCCOL nNewX1, SCROW nNewY1, SCCOL nNewX2, SCROW nNewY2, double nPixelPerTwipsX, double nPixelPerTwipsY, const Fraction* pZoomX = NULL, const Fraction* pZoomY = NULL ); ~ScOutputData(); void SetRefDevice( OutputDevice* pRDev ) { pRefDevice = pFmtDevice = pRDev; } void SetFmtDevice( OutputDevice* pRDev ) { pFmtDevice = pRDev; } void SetEditObject( SdrObject* pObj ) { pEditObj = pObj; } void SetViewShell( ScTabViewShell* pSh ) { pViewShell = pSh; } // #114135# void SetDrawView( FmFormView* pNew ) { pDrawView = pNew; } void SetSolidBackground( BOOL bSet ) { bSolidBackground = bSet; } void SetUseStyleColor( BOOL bSet ) { bUseStyleColor = bSet; } void SetEditCell( SCCOL nCol, SCROW nRow ); void SetSyntaxMode( BOOL bNewMode ); void SetMetaFileMode( BOOL bNewMode ); void SetSingleGrid( BOOL bNewMode ); void SetGridColor( const Color& rColor ); void SetMarkClipped( BOOL bSet ); void SetShowNullValues ( BOOL bSet = TRUE ); void SetShowFormulas ( BOOL bSet = TRUE ); void SetShowSpellErrors( BOOL bSet = TRUE ); void SetMirrorWidth( long nNew ); long GetScrW() const { return nScrW; } long GetScrH() const { return nScrH; } void SetSnapPixel( BOOL bSet = TRUE ); void DrawGrid( BOOL bGrid, BOOL bPage ); void DrawStrings( BOOL bPixelToLogic = FALSE ); void DrawBackground(); void DrawShadow(); void DrawExtraShadow(BOOL bLeft, BOOL bTop, BOOL bRight, BOOL bBottom); void DrawFrame(); // with logic MapMode set! void DrawEdit(BOOL bPixelToLogic); void FindRotated(); void DrawRotated(BOOL bPixelToLogic); // logisch void DrawClear(); void DrawPageBorder( SCCOL nStartX, SCROW nStartY, SCCOL nEndX, SCROW nEndY ); // #109985# //void DrawingLayer( USHORT nLayer, USHORT nObjectFlags, long nLogStX, long nLogStY ); void DrawingLayer(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode, long nLogStX, long nLogStY ); // nur Bildschirm: // #109985# //void DrawingSingle( USHORT nLayer, USHORT nObjectFlags, USHORT nDummyFlags ); void DrawingSingle(const sal_uInt16 nLayer, const sal_uInt16 nPaintMode); // #109985# //void DrawSelectiveObjects( USHORT nLayer, const Rectangle& rRect, USHORT nObjectFlags, USHORT nDummyFlags = 0 ); void DrawSelectiveObjects(const sal_uInt16 nLayer, const Rectangle& rRect, const sal_uInt16 nPaintMode); BOOL SetChangedClip(); // FALSE = nix void FindChanged(); void SetPagebreakMode( ScPageBreakData* pPageData ); void DrawMark( Window* pWin ); void DrawRefMark( SCCOL nRefStartX, SCROW nRefStartY, SCCOL nRefEndX, SCROW nRefEndY, const Color& rColor, BOOL bHandle ); void DrawOneChange( SCCOL nRefStartX, SCROW nRefStartY, SCCOL nRefEndX, SCROW nRefEndY, const Color& rColor, USHORT nType ); void DrawChangeTrack(); void DrawClipMarks(); void DrawNoteMarks(); void AddPDFNotes(); void PrintNoteMarks( const List& rPosList ); // List of ScAddress }; #endif <|endoftext|>
<commit_before>// Copyright © 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. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <cstdio> #include <nix.hpp> #include <nix/NDArray.hpp> #include <queue> #include <random> #include <type_traits> #include <iostream> #include <mutex> #include <condition_variable> #include <thread> #include <stdexcept> /* ************************************ */ class Stopwatch { public: typedef std::chrono::high_resolution_clock::time_point time_point_t; typedef std::chrono::high_resolution_clock clock_t; Stopwatch() : t_start(clock_t::now()) { }; ssize_t ms() { time_point_t t_end = clock_t::now(); ssize_t count = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count(); return count; } private: time_point_t t_start; }; /* ************************************ */ class RndGenBase { public: RndGenBase() : rd(), rd_gen(rd()) { }; protected: std::random_device rd; std::mt19937 rd_gen; }; template<typename T, typename Enable = void> class RndGen { }; template<typename T> class RndGen<T, typename std::enable_if<std::is_floating_point<T>::value >::type> : RndGenBase { public: RndGen() : dis(-1024.0, +1024.0) { }; T operator()(void) { return dis(rd_gen); }; private: std::uniform_real_distribution<T> dis; }; template<typename T> class RndGen<T, typename std::enable_if<std::is_integral<T>::value >::type> : RndGenBase { public: RndGen() : dis(-1024, +1024) { }; T operator()(void) { return dis(rd_gen); }; private: std::uniform_real_distribution<T> dis; }; /* ************************************ */ template<typename T> class BlockGenerator { public: BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { }; std::vector<T> make_block() { std::vector<T> block(blocksize); std::generate(block.begin(), block.end(), std::ref(rnd_gen)); return block; } std::vector<T> next_block() { std::unique_lock<std::mutex> lock(mtx); if (queue.empty()) { cnd.wait(lock, [this]{ return !queue.empty(); }); } std::vector<T> x(std::move(queue.front())); queue.pop(); cnd.notify_all(); return x; } void worker_thread() { while (do_run) { std::unique_lock<std::mutex> lock(mtx); std::vector<T> block = make_block(); if (queue.size() > bufsize) { //wait until there is room cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;}); if (!do_run) { return; } } queue.push(std::move(block)); cnd.notify_all(); } } void start_worker() { workers.emplace_back(&BlockGenerator::worker_thread, this); } ~BlockGenerator() { do_run = false; cnd.notify_all(); for (auto &w : workers) { w.join(); } } double speed_test() { Stopwatch sw; size_t N = 100; size_t iterations = 0; do { Stopwatch inner; for (size_t i = 0; i < N; i++) { std::vector<double> block = next_block(); iterations++; } if (inner.ms() < 100) { N *= 2; } } while (sw.ms() < 1000); ssize_t count = sw.ms(); return iterations * blocksize * sizeof(T) * (1000.0/count) / (1024.0*1024.0); } private: bool do_run = true; size_t blocksize; size_t bufsize; RndGen<T> rnd_gen; std::mutex mtx; std::condition_variable cnd; std::queue<std::vector<T>> queue; std::vector<std::thread> workers; }; class Config { public: Config(nix::DataType data_type, const nix::NDSize &blocksize) : data_type(data_type), block_size(blocksize) { sdim = find_single_dim(); shape = blocksize; shape[sdim] = 0; make_name(); }; size_t find_single_dim() { size_t sdim; bool have_rdim = false; for (size_t i = 0; i < block_size.size(); i ++) { if (block_size[i] == 1) { sdim = i; have_rdim = true; } } if (!have_rdim) { throw std::runtime_error("Could not find singelton dimension"); } return sdim; } nix::DataType dtype() const { return data_type; } const nix::NDSize& size() const { return block_size; } const nix::NDSize& extend() const { return shape; } size_t singleton_dimension() const { return sdim; } const std::string & name() const { return my_name; }; private: void make_name() { std::stringstream s; s << data_type << "@{ "; for (auto x : block_size) { s << x << " "; } s << "}"; my_name = s.str(); } private: const nix::DataType data_type; const nix::NDSize block_size; size_t sdim; nix::NDSize shape; std::string my_name; }; class Benchmark { public: Benchmark(const Config &cfg) : config(cfg) { } const Config & cfg() const { return config; } nix::DataArray openDataArray(nix::Block block) const { const std::string &cfg_name = config.name(); std::vector<nix::DataArray> v = block.dataArrays(nix::util::NameFilter<nix::DataArray>(cfg_name)); if (v.empty()) { return block.createDataArray(cfg_name, "nix.test.da", config.dtype(), config.extend()); } else { return v[0]; } } virtual ~Benchmark() { } virtual double speed_in_mbs() { return count * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/millis) / (1024 * 1024); } template<typename F> ssize_t time_it(F func) { Stopwatch watch; func(); return watch.ms(); } virtual void run(nix::Block block) = 0; virtual std::string id() = 0; protected: double calc_speed_mbs(ssize_t ms, size_t iterations) { return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/ms) / (1024.0*1024.0); } protected: const Config config; size_t count; double millis; }; class GeneratorBenchmark : public Benchmark { public: GeneratorBenchmark(const Config &cfg) : Benchmark(cfg) { }; void run(nix::Block block) override { switch (config.dtype()) { case nix::DataType::Double: test_speed<double>(); break; default: throw std::runtime_error("Unsupported DataType!"); } } template<typename T> void test_speed() { size_t nelms = config.size().nelms(); BlockGenerator<T> generator(nelms, 10); generator.start_worker(); speed = generator.speed_test(); } double speed_in_mbs() override { return speed; } std::string id() override { return "P"; } private: double speed; }; class WriteBenchmark : public Benchmark { public: WriteBenchmark(const Config &cfg) : Benchmark(cfg) { }; void test_write_io(nix::Block block) { nix::DataArray da = openDataArray(block); switch (config.dtype()) { case nix::DataType::Double: do_write_test<double>(da); break; default: throw std::runtime_error("Unsupported DataType!"); } } void run(nix::Block block) override { test_write_io(block); } double speed_in_mbs() override { return speed_write; } std::string id() override { return "W"; } private: template<typename T> void do_write_test(nix::DataArray da) { size_t nelms = config.size().nelms(); BlockGenerator<T> generator(nelms, 10); generator.start_worker(); size_t N = 100; size_t iterations = 0; nix::NDSize pos = {0, 0}; Stopwatch sw; ssize_t ms = 0; do { Stopwatch inner; for (size_t i = 0; i < N; i++) { std::vector<T> block = generator.next_block(); da.dataExtent(config.size() + pos); da.setData(config.dtype(), block.data(), config.size(), pos); pos[config.singleton_dimension()] += 1; iterations++; } if (inner.ms() < 100) { N *= 2; } } while ((ms = sw.ms()) < 3*1000); speed_write = calc_speed_mbs(ms, iterations); } private: double speed_write; }; class ReadBenchmark : public Benchmark { public: ReadBenchmark(const Config &cfg) : Benchmark(cfg) { }; void test_read_io(nix::Block block) { nix::DataArray da = openDataArray(block); speed_read = test_read_io(da); } double test_read_io(nix::DataArray da) { nix::NDArray array(config.dtype(), config.size()); nix::NDSize extend = da.dataExtent(); size_t N = extend[config.singleton_dimension()]; nix::NDSize pos = {0, 0}; ssize_t ms = time_it([this, &da, &N, &pos, &array] { for(size_t i = 0; i < N; i++) { da.getData(config.dtype(), array.data(), config.size(), pos); pos[config.singleton_dimension()] += 1; } }); return calc_speed_mbs(ms, N); } void run(nix::Block block) override { test_read_io(block); } double speed_in_mbs() override { return speed_read; } std::string id() override { return "R"; } private: double speed_read; }; class ReadPolyBenchmark : public ReadBenchmark { public: ReadPolyBenchmark(const Config &cfg) : ReadBenchmark(cfg) { }; void test_read_io_polynom(nix::Block block) { nix::DataArray da = openDataArray(block); da.polynomCoefficients({3, 4, 5, 6}); speed_read_poly = test_read_io(da); } void run(nix::Block block) override { test_read_io_polynom(block); } double speed_in_mbs() override { return speed_read_poly; } std::string id() override { return "P"; } private: double speed_read_poly; }; /* ************************************ */ static std::vector<Config> make_configs() { std::vector<Config> configs; configs.emplace_back(nix::DataType::Double, nix::NDSize{2048, 1}); configs.emplace_back(nix::DataType::Double, nix::NDSize{1, 2048}); return configs; } int main(int argc, char **argv) { nix::File fd = nix::File::open("iospeed.h5", nix::FileMode::Overwrite); nix::Block block = fd.createBlock("speed", "nix.test"); std::vector<Config> configs = make_configs(); std::vector<Benchmark *> marks; std::cout << "Performing generators tests..." << std::endl; for (const Config &cfg : configs) { GeneratorBenchmark *benchmark = new GeneratorBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << "Performing write tests..." << std::endl; for (const Config &cfg : configs) { WriteBenchmark *benchmark = new WriteBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << "Performing read tests..." << std::endl; for (const Config &cfg : configs) { ReadBenchmark *benchmark = new ReadBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << "Performing read (poly) tests..." << std::endl; for (const Config &cfg : configs) { ReadPolyBenchmark *benchmark = new ReadPolyBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << " === Reports ===" << std::endl; for (Benchmark *mark : marks) { std::cout << mark->cfg().name() << ", " << mark->id() << ", " << mark->speed_in_mbs() << " MB/s" << std::endl; delete mark; } return 0; } <commit_msg>[test] Benchmark: use base class recording<commit_after>// Copyright © 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. // // Author: Christian Kellner <kellner@bio.lmu.de> #include <cstdio> #include <nix.hpp> #include <nix/NDArray.hpp> #include <queue> #include <random> #include <type_traits> #include <iostream> #include <mutex> #include <condition_variable> #include <thread> #include <stdexcept> /* ************************************ */ class Stopwatch { public: typedef std::chrono::high_resolution_clock::time_point time_point_t; typedef std::chrono::high_resolution_clock clock_t; Stopwatch() : t_start(clock_t::now()) { }; ssize_t ms() { time_point_t t_end = clock_t::now(); ssize_t count = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count(); return count; } private: time_point_t t_start; }; /* ************************************ */ class RndGenBase { public: RndGenBase() : rd(), rd_gen(rd()) { }; protected: std::random_device rd; std::mt19937 rd_gen; }; template<typename T, typename Enable = void> class RndGen { }; template<typename T> class RndGen<T, typename std::enable_if<std::is_floating_point<T>::value >::type> : RndGenBase { public: RndGen() : dis(-1024.0, +1024.0) { }; T operator()(void) { return dis(rd_gen); }; private: std::uniform_real_distribution<T> dis; }; template<typename T> class RndGen<T, typename std::enable_if<std::is_integral<T>::value >::type> : RndGenBase { public: RndGen() : dis(-1024, +1024) { }; T operator()(void) { return dis(rd_gen); }; private: std::uniform_real_distribution<T> dis; }; /* ************************************ */ template<typename T> class BlockGenerator { public: BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { }; std::vector<T> make_block() { std::vector<T> block(blocksize); std::generate(block.begin(), block.end(), std::ref(rnd_gen)); return block; } std::vector<T> next_block() { std::unique_lock<std::mutex> lock(mtx); if (queue.empty()) { cnd.wait(lock, [this]{ return !queue.empty(); }); } std::vector<T> x(std::move(queue.front())); queue.pop(); cnd.notify_all(); return x; } void worker_thread() { while (do_run) { std::unique_lock<std::mutex> lock(mtx); std::vector<T> block = make_block(); if (queue.size() > bufsize) { //wait until there is room cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;}); if (!do_run) { return; } } queue.push(std::move(block)); cnd.notify_all(); } } void start_worker() { workers.emplace_back(&BlockGenerator::worker_thread, this); } ~BlockGenerator() { do_run = false; cnd.notify_all(); for (auto &w : workers) { w.join(); } } double speed_test() { Stopwatch sw; size_t N = 100; size_t iterations = 0; do { Stopwatch inner; for (size_t i = 0; i < N; i++) { std::vector<double> block = next_block(); iterations++; } if (inner.ms() < 100) { N *= 2; } } while (sw.ms() < 1000); ssize_t count = sw.ms(); return iterations * blocksize * sizeof(T) * (1000.0/count) / (1024.0*1024.0); } private: bool do_run = true; size_t blocksize; size_t bufsize; RndGen<T> rnd_gen; std::mutex mtx; std::condition_variable cnd; std::queue<std::vector<T>> queue; std::vector<std::thread> workers; }; class Config { public: Config(nix::DataType data_type, const nix::NDSize &blocksize) : data_type(data_type), block_size(blocksize) { sdim = find_single_dim(); shape = blocksize; shape[sdim] = 0; make_name(); }; size_t find_single_dim() { size_t sdim; bool have_rdim = false; for (size_t i = 0; i < block_size.size(); i ++) { if (block_size[i] == 1) { sdim = i; have_rdim = true; } } if (!have_rdim) { throw std::runtime_error("Could not find singelton dimension"); } return sdim; } nix::DataType dtype() const { return data_type; } const nix::NDSize& size() const { return block_size; } const nix::NDSize& extend() const { return shape; } size_t singleton_dimension() const { return sdim; } const std::string & name() const { return my_name; }; private: void make_name() { std::stringstream s; s << data_type << "@{ "; for (auto x : block_size) { s << x << " "; } s << "}"; my_name = s.str(); } private: const nix::DataType data_type; const nix::NDSize block_size; size_t sdim; nix::NDSize shape; std::string my_name; }; class Benchmark { public: Benchmark(const Config &cfg) : config(cfg) { } const Config & cfg() const { return config; } nix::DataArray openDataArray(nix::Block block) const { const std::string &cfg_name = config.name(); std::vector<nix::DataArray> v = block.dataArrays(nix::util::NameFilter<nix::DataArray>(cfg_name)); if (v.empty()) { return block.createDataArray(cfg_name, "nix.test.da", config.dtype(), config.extend()); } else { return v[0]; } } virtual ~Benchmark() { } virtual double speed_in_mbs() { return count * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/millis) / (1024 * 1024); } template<typename F> ssize_t time_it(F func) { Stopwatch watch; func(); return watch.ms(); } virtual void run(nix::Block block) = 0; virtual std::string id() = 0; protected: double calc_speed_mbs(ssize_t ms, size_t iterations) { return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/ms) / (1024.0*1024.0); } protected: const Config config; size_t count; double millis; }; class GeneratorBenchmark : public Benchmark { public: GeneratorBenchmark(const Config &cfg) : Benchmark(cfg) { }; void run(nix::Block block) override { switch (config.dtype()) { case nix::DataType::Double: test_speed<double>(); break; default: throw std::runtime_error("Unsupported DataType!"); } } template<typename T> void test_speed() { size_t nelms = config.size().nelms(); BlockGenerator<T> generator(nelms, 10); generator.start_worker(); speed = generator.speed_test(); } double speed_in_mbs() override { return speed; } std::string id() override { return "P"; } private: double speed; }; class WriteBenchmark : public Benchmark { public: WriteBenchmark(const Config &cfg) : Benchmark(cfg) { }; void test_write_io(nix::Block block) { nix::DataArray da = openDataArray(block); switch (config.dtype()) { case nix::DataType::Double: do_write_test<double>(da); break; default: throw std::runtime_error("Unsupported DataType!"); } } void run(nix::Block block) override { test_write_io(block); } std::string id() override { return "W"; } private: template<typename T> void do_write_test(nix::DataArray da) { size_t nelms = config.size().nelms(); BlockGenerator<T> generator(nelms, 10); generator.start_worker(); size_t N = 100; size_t iterations = 0; nix::NDSize pos = {0, 0}; Stopwatch sw; ssize_t ms = 0; do { Stopwatch inner; for (size_t i = 0; i < N; i++) { std::vector<T> block = generator.next_block(); da.dataExtent(config.size() + pos); da.setData(config.dtype(), block.data(), config.size(), pos); pos[config.singleton_dimension()] += 1; iterations++; } if (inner.ms() < 100) { N *= 2; } } while ((ms = sw.ms()) < 3*1000); this->count = iterations; this->millis = ms; } }; class ReadBenchmark : public Benchmark { public: ReadBenchmark(const Config &cfg) : Benchmark(cfg) { }; void test_read_io(nix::Block block) { nix::DataArray da = openDataArray(block); millis = test_read_io(da); } double test_read_io(nix::DataArray da) { nix::NDArray array(config.dtype(), config.size()); nix::NDSize extend = da.dataExtent(); size_t N = extend[config.singleton_dimension()]; nix::NDSize pos = {0, 0}; ssize_t ms = time_it([this, &da, &N, &pos, &array] { for(size_t i = 0; i < N; i++) { da.getData(config.dtype(), array.data(), config.size(), pos); pos[config.singleton_dimension()] += 1; } }); this->count = N; return ms; } void run(nix::Block block) override { test_read_io(block); } std::string id() override { return "R"; } }; class ReadPolyBenchmark : public ReadBenchmark { public: ReadPolyBenchmark(const Config &cfg) : ReadBenchmark(cfg) { }; void test_read_io_polynom(nix::Block block) { nix::DataArray da = openDataArray(block); da.polynomCoefficients({3, 4, 5, 6}); millis = test_read_io(da); } void run(nix::Block block) override { test_read_io_polynom(block); } std::string id() override { return "P"; } }; /* ************************************ */ static std::vector<Config> make_configs() { std::vector<Config> configs; configs.emplace_back(nix::DataType::Double, nix::NDSize{2048, 1}); configs.emplace_back(nix::DataType::Double, nix::NDSize{1, 2048}); return configs; } int main(int argc, char **argv) { nix::File fd = nix::File::open("iospeed.h5", nix::FileMode::Overwrite); nix::Block block = fd.createBlock("speed", "nix.test"); std::vector<Config> configs = make_configs(); std::vector<Benchmark *> marks; std::cout << "Performing generators tests..." << std::endl; for (const Config &cfg : configs) { GeneratorBenchmark *benchmark = new GeneratorBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << "Performing write tests..." << std::endl; for (const Config &cfg : configs) { WriteBenchmark *benchmark = new WriteBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << "Performing read tests..." << std::endl; for (const Config &cfg : configs) { ReadBenchmark *benchmark = new ReadBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << "Performing read (poly) tests..." << std::endl; for (const Config &cfg : configs) { ReadPolyBenchmark *benchmark = new ReadPolyBenchmark(cfg); benchmark->run(block); marks.push_back(benchmark); } std::cout << " === Reports ===" << std::endl; for (Benchmark *mark : marks) { std::cout << mark->cfg().name() << ", " << mark->id() << ", " << mark->speed_in_mbs() << " MB/s" << std::endl; delete mark; } return 0; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/mat/fun/cholesky_decompose.hpp> #include <stan/math/rev/scal/fun/value_of_rec.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/mat/err/check_pos_definite.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/mat/err/check_symmetric.hpp> namespace stan { namespace math { class cholesky_decompose_v_vari : public vari { public: int M_; // A.rows() = A.cols() int block_size_; typedef Eigen::Block<Eigen::MatrixXd> Block_; vari** variRefA_; vari** variRefL_; /* Constructor for cholesky function * * Stores varis for A * Instantiates and stores varis for L * Instantiates and stores dummy vari for * upper triangular part of var result returned * in cholesky_decompose function call * * variRefL aren't on the chainable * autodiff stack, only used for storage * and computation. Note that varis for * L are constructed externally in * cholesky_decompose. * * block_size_ determined using the same * calculation Eigen/LLT.h * * @param matrix A * @param matrix L, cholesky factor of A * */ cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A, const Eigen::Matrix<double, -1, -1>& L_A) : vari(0.0), M_(A.rows()), variRefA_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)), variRefL_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)) { size_t pos = 0; block_size_ = M_/8; block_size_ = (block_size_/16)*16; block_size_ = (std::min)((std::max)(block_size_,8), 128); for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { variRefA_[pos] = A.coeffRef(i, j).vi_; variRefL_[pos] = new vari(L_A.coeffRef(i, j), false); ++pos; } } } inline void symbolic_rev(Block_& L, Block_& Lbar, int size) { using Eigen::Lower; using Eigen::Upper; using Eigen::StrictlyUpper; L.transposeInPlace(); Lbar = (L * Lbar.triangularView<Lower>()).eval(); Lbar.triangularView<StrictlyUpper>() = Lbar.adjoint().triangularView<StrictlyUpper>(); L.triangularView<Upper>().solveInPlace(Lbar); L.triangularView<Upper>().solveInPlace(Lbar.transpose()); } /* Reverse mode differentiation * algorithm refernce: * * Iain Murray: Differentiation of * the Cholesky decomposition, 2016. * * */ virtual void chain() { using Eigen::MatrixXd; using Eigen::Lower; using Eigen::Block; using Eigen::Upper; using Eigen::StrictlyUpper; MatrixXd Lbar(M_, M_); MatrixXd L(M_, M_); Lbar.setZero(); L.setZero(); size_t pos = 0; for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { Lbar.coeffRef(i, j) = variRefL_[pos]->adj_; L.coeffRef(i, j) = variRefL_[pos]->val_; ++pos; } } for (int k = M_; k > 0; k -= block_size_) { int j = std::max(0, k - block_size_); Block_ R = L.block(j, 0, k - j, j); Block_ D = L.block(j, j, k - j, k - j); Block_ B = L.block(k, 0, M_ - k, j); Block_ C = L.block(k, j, M_ - k, k - j); Block_ Rbar = Lbar.block(j, 0, k - j, j); Block_ Dbar = Lbar.block(j, j, k - j, k - j); Block_ Bbar = Lbar.block(k, 0, M_ - k, j); Block_ Cbar = Lbar.block(k, j, M_ - k, k - j); if (Cbar.size() > 0) { Cbar = D.transpose().triangularView<Upper>() .solve(Cbar.transpose()).transpose(); Bbar.noalias() -= Cbar * R; Dbar.noalias() -= Cbar.transpose() * C; } symbolic_rev(D, Dbar, D.rows()); Rbar.noalias() -= Cbar.transpose() * B; Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R; Dbar.diagonal().array() *= 0.5; Dbar.triangularView<StrictlyUpper>().setZero(); } pos = 0; for (size_type j = 0; j < M_; ++j) for (size_type i = j; i < M_; ++i) variRefA_[pos++]->adj_ += Lbar.coeffRef(i,j); } }; /* Reverse mode specialization of * cholesky decomposition * * Internally calls llt rather than using * cholesky_decompose in order * to use selfadjointView<Lower> optimization. * * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky * when possible * * Note chainable stack varis are created * below in Matrix<var, -1, -1> * * @param Matrix A * @return L cholesky factor of A */ inline Eigen::Matrix<var, -1, -1> cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) { check_square("cholesky_decompose", "A", A); check_symmetric("cholesky_decompose", "A", A); Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A)); Eigen::LLT<Eigen::MatrixXd> L_factor = L_A.selfadjointView<Eigen::Lower>().llt(); check_pos_definite("cholesky_decompose", "m", L_factor); L_A = L_factor.matrixL(); // Memory allocated in arena. cholesky_decompose_v_vari *baseVari = new cholesky_decompose_v_vari(A, L_A); vari dummy(0.0, false); Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols()); size_t pos = 0; for (size_type j = 0; j < L.cols(); ++j) { for (size_type i = j; i < L.cols(); ++i) { L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++]; } for (size_type k = 0; k < j; ++k) L.coeffRef(k, j).vi_ = &dummy; } return L; } } } #endif <commit_msg>cpplint<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/mat/fun/cholesky_decompose.hpp> #include <stan/math/rev/scal/fun/value_of_rec.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/mat/err/check_pos_definite.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/mat/err/check_symmetric.hpp> #include <algorithm> namespace stan { namespace math { class cholesky_decompose_v_vari : public vari { public: int M_; // A.rows() = A.cols() int block_size_; typedef Eigen::Block<Eigen::MatrixXd> Block_; vari** variRefA_; vari** variRefL_; /** * Constructor for cholesky function. * * Stores varis for A. * Instantiates and stores varis for L. * Instantiates and stores dummy vari for * upper triangular part of var result returned * in cholesky_decompose function call * * variRefL aren't on the chainable * autodiff stack, only used for storage * and computation. Note that varis for * L are constructed externally in * cholesky_decompose. * * block_size_ determined using the same * calculation Eigen/LLT.h * * @param matrix A * @param matrix L, cholesky factor of A */ cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A, const Eigen::Matrix<double, -1, -1>& L_A) : vari(0.0), M_(A.rows()), variRefA_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)), variRefL_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)) { size_t pos = 0; block_size_ = M_/8; block_size_ = (block_size_/16)*16; block_size_ = (std::min)((std::max)(block_size_, 8), 128); for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { variRefA_[pos] = A.coeffRef(i, j).vi_; variRefL_[pos] = new vari(L_A.coeffRef(i, j), false); ++pos; } } } inline void symbolic_rev(Block_& L, Block_& Lbar, int size) { using Eigen::Lower; using Eigen::Upper; using Eigen::StrictlyUpper; L.transposeInPlace(); Lbar = (L * Lbar.triangularView<Lower>()).eval(); Lbar.triangularView<StrictlyUpper>() = Lbar.adjoint().triangularView<StrictlyUpper>(); L.triangularView<Upper>().solveInPlace(Lbar); L.triangularView<Upper>().solveInPlace(Lbar.transpose()); } /** * Reverse mode differentiation * algorithm refernce: * * Iain Murray: Differentiation of * the Cholesky decomposition, 2016. * */ virtual void chain() { using Eigen::MatrixXd; using Eigen::Lower; using Eigen::Block; using Eigen::Upper; using Eigen::StrictlyUpper; MatrixXd Lbar(M_, M_); MatrixXd L(M_, M_); Lbar.setZero(); L.setZero(); size_t pos = 0; for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { Lbar.coeffRef(i, j) = variRefL_[pos]->adj_; L.coeffRef(i, j) = variRefL_[pos]->val_; ++pos; } } for (int k = M_; k > 0; k -= block_size_) { int j = std::max(0, k - block_size_); Block_ R = L.block(j, 0, k - j, j); Block_ D = L.block(j, j, k - j, k - j); Block_ B = L.block(k, 0, M_ - k, j); Block_ C = L.block(k, j, M_ - k, k - j); Block_ Rbar = Lbar.block(j, 0, k - j, j); Block_ Dbar = Lbar.block(j, j, k - j, k - j); Block_ Bbar = Lbar.block(k, 0, M_ - k, j); Block_ Cbar = Lbar.block(k, j, M_ - k, k - j); if (Cbar.size() > 0) { Cbar = D.transpose().triangularView<Upper>() .solve(Cbar.transpose()).transpose(); Bbar.noalias() -= Cbar * R; Dbar.noalias() -= Cbar.transpose() * C; } symbolic_rev(D, Dbar, D.rows()); Rbar.noalias() -= Cbar.transpose() * B; Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R; Dbar.diagonal().array() *= 0.5; Dbar.triangularView<StrictlyUpper>().setZero(); } pos = 0; for (size_type j = 0; j < M_; ++j) for (size_type i = j; i < M_; ++i) variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j); } }; /** * Reverse mode specialization of * cholesky decomposition * * Internally calls llt rather than using * cholesky_decompose in order * to use selfadjointView<Lower> optimization. * * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky * when possible * * Note chainable stack varis are created * below in Matrix<var, -1, -1> * * @param Matrix A * @return L cholesky factor of A */ inline Eigen::Matrix<var, -1, -1> cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) { check_square("cholesky_decompose", "A", A); check_symmetric("cholesky_decompose", "A", A); Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A)); Eigen::LLT<Eigen::MatrixXd> L_factor = L_A.selfadjointView<Eigen::Lower>().llt(); check_pos_definite("cholesky_decompose", "m", L_factor); L_A = L_factor.matrixL(); // Memory allocated in arena. cholesky_decompose_v_vari *baseVari = new cholesky_decompose_v_vari(A, L_A); vari dummy(0.0, false); Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols()); size_t pos = 0; for (size_type j = 0; j < L.cols(); ++j) { for (size_type i = j; i < L.cols(); ++i) { L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++]; } for (size_type k = 0; k < j; ++k) L.coeffRef(k, j).vi_ = &dummy; } return L; } } } #endif <|endoftext|>
<commit_before>/* Hume Library Version 0.4.3 */ #include "Logger.h" hm::Logger* hm::Logger::instance = NULL; namespace hm { Logger::Logger() : level(DEBUGMSG) { initSession(); } Logger::~Logger() { if(instance != NULL) { endSession(); delete instance; instance = NULL; } } Logger* Logger::getLogger() { if(instance == NULL) instance = new Logger(); return instance; } LogLevel Logger::getLogLevel() { return level; } void Logger::setLogLevel(LogLevel level) { this->level = level; return; } void Logger::log(std::string msg, LogLevel level) { if(getLogger()->level < level) return; Logger* logger = getLogger(); // Output time. time_t raw_time; struct tm local_time; time(&raw_time); local_time = *localtime(&raw_time); logger->ofs << std::to_string(local_time.tm_hour) << ":" << std::to_string(local_time.tm_min) << ":" << std::to_string(local_time.tm_sec) << "\t"; switch(level) { case ERROR: logger->ofs << "ERROR:\t"; break; case WARNING: logger->ofs << "WARNING:\t"; break; case INFO: logger->ofs << "INFO:\t"; break; case DEBUGMSG: logger->ofs << "DEBUGMSG:\t"; break; default: logger->ofs << "UNID'd:\t"; break; } getLogger()->ofs << msg << std::endl; getLogger()->ofs.flush(); return; } void Logger::initSession() { ofs.open("log.txt", std::ios::app | std::ios::out); ofs << "NEW LOGGING SESSION = " << " HUME v" << MAJOR_VERSION << "." << MINOR_VERSION << "." << REVISION_VERSION << " ================" << std::endl; return; } void Logger::endSession() { ofs << "END LOGGING SESSION =============================" << std::endl; ofs.close(); return; } } <commit_msg>Adjust Hume versioning output.<commit_after>/* Hume Library Version 0.4.3 */ #include "Logger.h" hm::Logger* hm::Logger::instance = NULL; namespace hm { Logger::Logger() : level(DEBUGMSG) { initSession(); } Logger::~Logger() { if(instance != NULL) { endSession(); delete instance; instance = NULL; } } Logger* Logger::getLogger() { if(instance == NULL) instance = new Logger(); return instance; } LogLevel Logger::getLogLevel() { return level; } void Logger::setLogLevel(LogLevel level) { this->level = level; return; } void Logger::log(std::string msg, LogLevel level) { if(getLogger()->level < level) return; Logger* logger = getLogger(); // Output time. time_t raw_time; struct tm local_time; time(&raw_time); local_time = *localtime(&raw_time); logger->ofs << std::to_string(local_time.tm_hour) << ":" << std::to_string(local_time.tm_min) << ":" << std::to_string(local_time.tm_sec) << "\t"; switch(level) { case ERROR: logger->ofs << "ERROR:\t"; break; case WARNING: logger->ofs << "WARNING:\t"; break; case INFO: logger->ofs << "INFO:\t"; break; case DEBUGMSG: logger->ofs << "DEBUGMSG:\t"; break; default: logger->ofs << "UNID'd:\t"; break; } getLogger()->ofs << msg << std::endl; getLogger()->ofs.flush(); return; } void Logger::initSession() { ofs.open("log.txt", std::ios::app | std::ios::out); ofs << "NEW LOGGING SESSION ===== " << "HUME v" << MAJOR_VERSION << "." << MINOR_VERSION << "." << REVISION_VERSION << " ===========" << std::endl; return; } void Logger::endSession() { ofs << "END LOGGING SESSION =============================" << std::endl; ofs.close(); return; } } <|endoftext|>
<commit_before>/* Copyright � 2007-2009 Apple Inc. All Rights Reserved. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CARingBuffer.h" #include "CABitOperations.h" #include "CAAutoDisposer.h" #include "CAAtomic.h" #include <stdlib.h> #include <string.h> #include <algorithm> #include <libkern/OSAtomic.h> CARingBuffer::CARingBuffer() : mBuffers(NULL), mNumberChannels(0), mCapacityFrames(0), mCapacityBytes(0) { } CARingBuffer::~CARingBuffer() { Deallocate(); } void CARingBuffer::Allocate(int nChannels, UInt32 bytesPerFrame, UInt32 capacityFrames) { Deallocate(); capacityFrames = NextPowerOfTwo(capacityFrames); mNumberChannels = nChannels; mBytesPerFrame = bytesPerFrame; mCapacityFrames = capacityFrames; mCapacityFramesMask = capacityFrames - 1; mCapacityBytes = bytesPerFrame * capacityFrames; // put everything in one memory allocation, first the pointers, then the deinterleaved channels UInt32 allocSize = (mCapacityBytes + sizeof(Byte *)) * nChannels; Byte *p = (Byte *)CA_malloc(allocSize); memset(p, 0, allocSize); mBuffers = (Byte **)p; p += nChannels * sizeof(Byte *); for (int i = 0; i < nChannels; ++i) { mBuffers[i] = p; p += mCapacityBytes; } for (UInt32 i = 0; i<kGeneralRingTimeBoundsQueueSize; ++i) { mTimeBoundsQueue[i].mStartTime = 0; mTimeBoundsQueue[i].mEndTime = 0; mTimeBoundsQueue[i].mUpdateCounter = 0; } mTimeBoundsQueuePtr = 0; } void CARingBuffer::Deallocate() { if (mBuffers) { free(mBuffers); mBuffers = NULL; } mNumberChannels = 0; mCapacityBytes = 0; mCapacityFrames = 0; } inline void ZeroRange(Byte **buffers, int nchannels, int offset, int nbytes) { while (--nchannels >= 0) { memset(*buffers + offset, 0, nbytes); ++buffers; } } inline void StoreABL(Byte **buffers, int destOffset, const AudioBufferList *abl, int srcOffset, int nbytes) { int nchannels = abl->mNumberBuffers; const AudioBuffer *src = abl->mBuffers; while (--nchannels >= 0) { memcpy(*buffers + destOffset, (Byte *)src->mData + srcOffset, nbytes); ++buffers; ++src; } } inline void FetchABL(AudioBufferList *abl, int destOffset, Byte **buffers, int srcOffset, int nbytes) { int nchannels = abl->mNumberBuffers; AudioBuffer *dest = abl->mBuffers; while (--nchannels >= 0) { memcpy((Byte *)dest->mData + destOffset, *buffers + srcOffset, nbytes); ++buffers; ++dest; } } inline void ZeroABL(AudioBufferList *abl, int destOffset, int nbytes) { int nBuffers = abl->mNumberBuffers; AudioBuffer *dest = abl->mBuffers; while (--nBuffers >= 0) { memset((Byte *)dest->mData + destOffset, 0, nbytes); ++dest; } } CARingBufferError CARingBuffer::Store(const AudioBufferList *abl, UInt32 framesToWrite, SampleTime startWrite) { if(0 == framesToWrite) return noErr; if (framesToWrite > mCapacityFrames) return kCARingBufferError_TooMuch; // too big! SampleTime endWrite = startWrite + framesToWrite; if (startWrite < EndTime()) { // going backwards, throw everything out SetTimeBounds(startWrite, startWrite); } else if (endWrite - StartTime() <= mCapacityFrames) { // the buffer has not yet wrapped and will not need to } else { // advance the start time past the region we are about to overwrite SampleTime newStart = endWrite - mCapacityFrames; // one buffer of time behind where we're writing SampleTime newEnd = std::max(newStart, EndTime()); SetTimeBounds(newStart, newEnd); } // write the new frames Byte **buffers = mBuffers; int nchannels = mNumberChannels; int offset0, offset1, nbytes; SampleTime curEnd = EndTime(); if (startWrite > curEnd) { // we are skipping some samples, so zero the range we are skipping offset0 = FrameOffset(curEnd); offset1 = FrameOffset(startWrite); if (offset0 < offset1) ZeroRange(buffers, nchannels, offset0, offset1 - offset0); else { ZeroRange(buffers, nchannels, offset0, mCapacityBytes - offset0); ZeroRange(buffers, nchannels, 0, offset1); } offset0 = offset1; } else { offset0 = FrameOffset(startWrite); } offset1 = FrameOffset(endWrite); if (offset0 < offset1) StoreABL(buffers, offset0, abl, 0, offset1 - offset0); else { nbytes = mCapacityBytes - offset0; StoreABL(buffers, offset0, abl, 0, nbytes); StoreABL(buffers, 0, abl, nbytes, offset1); } // now update the end time SetTimeBounds(StartTime(), endWrite); return kCARingBufferError_OK; // success } void CARingBuffer::SetTimeBounds(SampleTime startTime, SampleTime endTime) { UInt32 nextPtr = mTimeBoundsQueuePtr + 1; UInt32 index = nextPtr & kGeneralRingTimeBoundsQueueMask; mTimeBoundsQueue[index].mStartTime = startTime; mTimeBoundsQueue[index].mEndTime = endTime; mTimeBoundsQueue[index].mUpdateCounter = nextPtr; CAAtomicCompareAndSwap32Barrier(mTimeBoundsQueuePtr, mTimeBoundsQueuePtr + 1, (SInt32*)&mTimeBoundsQueuePtr); } CARingBufferError CARingBuffer::GetTimeBounds(SampleTime &startTime, SampleTime &endTime) { for (int i=0; i<8; ++i) // fail after a few tries. { UInt32 curPtr = mTimeBoundsQueuePtr; UInt32 index = curPtr & kGeneralRingTimeBoundsQueueMask; CARingBuffer::TimeBounds* bounds = mTimeBoundsQueue + index; startTime = bounds->mStartTime; endTime = bounds->mEndTime; UInt32 newPtr = bounds->mUpdateCounter; if (newPtr == curPtr) return kCARingBufferError_OK; } return kCARingBufferError_CPUOverload; } CARingBufferError CARingBuffer::ClipTimeBounds(SampleTime& startRead, SampleTime& endRead) { SampleTime startTime, endTime; CARingBufferError err = GetTimeBounds(startTime, endTime); if (err) return err; startRead = std::max(startRead, startTime); endRead = std::min(endRead, endTime); endRead = std::max(endRead, startRead); return kCARingBufferError_OK; // success } CARingBufferError CARingBuffer::Fetch(AudioBufferList *abl, UInt32 nFrames, SampleTime startRead) { if(0 == nFrames) return noErr; SampleTime endRead = startRead + nFrames; SampleTime startRead0 = startRead; SampleTime endRead0 = endRead; SampleTime size; CARingBufferError err = ClipTimeBounds(startRead, endRead); if (err) return err; size = endRead - startRead; SInt32 destStartOffset = startRead - startRead0; if (destStartOffset > 0) { ZeroABL(abl, 0, destStartOffset * mBytesPerFrame); } SInt32 destEndSize = endRead0 - endRead; if (destEndSize > 0) { ZeroABL(abl, destStartOffset + size, destEndSize * mBytesPerFrame); } Byte **buffers = mBuffers; int offset0 = FrameOffset(startRead); int offset1 = FrameOffset(endRead); int nbytes; if (offset0 < offset1) { FetchABL(abl, destStartOffset, buffers, offset0, nbytes = offset1 - offset0); } else { nbytes = mCapacityBytes - offset0; FetchABL(abl, destStartOffset, buffers, offset0, nbytes); FetchABL(abl, destStartOffset + nbytes, buffers, 0, offset1); nbytes += offset1; } int nchannels = abl->mNumberBuffers; AudioBuffer *dest = abl->mBuffers; while (--nchannels >= 0) { dest->mDataByteSize = nbytes; dest++; } return noErr; } <commit_msg>Don't crash if the ring buffer doesn't contain the requested audio Apple bug number 9523959<commit_after>/* Copyright � 2007-2009 Apple Inc. All Rights Reserved. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CARingBuffer.h" #include "CABitOperations.h" #include "CAAutoDisposer.h" #include "CAAtomic.h" #include <stdlib.h> #include <string.h> #include <algorithm> #include <libkern/OSAtomic.h> CARingBuffer::CARingBuffer() : mBuffers(NULL), mNumberChannels(0), mCapacityFrames(0), mCapacityBytes(0) { } CARingBuffer::~CARingBuffer() { Deallocate(); } void CARingBuffer::Allocate(int nChannels, UInt32 bytesPerFrame, UInt32 capacityFrames) { Deallocate(); capacityFrames = NextPowerOfTwo(capacityFrames); mNumberChannels = nChannels; mBytesPerFrame = bytesPerFrame; mCapacityFrames = capacityFrames; mCapacityFramesMask = capacityFrames - 1; mCapacityBytes = bytesPerFrame * capacityFrames; // put everything in one memory allocation, first the pointers, then the deinterleaved channels UInt32 allocSize = (mCapacityBytes + sizeof(Byte *)) * nChannels; Byte *p = (Byte *)CA_malloc(allocSize); memset(p, 0, allocSize); mBuffers = (Byte **)p; p += nChannels * sizeof(Byte *); for (int i = 0; i < nChannels; ++i) { mBuffers[i] = p; p += mCapacityBytes; } for (UInt32 i = 0; i<kGeneralRingTimeBoundsQueueSize; ++i) { mTimeBoundsQueue[i].mStartTime = 0; mTimeBoundsQueue[i].mEndTime = 0; mTimeBoundsQueue[i].mUpdateCounter = 0; } mTimeBoundsQueuePtr = 0; } void CARingBuffer::Deallocate() { if (mBuffers) { free(mBuffers); mBuffers = NULL; } mNumberChannels = 0; mCapacityBytes = 0; mCapacityFrames = 0; } inline void ZeroRange(Byte **buffers, int nchannels, int offset, int nbytes) { while (--nchannels >= 0) { memset(*buffers + offset, 0, nbytes); ++buffers; } } inline void StoreABL(Byte **buffers, int destOffset, const AudioBufferList *abl, int srcOffset, int nbytes) { int nchannels = abl->mNumberBuffers; const AudioBuffer *src = abl->mBuffers; while (--nchannels >= 0) { memcpy(*buffers + destOffset, (Byte *)src->mData + srcOffset, nbytes); ++buffers; ++src; } } inline void FetchABL(AudioBufferList *abl, int destOffset, Byte **buffers, int srcOffset, int nbytes) { int nchannels = abl->mNumberBuffers; AudioBuffer *dest = abl->mBuffers; while (--nchannels >= 0) { memcpy((Byte *)dest->mData + destOffset, *buffers + srcOffset, nbytes); ++buffers; ++dest; } } inline void ZeroABL(AudioBufferList *abl, int destOffset, int nbytes) { int nBuffers = abl->mNumberBuffers; AudioBuffer *dest = abl->mBuffers; while (--nBuffers >= 0) { memset((Byte *)dest->mData + destOffset, 0, nbytes); ++dest; } } CARingBufferError CARingBuffer::Store(const AudioBufferList *abl, UInt32 framesToWrite, SampleTime startWrite) { if(0 == framesToWrite) return noErr; if (framesToWrite > mCapacityFrames) return kCARingBufferError_TooMuch; // too big! SampleTime endWrite = startWrite + framesToWrite; if (startWrite < EndTime()) { // going backwards, throw everything out SetTimeBounds(startWrite, startWrite); } else if (endWrite - StartTime() <= mCapacityFrames) { // the buffer has not yet wrapped and will not need to } else { // advance the start time past the region we are about to overwrite SampleTime newStart = endWrite - mCapacityFrames; // one buffer of time behind where we're writing SampleTime newEnd = std::max(newStart, EndTime()); SetTimeBounds(newStart, newEnd); } // write the new frames Byte **buffers = mBuffers; int nchannels = mNumberChannels; int offset0, offset1, nbytes; SampleTime curEnd = EndTime(); if (startWrite > curEnd) { // we are skipping some samples, so zero the range we are skipping offset0 = FrameOffset(curEnd); offset1 = FrameOffset(startWrite); if (offset0 < offset1) ZeroRange(buffers, nchannels, offset0, offset1 - offset0); else { ZeroRange(buffers, nchannels, offset0, mCapacityBytes - offset0); ZeroRange(buffers, nchannels, 0, offset1); } offset0 = offset1; } else { offset0 = FrameOffset(startWrite); } offset1 = FrameOffset(endWrite); if (offset0 < offset1) StoreABL(buffers, offset0, abl, 0, offset1 - offset0); else { nbytes = mCapacityBytes - offset0; StoreABL(buffers, offset0, abl, 0, nbytes); StoreABL(buffers, 0, abl, nbytes, offset1); } // now update the end time SetTimeBounds(StartTime(), endWrite); return kCARingBufferError_OK; // success } void CARingBuffer::SetTimeBounds(SampleTime startTime, SampleTime endTime) { UInt32 nextPtr = mTimeBoundsQueuePtr + 1; UInt32 index = nextPtr & kGeneralRingTimeBoundsQueueMask; mTimeBoundsQueue[index].mStartTime = startTime; mTimeBoundsQueue[index].mEndTime = endTime; mTimeBoundsQueue[index].mUpdateCounter = nextPtr; CAAtomicCompareAndSwap32Barrier(mTimeBoundsQueuePtr, mTimeBoundsQueuePtr + 1, (SInt32*)&mTimeBoundsQueuePtr); } CARingBufferError CARingBuffer::GetTimeBounds(SampleTime &startTime, SampleTime &endTime) { for (int i=0; i<8; ++i) // fail after a few tries. { UInt32 curPtr = mTimeBoundsQueuePtr; UInt32 index = curPtr & kGeneralRingTimeBoundsQueueMask; CARingBuffer::TimeBounds* bounds = mTimeBoundsQueue + index; startTime = bounds->mStartTime; endTime = bounds->mEndTime; UInt32 newPtr = bounds->mUpdateCounter; if (newPtr == curPtr) return kCARingBufferError_OK; } return kCARingBufferError_CPUOverload; } CARingBufferError CARingBuffer::ClipTimeBounds(SampleTime& startRead, SampleTime& endRead) { SampleTime startTime, endTime; CARingBufferError err = GetTimeBounds(startTime, endTime); if (err) return err; startRead = std::max(startRead, startTime); endRead = std::min(endRead, endTime); endRead = std::max(endRead, startRead); return kCARingBufferError_OK; // success } CARingBufferError CARingBuffer::Fetch(AudioBufferList *abl, UInt32 nFrames, SampleTime startRead) { if(0 == nFrames) return noErr; SampleTime endRead = startRead + nFrames; SampleTime startRead0 = startRead; SampleTime endRead0 = endRead; SampleTime size; CARingBufferError err = ClipTimeBounds(startRead, endRead); if (err) return err; size = endRead - startRead; // Don't perform out-of-bounds writes if((startRead - startRead0) > nFrames || (endRead0 - endRead) > nFrames) { ZeroABL(abl, 0, nFrames * mBytesPerFrame); return noErr; } SInt32 destStartOffset = startRead - startRead0; if (destStartOffset > 0) { ZeroABL(abl, 0, destStartOffset * mBytesPerFrame); } SInt32 destEndSize = endRead0 - endRead; if (destEndSize > 0) { ZeroABL(abl, destStartOffset + size, destEndSize * mBytesPerFrame); } Byte **buffers = mBuffers; int offset0 = FrameOffset(startRead); int offset1 = FrameOffset(endRead); int nbytes; if (offset0 < offset1) { FetchABL(abl, destStartOffset, buffers, offset0, nbytes = offset1 - offset0); } else { nbytes = mCapacityBytes - offset0; FetchABL(abl, destStartOffset, buffers, offset0, nbytes); FetchABL(abl, destStartOffset + nbytes, buffers, 0, offset1); nbytes += offset1; } int nchannels = abl->mNumberBuffers; AudioBuffer *dest = abl->mBuffers; while (--nchannels >= 0) { dest->mDataByteSize = nbytes; dest++; } return noErr; } <|endoftext|>
<commit_before>/** * Copyright 2018 Robot Garden, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "wheelencoder.h" #include <FastGPIO.h> #include <EnableInterrupt.h> static const long MIN_CHANGE_TIME = 1000; // 1000us = 1ms is minimum time between ticks. static volatile long left_ticks = 0; static volatile long right_ticks = 0; static volatile int last_left_state; static volatile long last_left_time; static volatile int last_right_state; static volatile long last_right_time; static const signed char ENC_STATES [] = { 0, // 00 -> 00 1, // 00 -> 01 -1, // 00 -> 10 0, // 00 -> 11 (shouldn't happen) -1, // 01 -> 00 0, // 01 -> 01 0, // 01 -> 10 (shouldn't happen) 1, // 01 -> 11 1, // 10 -> 00 0, // 10 -> 01 (shouldn't happen) 0, // 10 -> 10 -1, // 10 -> 11 0, // 11 -> 00 (shouldn't happen) -1, // 11 -> 01 1, // 11 -> 10 0 // 11 -> 11 }; static void updateTicks(volatile long &ticks, volatile int &last_state, volatile long &last_time, int new_state) { long new_time = micros(); if (new_time-last_time > MIN_CHANGE_TIME) { ticks += ENC_STATES[last_state<<2 | new_state]; last_state = new_state; last_time = new_time; } } // Update the left encoder when either encoder pin changes. static void leftISR() { int new_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh()<<1 | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh(); updateTicks(left_ticks, last_left_state, last_left_time, new_state); } // Update the encoder when the right A pin changes. static void rightISR() { int new_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh()<<1 | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh(); updateTicks(right_ticks, last_right_state, last_right_time, new_state); } /** * */ void initWheelEncoder() { FastGPIO::Pin<LEFT_ENCODER_PIN_A>::setInputPulledUp(); FastGPIO::Pin<LEFT_ENCODER_PIN_B>::setInputPulledUp(); FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::setInputPulledUp(); FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::setInputPulledUp(); enableInterrupt(LEFT_ENCODER_PIN_A, leftISR, CHANGE); enableInterrupt(LEFT_ENCODER_PIN_B, leftISR, CHANGE); enableInterrupt(RIGHT_ENCODER_PIN_A, rightISR, CHANGE); enableInterrupt(RIGHT_ENCODER_PIN_B, rightISR, CHANGE); resetEncoders(); } /* Wrap the encoder reading function */ double readTicks(int i) { if (i == LEFT_ENCODER) { return left_ticks; } else { return right_ticks; } } /* Wrap the encoder reset function */ void resetEncoder(int i) { if (i == LEFT_ENCODER) { left_ticks = 0; last_left_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh()<<1 | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh(); last_left_time = micros(); } else { right_ticks = 0; last_right_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh()<<1 | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh(); last_right_time = micros(); } } void resetEncoders() { resetEncoder(LEFT_ENCODER); resetEncoder(RIGHT_ENCODER); } <commit_msg>Fix detection of wheel direction<commit_after>/** * Copyright 2018 Robot Garden, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include "wheelencoder.h" #include <FastGPIO.h> #include <EnableInterrupt.h> static const long MIN_CHANGE_TIME = 1000; // 1000us = 1ms is minimum time between ticks. static volatile long left_ticks = 0; static volatile long right_ticks = 0; static volatile int last_left_state; static volatile long last_left_time; static volatile int last_right_state; static volatile long last_right_time; // Encodes how much to increment the ticks based on the last state and the new state. // The states are encoded as "B<<1 | A" for the A & B interrupt pins. // Indices into the array are: // last_state<<2 | new_state // The commend next to each value shows "last_state -> new_state". static const signed char ENC_STATES [] = { 0, // 00 -> 00 1, // 00 -> 01 -1, // 00 -> 10 0, // 00 -> 11 (shouldn't happen) -1, // 01 -> 00 0, // 01 -> 01 0, // 01 -> 10 (shouldn't happen) 1, // 01 -> 11 1, // 10 -> 00 0, // 10 -> 01 (shouldn't happen) 0, // 10 -> 10 -1, // 10 -> 11 0, // 11 -> 00 (shouldn't happen) -1, // 11 -> 01 1, // 11 -> 10 0 // 11 -> 11 }; static void updateTicks(volatile long &ticks, volatile int &last_state, volatile long &last_time, int new_state) { long new_time = micros(); if (new_time-last_time > MIN_CHANGE_TIME) { ticks += ENC_STATES[last_state<<2 | new_state]; last_state = new_state; last_time = new_time; } } // Update the left encoder when either encoder pin changes. static void leftISR() { int new_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh() | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh()<<1; updateTicks(left_ticks, last_left_state, last_left_time, new_state); } // Update the encoder when the right A pin changes. static void rightISR() { int new_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh() | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh()<<1; updateTicks(right_ticks, last_right_state, last_right_time, new_state); } /** * */ void initWheelEncoder() { FastGPIO::Pin<LEFT_ENCODER_PIN_A>::setInputPulledUp(); FastGPIO::Pin<LEFT_ENCODER_PIN_B>::setInputPulledUp(); FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::setInputPulledUp(); FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::setInputPulledUp(); enableInterrupt(LEFT_ENCODER_PIN_A, leftISR, CHANGE); enableInterrupt(LEFT_ENCODER_PIN_B, leftISR, CHANGE); enableInterrupt(RIGHT_ENCODER_PIN_A, rightISR, CHANGE); enableInterrupt(RIGHT_ENCODER_PIN_B, rightISR, CHANGE); resetEncoders(); } /* Wrap the encoder reading function */ double readTicks(int i) { if (i == LEFT_ENCODER) { return left_ticks; } else { return right_ticks; } } /* Wrap the encoder reset function */ void resetEncoder(int i) { if (i == LEFT_ENCODER) { left_ticks = 0; last_left_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh()<<1 | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh(); last_left_time = micros(); } else { right_ticks = 0; last_right_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh()<<1 | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh(); last_right_time = micros(); } } void resetEncoders() { resetEncoder(LEFT_ENCODER); resetEncoder(RIGHT_ENCODER); } <|endoftext|>
<commit_before>// Copyright (c) 2013, 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 "TestBlock.hpp" #include <nix/util/util.hpp> #include <nix/valid/validate.hpp> #include <nix/Exception.hpp> #include <ctime> using namespace std; using namespace nix; using namespace valid; void TestBlock::setUp() { startup_time = time(NULL); file = File::open("test_block.h5", FileMode::Overwrite); section = file.createSection("foo_section", "metadata"); block = file.createBlock("block_one", "dataset"); block_other = file.createBlock("block_two", "dataset"); block_null = nix::none; } void TestBlock::tearDown() { file.close(); } void TestBlock::testValidate() { valid::Result result = validate(block); CPPUNIT_ASSERT(result.getErrors().size() == 0); CPPUNIT_ASSERT(result.getWarnings().size() == 0); } void TestBlock::testId() { CPPUNIT_ASSERT(block.id().size() == 36); } void TestBlock::testName() { CPPUNIT_ASSERT(block.name() == "block_one"); } void TestBlock::testType() { CPPUNIT_ASSERT(block.type() == "dataset"); string typ = util::createId(); block.type(typ); CPPUNIT_ASSERT(block.type() == typ); } void TestBlock::testDefinition() { string def = util::createId(); block.definition(def); CPPUNIT_ASSERT(*block.definition() == def); } void TestBlock::testMetadataAccess() { CPPUNIT_ASSERT(!block.metadata()); block.metadata(section); CPPUNIT_ASSERT(block.metadata()); // test none-unsetter block.metadata(none); CPPUNIT_ASSERT(!block.metadata()); // test deleter removing link too block.metadata(section); file.deleteSection(section.id()); CPPUNIT_ASSERT(!block.metadata()); // re-create section section = file.createSection("foo_section", "metadata"); } void TestBlock::testSourceAccess() { vector<string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" }; Source s; CPPUNIT_ASSERT_THROW(block.hasSource(s), std::runtime_error); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); CPPUNIT_ASSERT(!block.hasSource("invalid_id")); vector<string> ids; for (const auto &name : names) { Source src = block.createSource(name, "channel"); CPPUNIT_ASSERT(src.name() == name); CPPUNIT_ASSERT(block.hasSource(name)); CPPUNIT_ASSERT(block.hasSource(src)); ids.push_back(src.id()); } CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"), DuplicateName); CPPUNIT_ASSERT(block.sourceCount() == names.size()); CPPUNIT_ASSERT(block.sources().size() == names.size()); for (const auto &id : ids) { Source src = block.getSource(id); CPPUNIT_ASSERT(block.hasSource(id) == true); CPPUNIT_ASSERT(src.id() == id); block.deleteSource(id); } s = block.createSource("test", "test"); CPPUNIT_ASSERT(block.sourceCount() == 1); CPPUNIT_ASSERT_NO_THROW(block.deleteSource(s)); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); } void TestBlock::testDataArrayAccess() { vector<string> names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; DataArray data_array, a; CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); vector<string> ids; for (const auto &name : names) { data_array = block.createDataArray(name, "channel", DataType::Double, nix::NDSize({ 0 })); CPPUNIT_ASSERT(data_array.name() == name); CPPUNIT_ASSERT(data_array.type() == "channel"); ids.push_back(data_array.id()); } CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })), DuplicateName); CPPUNIT_ASSERT(block.hasDataArray(data_array)); CPPUNIT_ASSERT_THROW(block.hasDataArray(a), std::runtime_error); CPPUNIT_ASSERT(block.dataArrayCount() == names.size()); CPPUNIT_ASSERT(block.dataArrays().size() == names.size()); for (const auto &name : names) { DataArray da_name = block.getDataArray(name); CPPUNIT_ASSERT(da_name); DataArray da_id = block.getDataArray(da_name.id()); CPPUNIT_ASSERT(da_id); CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name()); } vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel")); CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size()); filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c")); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size()); if (filteredArrays.size() > 0) { boost::optional<std::string> name = filteredArrays[0].name(); CPPUNIT_ASSERT(name && *name == "data_array_c"); } for (auto it = ids.begin(); it != ids.end(); it++) { DataArray data_array = block.getDataArray(*it); CPPUNIT_ASSERT(block.hasDataArray(*it) == true); CPPUNIT_ASSERT(data_array.id() == *it); block.deleteDataArray(*it); } CPPUNIT_ASSERT_THROW(block.deleteDataArray(a), std::runtime_error); CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); } void TestBlock::testTagAccess() { vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; vector<string> array_names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; vector<DataArray> refs; Tag tag, t; for (const auto &name : array_names) { refs.push_back(block.createDataArray(name, "reference", DataType::Double, nix::NDSize({ 0 }))); } CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); CPPUNIT_ASSERT_THROW(block.hasTag(t), std::runtime_error); vector<string> ids; for (auto it = names.begin(); it != names.end(); ++it) { tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4}); tag.references(refs); CPPUNIT_ASSERT(tag.name() == *it); CPPUNIT_ASSERT(block.hasTag(tag)); ids.push_back(tag.id()); } CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}), DuplicateName); CPPUNIT_ASSERT(block.tagCount() == names.size()); CPPUNIT_ASSERT(block.tags().size() == names.size()); for (auto it = ids.begin(); it != ids.end(); ++it) { tag = block.getTag(*it); CPPUNIT_ASSERT(block.hasTag(*it) == true); CPPUNIT_ASSERT(tag.id() == *it); block.deleteTag(*it); } tag = block.createTag("test", "test", {0.0}); CPPUNIT_ASSERT(block.hasTag(tag)); CPPUNIT_ASSERT_NO_THROW(block.deleteTag(tag)); CPPUNIT_ASSERT_THROW(block.deleteTag(t), std::runtime_error); CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); } void TestBlock::testMultiTagAccess() { vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; MultiTag mtag, m; // create a valid positions data array below typedef boost::multi_array<double, 3>::index index; DataArray positions = block.createDataArray("array_one", "testdata", DataType::Double, nix::NDSize({ 3, 4, 2 })); boost::multi_array<double, 3> A(boost::extents[3][4][2]); int values = 0; for(index i = 0; i != 3; ++i) for(index j = 0; j != 4; ++j) for(index k = 0; k != 2; ++k) A[i][j][k] = values++; positions.setData(A); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); CPPUNIT_ASSERT_THROW(block.hasMultiTag(m), std::runtime_error); vector<string> ids; for (auto it = names.begin(); it != names.end(); it++) { mtag = block.createMultiTag(*it, "segment", positions); CPPUNIT_ASSERT(mtag.name() == *it); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); ids.push_back(mtag.id()); } CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions), DuplicateName); CPPUNIT_ASSERT(block.multiTagCount() == names.size()); CPPUNIT_ASSERT(block.multiTags().size() == names.size()); for (auto it = ids.begin(); it != ids.end(); it++) { mtag = block.getMultiTag(*it); CPPUNIT_ASSERT(block.hasMultiTag(*it) == true); CPPUNIT_ASSERT(mtag.id() == *it); block.deleteMultiTag(*it); } mtag = block.createMultiTag("test", "test", positions); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); CPPUNIT_ASSERT_THROW(block.deleteMultiTag(m), std::runtime_error); CPPUNIT_ASSERT_NO_THROW(block.deleteMultiTag(mtag)); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); } void TestBlock::testOperators() { CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); CPPUNIT_ASSERT(block != false); CPPUNIT_ASSERT(block != none); CPPUNIT_ASSERT(block == block); CPPUNIT_ASSERT(block != block_other); block_other = block; CPPUNIT_ASSERT(block == block_other); block_other = none; CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); } void TestBlock::testCreatedAt() { CPPUNIT_ASSERT(block.createdAt() >= startup_time); time_t past_time = time(NULL) - 10000000; block.forceCreatedAt(past_time); CPPUNIT_ASSERT(block.createdAt() == past_time); } void TestBlock::testUpdatedAt() { CPPUNIT_ASSERT(block.updatedAt() >= startup_time); } void TestBlock::testCompare() { string other_name = block_other.name(); string block_name = block.name(); CPPUNIT_ASSERT(block.compare(block) == 0); CPPUNIT_ASSERT(block.compare(block_other) == block_name.compare(other_name)); } <commit_msg>[TestBlock] change Throw asserts checks to expect UninitializedEntity<commit_after>// Copyright (c) 2013, 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 "TestBlock.hpp" #include <nix/util/util.hpp> #include <nix/valid/validate.hpp> #include <nix/Exception.hpp> #include <ctime> using namespace std; using namespace nix; using namespace valid; void TestBlock::setUp() { startup_time = time(NULL); file = File::open("test_block.h5", FileMode::Overwrite); section = file.createSection("foo_section", "metadata"); block = file.createBlock("block_one", "dataset"); block_other = file.createBlock("block_two", "dataset"); block_null = nix::none; } void TestBlock::tearDown() { file.close(); } void TestBlock::testValidate() { valid::Result result = validate(block); CPPUNIT_ASSERT(result.getErrors().size() == 0); CPPUNIT_ASSERT(result.getWarnings().size() == 0); } void TestBlock::testId() { CPPUNIT_ASSERT(block.id().size() == 36); } void TestBlock::testName() { CPPUNIT_ASSERT(block.name() == "block_one"); } void TestBlock::testType() { CPPUNIT_ASSERT(block.type() == "dataset"); string typ = util::createId(); block.type(typ); CPPUNIT_ASSERT(block.type() == typ); } void TestBlock::testDefinition() { string def = util::createId(); block.definition(def); CPPUNIT_ASSERT(*block.definition() == def); } void TestBlock::testMetadataAccess() { CPPUNIT_ASSERT(!block.metadata()); block.metadata(section); CPPUNIT_ASSERT(block.metadata()); // test none-unsetter block.metadata(none); CPPUNIT_ASSERT(!block.metadata()); // test deleter removing link too block.metadata(section); file.deleteSection(section.id()); CPPUNIT_ASSERT(!block.metadata()); // re-create section section = file.createSection("foo_section", "metadata"); } void TestBlock::testSourceAccess() { vector<string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" }; Source s; CPPUNIT_ASSERT_THROW(block.hasSource(s), UninitializedEntity); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); CPPUNIT_ASSERT(!block.hasSource("invalid_id")); vector<string> ids; for (const auto &name : names) { Source src = block.createSource(name, "channel"); CPPUNIT_ASSERT(src.name() == name); CPPUNIT_ASSERT(block.hasSource(name)); CPPUNIT_ASSERT(block.hasSource(src)); ids.push_back(src.id()); } CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"), DuplicateName); CPPUNIT_ASSERT(block.sourceCount() == names.size()); CPPUNIT_ASSERT(block.sources().size() == names.size()); for (const auto &id : ids) { Source src = block.getSource(id); CPPUNIT_ASSERT(block.hasSource(id) == true); CPPUNIT_ASSERT(src.id() == id); block.deleteSource(id); } s = block.createSource("test", "test"); CPPUNIT_ASSERT(block.sourceCount() == 1); CPPUNIT_ASSERT_NO_THROW(block.deleteSource(s)); CPPUNIT_ASSERT(block.sourceCount() == 0); CPPUNIT_ASSERT(block.sources().size() == 0); CPPUNIT_ASSERT(block.getSource("invalid_id") == false); } void TestBlock::testDataArrayAccess() { vector<string> names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; DataArray data_array, a; CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); vector<string> ids; for (const auto &name : names) { data_array = block.createDataArray(name, "channel", DataType::Double, nix::NDSize({ 0 })); CPPUNIT_ASSERT(data_array.name() == name); CPPUNIT_ASSERT(data_array.type() == "channel"); ids.push_back(data_array.id()); } CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })), DuplicateName); CPPUNIT_ASSERT(block.hasDataArray(data_array)); CPPUNIT_ASSERT_THROW(block.hasDataArray(a), UninitializedEntity); CPPUNIT_ASSERT(block.dataArrayCount() == names.size()); CPPUNIT_ASSERT(block.dataArrays().size() == names.size()); for (const auto &name : names) { DataArray da_name = block.getDataArray(name); CPPUNIT_ASSERT(da_name); DataArray da_id = block.getDataArray(da_name.id()); CPPUNIT_ASSERT(da_id); CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name()); } vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel")); CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size()); filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c")); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size()); if (filteredArrays.size() > 0) { boost::optional<std::string> name = filteredArrays[0].name(); CPPUNIT_ASSERT(name && *name == "data_array_c"); } for (auto it = ids.begin(); it != ids.end(); it++) { DataArray data_array = block.getDataArray(*it); CPPUNIT_ASSERT(block.hasDataArray(*it) == true); CPPUNIT_ASSERT(data_array.id() == *it); block.deleteDataArray(*it); } CPPUNIT_ASSERT_THROW(block.deleteDataArray(a), UninitializedEntity); CPPUNIT_ASSERT(block.dataArrayCount() == 0); CPPUNIT_ASSERT(block.dataArrays().size() == 0); CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false); } void TestBlock::testTagAccess() { vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; vector<string> array_names = { "data_array_a", "data_array_b", "data_array_c", "data_array_d", "data_array_e" }; vector<DataArray> refs; Tag tag, t; for (const auto &name : array_names) { refs.push_back(block.createDataArray(name, "reference", DataType::Double, nix::NDSize({ 0 }))); } CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); CPPUNIT_ASSERT_THROW(block.hasTag(t), UninitializedEntity); vector<string> ids; for (auto it = names.begin(); it != names.end(); ++it) { tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4}); tag.references(refs); CPPUNIT_ASSERT(tag.name() == *it); CPPUNIT_ASSERT(block.hasTag(tag)); ids.push_back(tag.id()); } CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}), DuplicateName); CPPUNIT_ASSERT(block.tagCount() == names.size()); CPPUNIT_ASSERT(block.tags().size() == names.size()); for (auto it = ids.begin(); it != ids.end(); ++it) { tag = block.getTag(*it); CPPUNIT_ASSERT(block.hasTag(*it) == true); CPPUNIT_ASSERT(tag.id() == *it); block.deleteTag(*it); } tag = block.createTag("test", "test", {0.0}); CPPUNIT_ASSERT(block.hasTag(tag)); CPPUNIT_ASSERT_NO_THROW(block.deleteTag(tag)); CPPUNIT_ASSERT_THROW(block.deleteTag(t), UninitializedEntity); CPPUNIT_ASSERT(block.tagCount() == 0); CPPUNIT_ASSERT(block.tags().size() == 0); CPPUNIT_ASSERT(block.getTag("invalid_id") == false); } void TestBlock::testMultiTagAccess() { vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" }; MultiTag mtag, m; // create a valid positions data array below typedef boost::multi_array<double, 3>::index index; DataArray positions = block.createDataArray("array_one", "testdata", DataType::Double, nix::NDSize({ 3, 4, 2 })); boost::multi_array<double, 3> A(boost::extents[3][4][2]); int values = 0; for(index i = 0; i != 3; ++i) for(index j = 0; j != 4; ++j) for(index k = 0; k != 2; ++k) A[i][j][k] = values++; positions.setData(A); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); CPPUNIT_ASSERT_THROW(block.hasMultiTag(m), UninitializedEntity); vector<string> ids; for (auto it = names.begin(); it != names.end(); it++) { mtag = block.createMultiTag(*it, "segment", positions); CPPUNIT_ASSERT(mtag.name() == *it); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); ids.push_back(mtag.id()); } CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions), DuplicateName); CPPUNIT_ASSERT(block.multiTagCount() == names.size()); CPPUNIT_ASSERT(block.multiTags().size() == names.size()); for (auto it = ids.begin(); it != ids.end(); it++) { mtag = block.getMultiTag(*it); CPPUNIT_ASSERT(block.hasMultiTag(*it) == true); CPPUNIT_ASSERT(mtag.id() == *it); block.deleteMultiTag(*it); } mtag = block.createMultiTag("test", "test", positions); CPPUNIT_ASSERT(block.hasMultiTag(mtag)); CPPUNIT_ASSERT_THROW(block.deleteMultiTag(m), UninitializedEntity); CPPUNIT_ASSERT_NO_THROW(block.deleteMultiTag(mtag)); CPPUNIT_ASSERT(block.multiTagCount() == 0); CPPUNIT_ASSERT(block.multiTags().size() == 0); CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false); } void TestBlock::testOperators() { CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); CPPUNIT_ASSERT(block != false); CPPUNIT_ASSERT(block != none); CPPUNIT_ASSERT(block == block); CPPUNIT_ASSERT(block != block_other); block_other = block; CPPUNIT_ASSERT(block == block_other); block_other = none; CPPUNIT_ASSERT(block_null == false); CPPUNIT_ASSERT(block_null == none); } void TestBlock::testCreatedAt() { CPPUNIT_ASSERT(block.createdAt() >= startup_time); time_t past_time = time(NULL) - 10000000; block.forceCreatedAt(past_time); CPPUNIT_ASSERT(block.createdAt() == past_time); } void TestBlock::testUpdatedAt() { CPPUNIT_ASSERT(block.updatedAt() >= startup_time); } void TestBlock::testCompare() { string other_name = block_other.name(); string block_name = block.name(); CPPUNIT_ASSERT(block.compare(block) == 0); CPPUNIT_ASSERT(block.compare(block_other) == block_name.compare(other_name)); } <|endoftext|>
<commit_before>// Qubit teleporation circuit simulator // Source: ./examples/circuits/noisy_teleport_qubit_circuit.cpp #include <iostream> #include "qpp.h" int main() { using namespace qpp; std::cout << ">> Qubit noisy teleportation quantum circuit simulation\n\n"; // quantum circuit with 3 qubits and 2 classical bits QCircuit qc{3, 2}; // set the qubit 0 to a random state cmat U = randU(2); // apply the gate U with name randU to qubit 0 qc.gate(U, 0, "randU"); // set the MES between qubits 1 and 2 qc.gate(gt.H, 1); qc.CTRL(gt.X, 1, 2); // perform the Bell measurement between qubits 0 and 1 qc.CTRL(gt.X, 0, 1); qc.gate(gt.H, 0); qc.measureZ(0, 0); qc.measureZ(1, 1); // apply the classical controls qc.cCTRL(gt.X, 1, 2); qc.cCTRL(gt.Z, 0, 2); // initialize the noisy quantum engine with an amplitude damping noise model // and a quantum circuit; in C++17 you can make use of the class template // argument deduction rules to simply write // QNoisyEngine qNoisyEngine{qc, QubitAmplitudeDampingNoise{0.99}}; QNoisyEngine<QubitAmplitudeDampingNoise> qNoisyEngine{ qc, QubitAmplitudeDampingNoise{0.99}}; // display the quantum circuit std::cout << ">> BEGIN CIRCUIT\n"; std::cout << qNoisyEngine.get_circuit() << '\n'; std::cout << ">> END CIRCUIT\n\n"; // execute the circuit for (auto&& step : qc) qNoisyEngine.execute(step); // display the measurement statistics std::cout << ">> BEGIN AFTER RUNNING\n"; std::cout << qNoisyEngine << '\n'; std::cout << ">> END AFTER RUNNING\n\n"; // verify how successful the teleportation was ket psi_initial = U * 0_ket; ket psi_final = qNoisyEngine.get_psi(); std::cout << ">> Initial state:\n"; std::cout << disp(psi_initial) << '\n'; std::cout << ">> Teleported state:\n"; std::cout << disp(psi_final) << '\n'; std::cout << ">> Norm difference: " << norm(psi_final - psi_initial) << '\n'; } <commit_msg>commit<commit_after>// Qubit teleporation circuit simulator // Source: ./examples/circuits/noisy_teleport_qubit_circuit.cpp #include <iostream> #include "qpp.h" int main() { using namespace qpp; std::cout << ">> Qubit noisy teleportation quantum circuit simulation\n\n"; // quantum circuit with 3 qubits and 2 classical bits QCircuit qc{3, 2}; // set the qubit 0 to a random state cmat U = randU(2); // apply the gate U with name randU to qubit 0 qc.gate(U, 0, "randU"); // set the MES between qubits 1 and 2 qc.gate(gt.H, 1); qc.CTRL(gt.X, 1, 2); // perform the Bell measurement between qubits 0 and 1 qc.CTRL(gt.X, 0, 1); qc.gate(gt.H, 0); qc.measureZ(0, 0); qc.measureZ(1, 1); // apply the classical controls qc.cCTRL(gt.X, 1, 2); qc.cCTRL(gt.Z, 0, 2); // initialize the noisy quantum engine with an amplitude damping noise model // and a quantum circuit; in C++17 you can make use of the class template // argument deduction rules to simply write // QNoisyEngine noisy_engine{qc, QubitAmplitudeDampingNoise{0.99}}; QNoisyEngine<QubitAmplitudeDampingNoise> noisy_engine{ qc, QubitAmplitudeDampingNoise{0.99}}; // display the quantum circuit std::cout << ">> BEGIN CIRCUIT\n"; std::cout << noisy_engine.get_circuit() << '\n'; std::cout << ">> END CIRCUIT\n\n"; // execute the circuit for (auto&& step : qc) noisy_engine.execute(step); // display the measurement statistics std::cout << ">> BEGIN AFTER RUNNING\n"; std::cout << noisy_engine << '\n'; std::cout << ">> END AFTER RUNNING\n\n"; // verify how successful the teleportation was ket psi_initial = U * 0_ket; ket psi_final = noisy_engine.get_psi(); std::cout << ">> Initial state:\n"; std::cout << disp(psi_initial) << '\n'; std::cout << ">> Teleported state:\n"; std::cout << disp(psi_final) << '\n'; std::cout << ">> Norm difference: " << norm(psi_final - psi_initial) << '\n'; } <|endoftext|>
<commit_before>#include "commands.h" #include "Workspace.h" #include <busyUtils/busyUtils.h> #include <iostream> using namespace busy; namespace commands { void cleanAll() { utils::rm("./build", true); utils::mkdir("./build"); //!TODO reset lastCompileTime auto dirs = utils::listDirs(".busy", true); for (auto d : dirs) { utils::rm(".busy/" + d, true); } auto files = utils::listFiles(".busy", false); for (auto f : files) { if (f != "workspace.bin") { utils::rm(".busy/" + f, false); } } std::cout << "clean all done" << std::endl; } } <commit_msg>cleanall now cleans all<commit_after>#include "commands.h" #include "Workspace.h" #include <busyUtils/busyUtils.h> #include <iostream> using namespace busy; namespace commands { void cleanAll() { utils::rm("./build", true); utils::mkdir("./build"); utils::rm(".busy", true, true); std::cout << "clean all done" << std::endl; } } <|endoftext|>
<commit_before>#include "Application.h" #include "MainMenuScene.h" #include "SceneManager.h" LRESULT WINAPI fakeWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { Application* app = reinterpret_cast<Application*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (app != nullptr) { return app->WindowProc(hWnd, Msg, wParam, lParam); } else { return DefWindowProc(hWnd, Msg, wParam, lParam); } } Application::Application() :_renderer(), _handle() { } Application::~Application() { } int Application::run(HINSTANCE hInstance, const int& nCmdShow) { WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = "WND"; wc.hInstance = hInstance; wc.lpfnWndProc = fakeWindowProc; wc.hCursor = LoadCursor(hInstance, IDC_ARROW); int ret = RegisterClassEx(&wc); RECT wndRect; wndRect.right = 500; wndRect.bottom = 500; BOOL b = AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, FALSE); assert(b); _handle = CreateWindowEx(0, "WND", "15 PUZZLE", WS_OVERLAPPEDWINDOW, 0, 0, wndRect.right, wndRect.bottom, nullptr, nullptr, hInstance, nullptr); _renderer.init(_handle, 500, 500); SceneManager::getSingleton().setActiveScene(new MainMenuScene(&_renderer)); ShowWindow(_handle, nCmdShow); MSG msg = {0}; size_t frameCounter = 0; SetWindowLongPtr(_handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this)); while(true) { if (PeekMessage(&msg, _handle, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_QUIT) { break; } } else { SceneManager& sceneMgr = SceneManager::getSingleton(); sceneMgr.update(); if (frameCounter == 10) { sceneMgr.getActiveScene()->update(); frameCounter = 0; } sceneMgr.getActiveScene()->render(); ++frameCounter; } } ret = UnregisterClass("WND", hInstance); return 0; } LRESULT WINAPI Application::WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch(Msg) { case WM_SIZE: { uint32_t width = LOWORD(lParam); uint32_t height = HIWORD(lParam); _renderer.resize(width, height); } return 0; default: return DefWindowProc(hWnd, Msg, wParam, lParam); } } void Application::Shutdown() { PostQuitMessage(0); }<commit_msg>In case using close window button(X) application continue working in background mode<commit_after>#include "Application.h" #include "MainMenuScene.h" #include "SceneManager.h" LRESULT WINAPI fakeWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { Application* app = reinterpret_cast<Application*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (app != nullptr) { return app->WindowProc(hWnd, Msg, wParam, lParam); } else { return DefWindowProc(hWnd, Msg, wParam, lParam); } } Application::Application() :_renderer(), _handle() { } Application::~Application() { } int Application::run(HINSTANCE hInstance, const int& nCmdShow) { WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpszClassName = "WND"; wc.hInstance = hInstance; wc.lpfnWndProc = fakeWindowProc; wc.hCursor = LoadCursor(hInstance, IDC_ARROW); int ret = RegisterClassEx(&wc); RECT wndRect; wndRect.right = 500; wndRect.bottom = 500; BOOL b = AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, FALSE); assert(b); _handle = CreateWindowEx(0, "WND", "15 PUZZLE", WS_OVERLAPPEDWINDOW, 0, 0, wndRect.right, wndRect.bottom, nullptr, nullptr, hInstance, nullptr); _renderer.init(_handle, 500, 500); SceneManager::getSingleton().setActiveScene(new MainMenuScene(&_renderer)); ShowWindow(_handle, nCmdShow); MSG msg = {0}; size_t frameCounter = 0; SetWindowLongPtr(_handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this)); while(true) { if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_QUIT) { break; } } else { SceneManager& sceneMgr = SceneManager::getSingleton(); sceneMgr.update(); if (frameCounter == 10) { sceneMgr.getActiveScene()->update(); frameCounter = 0; } sceneMgr.getActiveScene()->render(); ++frameCounter; } } ret = UnregisterClass("WND", hInstance); return 0; } LRESULT WINAPI Application::WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { switch(Msg) { case WM_SIZE: { uint32_t width = LOWORD(lParam); uint32_t height = HIWORD(lParam); _renderer.resize(width, height); } return 0L; case WM_DESTROY: { PostQuitMessage(0); } return 0L; default: return DefWindowProc(hWnd, Msg, wParam, lParam); } } void Application::Shutdown() { PostQuitMessage(0); } <|endoftext|>
<commit_before>#include <fstream> #include <future> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <set> #include <boost/algorithm/string/predicate.hpp> #include <cryptopp/adler32.h> #include <cryptopp/filters.h> #include <cryptopp/hex.h> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <gumbo.h> #include <uriparser/Uri.h> #include "csd.hpp" using namespace std; using namespace CryptoPP; class UriParseFailure : public runtime_error { public: UriParseFailure(int error_code) : runtime_error("uri parsing error code: " + to_string(error_code)) { } }; class Uri { // FIXME: pick a sane lib here and package it where needed // sane looking libs: // - https://github.com/datacratic/google-url // - https://github.com/chmike/CxxUrl // FIXME: this implemenation with uriparser probably doesn't support // anything other than most common formats. // Unsupported includes: explicit ports, file access, probably // localized uris public: const string str; Uri(string url) : str(url) { state.uri = &uri; if (uriParseUriA(&state, str.c_str()) != URI_SUCCESS) { throw new UriParseFailure(state.errorCode); } scheme = _mkstr(uri.scheme); port = _mkstr(uri.portText); host = _mkstr(uri.hostText); is_abs = uri.absolutePath; is_prl = boost::starts_with(str, "//"); uriFreeUriMembersA(&uri); } string get_absolute(string base) { return get_absolute(Uri(base)); } /** * \param[in] base uri of the page to resolve relative links against. * eg.: Uri("foo").get_absolute("http://example.com") == "http://example.com/foo" */ string get_absolute(const Uri base) const { // TODO: cover by unit tests if (!scheme.empty()) { return str; } if (!is_abs) { return base.str + "/" + str; } if (is_prl) { // FIXME: scheme-relative-file-URL not implemented. // The path-absolute-non-Windows-file-URL doesn't make sense // to me. return base.scheme + ":" + str; } if (host.empty()) { return base.scheme + "://" + base.host + str; } throw runtime_error("Failed to absolutize " + str + " with base " + base.str); } private: UriParserStateA state; UriUriA uri; string host; string port; string scheme; /** * True if the URL starts with a '/', false otherwise (including * starting with scheme) */ bool is_abs; /** * True if uri is Protocol Relative Link * https://url.spec.whatwg.org/#syntax-url-scheme-relative */ bool is_prl; string _mkstr(UriTextRangeA x) const { if (x.first == NULL || x.afterLast == NULL) { return string(); // TODO: maybe check if only one of those is NULL? } return string(x.first, x.afterLast); } }; /** * Parses file references from HTML document. * TODO: Probably can handle only HTML5 now. */ class Html5Parser { public: /** URLs parsed from the given document */ set<string> urls; /** * \param[in] page HTML document * \param[in] url URL of the document. Used for resolving relative * links. */ Html5Parser (const string page, string url) : base_url(url) { output = gumbo_parse(page.c_str()); parse(output->root); gumbo_destroy_output(&kGumboDefaultOptions, output); munge(); } private: GumboOutput* output; string base_url; vector<Uri> relative_urls; /** * Parses raw urls from the given HTML document */ void parse(GumboNode *node) { if (node->type != GUMBO_NODE_ELEMENT) { return; } parse_a(node); // TODO: Add more tag parsers GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { parse(static_cast<GumboNode*>(children->data[i])); } } void parse_a(GumboNode *node) { if (node->v.element.tag != GUMBO_TAG_A) { return; } GumboAttribute* href; if ((href = gumbo_get_attribute(&node->v.element.attributes, "href"))) { relative_urls.push_back(Uri(href->value)); } } /** * Resolves the relative links to absolute. * */ void munge() { for (const auto &x : relative_urls) { urls.insert(x.get_absolute(Uri(base_url))); } } }; File::File(const string url) : url(url), data(File::download_url(url)), adler32hex(File::mk_hash()) {} string File::mk_hash() const { Adler32 hash; string hex; StringSource ss(data, true, new HashFilter(hash, new HexEncoder(new StringSink( hex )) ) ); return hex; } bool File::size_cmp(File x, File y) { return x.data.size() < y.data.size(); } string File::download_url(const string url) const { stringstream out; curlpp::Cleanup cleanup; curlpp::Easy request; request.setOpt(new curlpp::options::Url(url)); request.setOpt(new curlpp::options::WriteStream(&out)); request.setOpt(new curlpp::options::FollowLocation(true)); request.perform(); return out.str(); } OriginUrl::OriginUrl(const string url) : File(url), urls(parse_urls()) {} vector<File> OriginUrl::fetch_files() { vector<future<File>> futures; for (const auto &x : urls) { auto f(std::async([] (string url) -> File { return File(url); }, x)); futures.push_back(move(f)); } vector<File> files; while (futures.size() > 0 ) { for(unsigned int i = 0; i < futures.size(); i++) { if (futures[i].valid()) { files.push_back(futures[i].get()); futures.erase(futures.begin() + i); } } } return files; } set<string> OriginUrl::parse_urls() const { return Html5Parser(data, url).urls; } <commit_msg>Add more tag parsers<commit_after>#include <fstream> #include <future> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <set> #include <boost/algorithm/string/predicate.hpp> #include <cryptopp/adler32.h> #include <cryptopp/filters.h> #include <cryptopp/hex.h> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <gumbo.h> #include <uriparser/Uri.h> #include "csd.hpp" using namespace std; using namespace CryptoPP; class UriParseFailure : public runtime_error { public: UriParseFailure(int error_code) : runtime_error("uri parsing error code: " + to_string(error_code)) { } }; class Uri { // FIXME: pick a sane lib here and package it where needed // sane looking libs: // - https://github.com/datacratic/google-url // - https://github.com/chmike/CxxUrl // FIXME: this implemenation with uriparser probably doesn't support // anything other than most common formats. // Unsupported includes: explicit ports, file access, probably // localized uris public: const string str; Uri(string url) : str(url) { state.uri = &uri; if (uriParseUriA(&state, str.c_str()) != URI_SUCCESS) { throw new UriParseFailure(state.errorCode); } scheme = _mkstr(uri.scheme); port = _mkstr(uri.portText); host = _mkstr(uri.hostText); is_abs = uri.absolutePath; is_prl = boost::starts_with(str, "//"); uriFreeUriMembersA(&uri); } string get_absolute(string base) { return get_absolute(Uri(base)); } /** * \param[in] base uri of the page to resolve relative links against. * eg.: Uri("foo").get_absolute("http://example.com") == "http://example.com/foo" */ string get_absolute(const Uri base) const { // TODO: cover by unit tests if (!scheme.empty()) { return str; } if (!is_abs) { return base.str + "/" + str; } if (is_prl) { // FIXME: scheme-relative-file-URL not implemented. // The path-absolute-non-Windows-file-URL doesn't make sense // to me. return base.scheme + ":" + str; } if (host.empty()) { return base.scheme + "://" + base.host + str; } throw runtime_error("Failed to absolutize " + str + " with base " + base.str); } private: UriParserStateA state; UriUriA uri; string host; string port; string scheme; /** * True if the URL starts with a '/', false otherwise (including * starting with scheme) */ bool is_abs; /** * True if uri is Protocol Relative Link * https://url.spec.whatwg.org/#syntax-url-scheme-relative */ bool is_prl; string _mkstr(UriTextRangeA x) const { if (x.first == NULL || x.afterLast == NULL) { return string(); // TODO: maybe check if only one of those is NULL? } return string(x.first, x.afterLast); } }; /** * Parses file references from HTML document. * TODO: Probably can handle only HTML5 now. */ class Html5Parser { public: /** URLs parsed from the given document */ set<string> urls; /** * \param[in] page HTML document * \param[in] url URL of the document. Used for resolving relative * links. */ Html5Parser (const string page, string url) : base_url(url) { output = gumbo_parse(page.c_str()); parse(output->root); gumbo_destroy_output(&kGumboDefaultOptions, output); munge(); } private: GumboOutput* output; string base_url; vector<Uri> relative_urls; /** * Parses raw urls from the given HTML document */ void parse(GumboNode *node) { if (node->type != GUMBO_NODE_ELEMENT) { return; } parse_attr(node, GUMBO_TAG_A, "href"); parse_attr(node, GUMBO_TAG_IMG, "src"); parse_attr(node, GUMBO_TAG_LINK, "href"); parse_attr(node, GUMBO_TAG_SCRIPT, "src"); // TODO: probably missed some, check with html5 spec // FIXME: handle base tag GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { parse(static_cast<GumboNode*>(children->data[i])); } } void parse_attr(GumboNode *node, const GumboTag t, const char* attr) { if (node->v.element.tag != t) { return; } GumboAttribute* gattr; if ((gattr = gumbo_get_attribute(&node->v.element.attributes, attr))) { relative_urls.push_back(Uri(gattr->value)); } } /** * Resolves the relative links to absolute. * */ void munge() { for (const auto &x : relative_urls) { urls.insert(x.get_absolute(Uri(base_url))); } } }; File::File(const string url) : url(url), data(File::download_url(url)), adler32hex(File::mk_hash()) {} string File::mk_hash() const { Adler32 hash; string hex; StringSource ss(data, true, new HashFilter(hash, new HexEncoder(new StringSink( hex )) ) ); return hex; } bool File::size_cmp(File x, File y) { return x.data.size() < y.data.size(); } string File::download_url(const string url) const { stringstream out; curlpp::Cleanup cleanup; curlpp::Easy request; request.setOpt(new curlpp::options::Url(url)); request.setOpt(new curlpp::options::WriteStream(&out)); request.setOpt(new curlpp::options::FollowLocation(true)); request.perform(); return out.str(); } OriginUrl::OriginUrl(const string url) : File(url), urls(parse_urls()) {} vector<File> OriginUrl::fetch_files() { vector<future<File>> futures; for (const auto &x : urls) { auto f(std::async([] (string url) -> File { return File(url); }, x)); futures.push_back(move(f)); } vector<File> files; while (futures.size() > 0 ) { for(unsigned int i = 0; i < futures.size(); i++) { if (futures[i].valid()) { files.push_back(futures[i].get()); futures.erase(futures.begin() + i); } } } return files; } set<string> OriginUrl::parse_urls() const { return Html5Parser(data, url).urls; } <|endoftext|>
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL. // Simple example using GLUT to create an OpenGL window and OSG for rendering. // Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp #include <osgGA/SimpleViewer> #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> #include <SDL.h> #include <SDL_events.h> #include <iostream> int main( int argc, char **argv ) { if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // init SDL if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); exit(1); } atexit(SDL_Quit); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } unsigned int windowWidth = 1280; unsigned int windowHeight = 1024; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // set up the surface to render to SDL_Surface* screen = SDL_SetVideoMode(windowWidth, windowHeight, 32, SDL_OPENGL | SDL_FULLSCREEN | SDL_RESIZABLE); if ( screen == NULL ) { std::cerr<<"Unable to set "<<windowWidth<<"x"<<windowHeight<<" video: %s\n"<< SDL_GetError()<<std::endl; exit(1); } SDL_EnableUNICODE(1); osgGA::SimpleViewer viewer; viewer.setSceneData(loadedModel.get()); viewer.setCameraManipulator(new osgGA::TrackballManipulator); viewer.getEventQueue()->windowResize(0, 0, windowWidth, windowHeight ); bool done = false; while( !done ) { SDL_Event event; while ( SDL_PollEvent(&event) ) { switch (event.type) { case SDL_MOUSEMOTION: viewer.getEventQueue()->mouseMotion(event.motion.x, event.motion.y); break; case SDL_MOUSEBUTTONDOWN: viewer.getEventQueue()->mouseButtonPress(event.button.x, event.button.y, event.button.button); break; case SDL_MOUSEBUTTONUP: viewer.getEventQueue()->mouseButtonRelease(event.button.x, event.button.y, event.button.button); break; case SDL_KEYUP: viewer.getEventQueue()->keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode); if (event.key.keysym.sym==SDLK_ESCAPE) done = true; if (event.key.keysym.sym=='f') SDL_WM_ToggleFullScreen(screen); break; case SDL_KEYDOWN: viewer.getEventQueue()->keyPress( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode); break; case SDL_VIDEORESIZE: { viewer.getEventQueue()->windowResize(0, 0, event.resize.w, event.resize.h ); std::cout<<"event.resize.w="<<event.resize.w<<" event.resize.h="<<event.resize.h<<std::endl; break; } case SDL_QUIT: done = true; } } if (done) continue; // draw the new frame viewer.frame(); // Swap Buffers SDL_GL_SwapBuffers(); } return 0; } /*EOF*/ <commit_msg>Refactored the SDL example so that the event conversion in done is a seperate method.<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL. // Simple example using GLUT to create an OpenGL window and OSG for rendering. // Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp #include <osgGA/SimpleViewer> #include <osgGA/TrackballManipulator> #include <osgDB/ReadFile> #include <SDL.h> #include <SDL_events.h> #include <iostream> bool convertEvent(SDL_Event& event, osgGA::EventQueue& eventQueue) { switch (event.type) { case SDL_MOUSEMOTION: eventQueue.mouseMotion(event.motion.x, event.motion.y); return true; case SDL_MOUSEBUTTONDOWN: eventQueue.mouseButtonPress(event.button.x, event.button.y, event.button.button); return true; case SDL_MOUSEBUTTONUP: eventQueue.mouseButtonRelease(event.button.x, event.button.y, event.button.button); return true; case SDL_KEYUP: eventQueue.keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode); return true; case SDL_KEYDOWN: eventQueue.keyPress( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode); return true; case SDL_VIDEORESIZE: eventQueue.windowResize(0, 0, event.resize.w, event.resize.h ); return true; default: break; } return false; } int main( int argc, char **argv ) { if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // init SDL if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); exit(1); } atexit(SDL_Quit); // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } unsigned int windowWidth = 1280; unsigned int windowHeight = 1024; SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 ); SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 ); SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 ); // set up the surface to render to SDL_Surface* screen = SDL_SetVideoMode(windowWidth, windowHeight, 32, SDL_OPENGL | SDL_FULLSCREEN | SDL_RESIZABLE); if ( screen == NULL ) { std::cerr<<"Unable to set "<<windowWidth<<"x"<<windowHeight<<" video: %s\n"<< SDL_GetError()<<std::endl; exit(1); } SDL_EnableUNICODE(1); osgGA::SimpleViewer viewer; viewer.setSceneData(loadedModel.get()); viewer.setCameraManipulator(new osgGA::TrackballManipulator); viewer.getEventQueue()->windowResize(0, 0, windowWidth, windowHeight ); bool done = false; while( !done ) { SDL_Event event; while ( SDL_PollEvent(&event) ) { // pass the SDL event into the viewers event queue convertEvent(event, *viewer.getEventQueue()); switch (event.type) { case SDL_KEYUP: if (event.key.keysym.sym==SDLK_ESCAPE) done = true; if (event.key.keysym.sym=='f') SDL_WM_ToggleFullScreen(screen); break; case SDL_QUIT: done = true; } } if (done) continue; // draw the new frame viewer.frame(); // Swap Buffers SDL_GL_SwapBuffers(); } return 0; } /*EOF*/ <|endoftext|>
<commit_before>#include "../SDP_Solver.hxx" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> // We use binary checkpointing because writing text does not write all // of the necessary digits. The GMP library sets it to one less than // required for round-tripping. template <typename T> void write_local_blocks(const T &t, boost::filesystem::ofstream &checkpoint_stream) { El::BigFloat zero(0); const size_t serialized_size(zero.SerializedSize()); std::vector<uint8_t> local_array(serialized_size); for(auto &block : t.blocks) { int64_t local_height(block.LocalHeight()), local_width(block.LocalWidth()); checkpoint_stream.write(reinterpret_cast<char *>(&local_height), sizeof(int64_t)); checkpoint_stream.write(reinterpret_cast<char *>(&local_width), sizeof(int64_t)); for(int64_t row = 0; row < local_height; ++row) for(int64_t column = 0; column < local_width; ++column) { block.GetLocal(row, column).Serialize(local_array.data()); checkpoint_stream.write( reinterpret_cast<char *>(local_array.data()), std::streamsize(local_array.size())); } } } void SDP_Solver::save_checkpoint( const boost::filesystem::path &checkpoint_directory, const Verbosity &verbosity) const { boost::filesystem::path checkpoint_filename( checkpoint_directory / ("checkpoint." + std::to_string(El::mpi::Rank()))); if(!exists(checkpoint_directory)) { create_directories(checkpoint_directory); } else if(!is_directory(checkpoint_directory)) { throw std::runtime_error("Checkpoint directory '" + checkpoint_directory.string() + "'already exists, but is not a directory"); } if(exists(checkpoint_directory / checkpoint_filename)) { if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0) { std::cout << "Backing up checkpoint\n"; } boost::filesystem::path backup_filename(checkpoint_filename.string() + ".bk"); remove(backup_filename); rename(checkpoint_filename, backup_filename); } boost::filesystem::ofstream checkpoint_stream(checkpoint_filename); if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0) { std::cout << "Saving checkpoint to : " << checkpoint_directory << '\n'; } write_local_blocks(x, checkpoint_stream); write_local_blocks(X, checkpoint_stream); write_local_blocks(y, checkpoint_stream); write_local_blocks(Y, checkpoint_stream); } <commit_msg>Add retry logic if the filesystem is not working properly.<commit_after>#include "../SDP_Solver.hxx" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> // We use binary checkpointing because writing text does not write all // of the necessary digits. The GMP library sets it to one less than // required for round-tripping. template <typename T> void write_local_blocks(const T &t, boost::filesystem::ofstream &checkpoint_stream) { El::BigFloat zero(0); const size_t serialized_size(zero.SerializedSize()); std::vector<uint8_t> local_array(serialized_size); for(auto &block : t.blocks) { int64_t local_height(block.LocalHeight()), local_width(block.LocalWidth()); checkpoint_stream.write(reinterpret_cast<char *>(&local_height), sizeof(int64_t)); checkpoint_stream.write(reinterpret_cast<char *>(&local_width), sizeof(int64_t)); for(int64_t row = 0; row < local_height; ++row) for(int64_t column = 0; column < local_width; ++column) { block.GetLocal(row, column).Serialize(local_array.data()); checkpoint_stream.write( reinterpret_cast<char *>(local_array.data()), std::streamsize(local_array.size())); } } } void SDP_Solver::save_checkpoint( const boost::filesystem::path &checkpoint_directory, const Verbosity &verbosity) const { boost::filesystem::path checkpoint_filename( checkpoint_directory / ("checkpoint." + std::to_string(El::mpi::Rank()))); if(!exists(checkpoint_directory)) { create_directories(checkpoint_directory); } else if(!is_directory(checkpoint_directory)) { throw std::runtime_error("Checkpoint directory '" + checkpoint_directory.string() + "'already exists, but is not a directory"); } if(exists(checkpoint_directory / checkpoint_filename)) { if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0) { std::cout << "Backing up checkpoint\n"; } boost::filesystem::path backup_filename(checkpoint_filename.string() + ".bk"); remove(backup_filename); rename(checkpoint_filename, backup_filename); } const size_t max_retries(10); bool wrote_successfully(false); for(size_t attempt=0; attempt<max_retries && !wrote_successfully; ++attempt) { boost::filesystem::ofstream checkpoint_stream(checkpoint_filename); if(verbosity >= Verbosity::regular && El::mpi::Rank() == 0) { std::cout << "Saving checkpoint to : " << checkpoint_directory << '\n'; } write_local_blocks(x, checkpoint_stream); write_local_blocks(X, checkpoint_stream); write_local_blocks(y, checkpoint_stream); write_local_blocks(Y, checkpoint_stream); wrote_successfully=checkpoint_stream.good(); if(!wrote_successfully) { if(attempt+1<max_retries) { std::stringstream ss; ss << "Error writing checkpoint file '" << checkpoint_filename << "'. Retrying " << (attempt+2) << "/" << max_retries << "\n"; std::cerr << ss.str() << std::flush; } else { std::stringstream ss; ss << "Error writing checkpoint file '" << checkpoint_filename << "'. Exceeded max retries.\n"; throw std::runtime_error(ss.str()); } } } } <|endoftext|>
<commit_before>//===- TreeView.cpp - diagtool tool for printing warning flags ------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "DiagTool.h" #include "DiagnosticNames.h" #include "clang/Basic/AllDiagnostics.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/Format.h" #include "llvm/Support/Process.h" DEF_DIAGTOOL("tree", "Show warning flags in a tree view", TreeView) using namespace clang; using namespace diagtool; static bool hasColors(const llvm::raw_ostream &out) { if (&out != &llvm::errs() && &out != &llvm::outs()) return false; return llvm::errs().is_displayed() && llvm::outs().is_displayed(); } class TreePrinter { public: llvm::raw_ostream &out; const bool ShowColors; bool Internal; TreePrinter(llvm::raw_ostream &out) : out(out), ShowColors(hasColors(out)), Internal(false) {} void setColor(llvm::raw_ostream::Colors Color) { if (ShowColors) out << llvm::sys::Process::OutputColor(Color, false, false); } void resetColor() { if (ShowColors) out << llvm::sys::Process::ResetColor(); } static bool isIgnored(unsigned DiagID) { // FIXME: This feels like a hack. static clang::DiagnosticsEngine Diags(new DiagnosticIDs, new DiagnosticOptions); return Diags.isIgnored(DiagID, SourceLocation()); } static bool enabledByDefault(const GroupRecord &Group) { for (const DiagnosticRecord &DR : Group.diagnostics()) { if (isIgnored(DR.DiagID)) return false; } for (const GroupRecord &GR : Group.subgroups()) { if (!enabledByDefault(GR)) return false; } return true; } void printGroup(const GroupRecord &Group, unsigned Indent = 0) { out.indent(Indent * 2); if (enabledByDefault(Group)) setColor(llvm::raw_ostream::GREEN); else setColor(llvm::raw_ostream::YELLOW); out << "-W" << Group.getName() << "\n"; resetColor(); ++Indent; for (const GroupRecord &GR : Group.subgroups()) { printGroup(GR, Indent); } if (Internal) { for (const DiagnosticRecord &DR : Group.diagnostics()) { if (ShowColors && !isIgnored(DR.DiagID)) setColor(llvm::raw_ostream::GREEN); out.indent(Indent * 2); out << DR.getName(); resetColor(); out << "\n"; } } } int showGroup(StringRef RootGroup) { ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups(); if (RootGroup.size() > UINT16_MAX) { llvm::errs() << "No such diagnostic group exists\n"; return 1; } const GroupRecord *Found = llvm::lower_bound(AllGroups, RootGroup); if (Found == AllGroups.end() || Found->getName() != RootGroup) { llvm::errs() << "No such diagnostic group exists\n"; return 1; } printGroup(*Found); return 0; } int showAll() { ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups(); llvm::DenseSet<unsigned> NonRootGroupIDs; for (const GroupRecord &GR : AllGroups) { for (auto SI = GR.subgroup_begin(), SE = GR.subgroup_end(); SI != SE; ++SI) { NonRootGroupIDs.insert((unsigned)SI.getID()); } } assert(NonRootGroupIDs.size() < AllGroups.size()); for (unsigned i = 0, e = AllGroups.size(); i != e; ++i) { if (!NonRootGroupIDs.count(i)) printGroup(AllGroups[i]); } return 0; } void showKey() { if (ShowColors) { out << '\n'; setColor(llvm::raw_ostream::GREEN); out << "GREEN"; resetColor(); out << " = enabled by default\n\n"; } } }; static void printUsage() { llvm::errs() << "Usage: diagtool tree [--internal] [<diagnostic-group>]\n"; } int TreeView::run(unsigned int argc, char **argv, llvm::raw_ostream &out) { // First check our one flag (--flags-only). bool Internal = false; if (argc > 0) { StringRef FirstArg(*argv); if (FirstArg.equals("--internal")) { Internal = true; --argc; ++argv; } } bool ShowAll = false; StringRef RootGroup; switch (argc) { case 0: ShowAll = true; break; case 1: RootGroup = argv[0]; if (RootGroup.startswith("-W")) RootGroup = RootGroup.substr(2); if (RootGroup == "everything") ShowAll = true; // FIXME: Handle other special warning flags, like -pedantic. break; default: printUsage(); return -1; } TreePrinter TP(out); TP.Internal = Internal; TP.showKey(); return ShowAll ? TP.showAll() : TP.showGroup(RootGroup); } <commit_msg>Re-submit r367649: Improve raw_ostream so that you can "write" colors using operator<<<commit_after>//===- TreeView.cpp - diagtool tool for printing warning flags ------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "DiagTool.h" #include "DiagnosticNames.h" #include "clang/Basic/AllDiagnostics.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/Format.h" #include "llvm/Support/Process.h" DEF_DIAGTOOL("tree", "Show warning flags in a tree view", TreeView) using namespace clang; using namespace diagtool; static bool hasColors(const llvm::raw_ostream &out) { if (&out != &llvm::errs() && &out != &llvm::outs()) return false; return llvm::errs().is_displayed() && llvm::outs().is_displayed(); } class TreePrinter { public: llvm::raw_ostream &out; const bool ShowColors; bool Internal; TreePrinter(llvm::raw_ostream &out) : out(out), ShowColors(hasColors(out)), Internal(false) {} void setColor(llvm::raw_ostream::Colors Color) { if (ShowColors) out << llvm::sys::Process::OutputColor(static_cast<char>(Color), false, false); } void resetColor() { if (ShowColors) out << llvm::sys::Process::ResetColor(); } static bool isIgnored(unsigned DiagID) { // FIXME: This feels like a hack. static clang::DiagnosticsEngine Diags(new DiagnosticIDs, new DiagnosticOptions); return Diags.isIgnored(DiagID, SourceLocation()); } static bool enabledByDefault(const GroupRecord &Group) { for (const DiagnosticRecord &DR : Group.diagnostics()) { if (isIgnored(DR.DiagID)) return false; } for (const GroupRecord &GR : Group.subgroups()) { if (!enabledByDefault(GR)) return false; } return true; } void printGroup(const GroupRecord &Group, unsigned Indent = 0) { out.indent(Indent * 2); if (enabledByDefault(Group)) setColor(llvm::raw_ostream::GREEN); else setColor(llvm::raw_ostream::YELLOW); out << "-W" << Group.getName() << "\n"; resetColor(); ++Indent; for (const GroupRecord &GR : Group.subgroups()) { printGroup(GR, Indent); } if (Internal) { for (const DiagnosticRecord &DR : Group.diagnostics()) { if (ShowColors && !isIgnored(DR.DiagID)) setColor(llvm::raw_ostream::GREEN); out.indent(Indent * 2); out << DR.getName(); resetColor(); out << "\n"; } } } int showGroup(StringRef RootGroup) { ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups(); if (RootGroup.size() > UINT16_MAX) { llvm::errs() << "No such diagnostic group exists\n"; return 1; } const GroupRecord *Found = llvm::lower_bound(AllGroups, RootGroup); if (Found == AllGroups.end() || Found->getName() != RootGroup) { llvm::errs() << "No such diagnostic group exists\n"; return 1; } printGroup(*Found); return 0; } int showAll() { ArrayRef<GroupRecord> AllGroups = getDiagnosticGroups(); llvm::DenseSet<unsigned> NonRootGroupIDs; for (const GroupRecord &GR : AllGroups) { for (auto SI = GR.subgroup_begin(), SE = GR.subgroup_end(); SI != SE; ++SI) { NonRootGroupIDs.insert((unsigned)SI.getID()); } } assert(NonRootGroupIDs.size() < AllGroups.size()); for (unsigned i = 0, e = AllGroups.size(); i != e; ++i) { if (!NonRootGroupIDs.count(i)) printGroup(AllGroups[i]); } return 0; } void showKey() { if (ShowColors) { out << '\n'; setColor(llvm::raw_ostream::GREEN); out << "GREEN"; resetColor(); out << " = enabled by default\n\n"; } } }; static void printUsage() { llvm::errs() << "Usage: diagtool tree [--internal] [<diagnostic-group>]\n"; } int TreeView::run(unsigned int argc, char **argv, llvm::raw_ostream &out) { // First check our one flag (--flags-only). bool Internal = false; if (argc > 0) { StringRef FirstArg(*argv); if (FirstArg.equals("--internal")) { Internal = true; --argc; ++argv; } } bool ShowAll = false; StringRef RootGroup; switch (argc) { case 0: ShowAll = true; break; case 1: RootGroup = argv[0]; if (RootGroup.startswith("-W")) RootGroup = RootGroup.substr(2); if (RootGroup == "everything") ShowAll = true; // FIXME: Handle other special warning flags, like -pedantic. break; default: printUsage(); return -1; } TreePrinter TP(out); TP.Internal = Internal; TP.showKey(); return ShowAll ? TP.showAll() : TP.showGroup(RootGroup); } <|endoftext|>
<commit_before>//Foster.cpp //Implements definitions of Foster functionality. //"Bad becomes good" - Tory Foster //josh@mindaptiv.com //includes #include "pch.h" #include "Foster.h" #include <windows.foundation.h> #include <windows.system.h> #include <sysinfoapi.h> //If Visual Studio freaks out about this code someday, add this line back in OR modify your project settings //#pragma comment(lib, "Ws2_32.lib") //Method definitions: //getters unsigned int getFosterMilliseconds(struct cylonStruct tf) { //return return tf.milliseconds; } unsigned int getFosterSeconds(struct cylonStruct tf) { //return return tf.seconds; } unsigned int getFosterMinutes(struct cylonStruct tf) { //return return tf.minutes; } unsigned int getFosterHours(struct cylonStruct tf) { //return return tf.hours; } unsigned int getFosterDay(struct cylonStruct tf) { //return return tf.day; } unsigned int getFosterDate(struct cylonStruct tf) { //return return tf.date; } unsigned int getFosterMonth(struct cylonStruct tf) { //return return tf.month; } unsigned int getFosterYear(struct cylonStruct tf) { //return return tf.year; } long getFosterTimeZone(struct cylonStruct tf) { //return return tf.timeZone; } unsigned int getFosterDST(struct cylonStruct tf) { //return return tf.dst; } std::wstring getFosterTimeZoneName(struct cylonStruct tf) { //return return tf.wTimeZoneName; } std::wstring getFosterUsername(struct cylonStruct tf) { //return return tf.wUsername; } std::wstring getFosterDeviceName(struct cylonStruct tf) { //return return tf.wDeviceName; } unsigned short getFosterArchitecture(struct cylonStruct tf) { //return return tf.architecture; } unsigned short getFosterProcessorLevel(struct cylonStruct tf) { //return return tf.processorLevel; } unsigned long getFosterPageSize(struct cylonStruct tf) { //return return tf.pageSize; } unsigned long getFosterProcessorCount(struct cylonStruct tf) { //return return tf.processorCount; } unsigned long getFosterAllocationGranularity(struct cylonStruct tf) { //return return tf.allocationGranularity; } void* getFosterMinAppAddress(struct cylonStruct tf) { //return return tf.minAppAddress; } void* getFosterMaxAppAddress(struct cylonStruct tf) { //return return tf.maxAppAddress; } std::wstring getFosterPictureType(struct cylonStruct tf) { //return return tf.pictureType; } Windows::Storage::IStorageFile^ getFosterPictureFile(struct cylonStruct tf) { //return return tf.picture; } //end getters //for getting username void produceUsername(struct cylonStruct& tory) { //Variable declaration Platform::String^ managedUsername; Windows::Foundation::IAsyncOperation<Platform::String^>^ operation; const wchar_t* operationDataPointer; std::wstring wideUsername; std::string username; //Retrieve username operation = Windows::System::UserProfile::UserInformation::GetDisplayNameAsync(); while( operation->Status == Windows::Foundation::AsyncStatus::Started) { //WAIT, YO } managedUsername = operation->GetResults(); operation->Close(); //Convert username to std::wstring operationDataPointer = managedUsername->Data(); wideUsername = std::wstring(operationDataPointer); //TODO convert from wstring to string //TODO: check if retrieved username is empty string? (therefore UserInformation::NameAccessAllowed property would be set to false) //Set username tory.wUsername = wideUsername; } //end getDisplayNameAsync //Fills cylonStruct with timezone name, UTC offset bias, and dst flag void produceTimeZone(struct cylonStruct& tory) { //Variable Declaration DWORD tzResult; TIME_ZONE_INFORMATION tzinfo; std::wstring timezoneName; //grab and convert bias tzResult = GetTimeZoneInformation(&tzinfo); //set bias tory.timeZone = tzinfo.Bias; //Check DWORD value if (tzResult == TIME_ZONE_ID_STANDARD) { //standard time tory.dst = 0; } else if (tzResult == TIME_ZONE_ID_DAYLIGHT) { //daylight time tory.dst = 1; } else { //otherwise or invalid ==> shenanigans //"Oh hell! I have to run home and grab my broom!" tory.dst = 2; //value is arbitrary } //end if //grab time zone name std::wstring standardName; //grab name from TimeZoneInformation standardName = tzinfo.StandardName; //place string name into tory tory.wTimeZoneName = standardName; } //end produceBias //Grabs time information and stores it in cylonStruct void produceDateTime(struct cylonStruct& tory) { //Variable declaration SYSTEMTIME st; //init st GetLocalTime(&st); //grab values from SYSTEMTIME tory.milliseconds = st.wMilliseconds; tory.seconds = st.wSecond; tory.minutes = st.wMinute; tory.hours = st.wHour; tory.day = st.wDayOfWeek; tory.date = st.wDay; tory.month = st.wMonth; tory.year = st.wYear; } //end produceDateTime //populates tory's device name void produceDeviceName(struct cylonStruct& tory) { //Variable declaration int result; int size_needed; char hostBuffer[MAX_PATH]; std::string deviceName; WSAData wsa_data; //start WSA WSAStartup(MAKEWORD(1, 1), &wsa_data); //grab result result = gethostname(hostBuffer, MAX_PATH); deviceName = hostBuffer; //check socket errors int error; error = WSAGetLastError(); //cleanup WSA WSACleanup(); //convert string to wstring size_needed = MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), NULL, 0); std::wstring wDeviceName(size_needed, 0); MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), &wDeviceName[0], size_needed); //set device name for tory tory.wDeviceName = wDeviceName; } //end produceDeviceName //for getting processor info void produceProcessorInfo(struct cylonStruct& tf) { //Variable Declaration SYSTEM_INFO sysinfo; unsigned int architecture; //Grab system info GetNativeSystemInfo(&sysinfo); //test int one = 9; one = one * 9; //end test //Convert results into local values //Convert architecture if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { //x64 (AMD or Intel) architecture = 1; } else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM) { //ARM architecture = 2; } else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { //Intel Itanium-based architecture = 3; } else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) { //x86 architecture = 4; } else { //unknown error architecture = 0; } //end if //set tory architecture tf.architecture = architecture; //set tory page size tf.pageSize = (unsigned long)sysinfo.dwPageSize; //set the min and max pointers for apps tf.minAppAddress = (void*)sysinfo.lpMinimumApplicationAddress; tf.maxAppAddress = (void*)sysinfo.lpMaximumApplicationAddress; //set the number of processors tf.processorCount = (unsigned long)sysinfo.dwNumberOfProcessors; //set allocation granularity tf.allocationGranularity = (unsigned long)sysinfo.dwAllocationGranularity; //TODO grab hertz } //end produce processor info //for getting memory info void produceMemoryInfo(struct cylonStruct& tf) { //TODO get memory } //end produceMemoryInfo //for getting account picture void produceAccountPicture(struct cylonStruct& tf) { //variable declaration Windows::System::UserProfile::AccountPictureKind kind = Windows::System::UserProfile::AccountPictureKind::SmallImage; Windows::Storage::IStorageFile^ picture; std::wstring pictureType; const wchar_t* typeDataPointer; //retrieve picture picture = Windows::System::UserProfile::UserInformation::GetAccountPicture(kind); //set picture tf.picture = picture; //convert picture type to wstring typeDataPointer = picture->FileType->Data(); pictureType = std::wstring(typeDataPointer); //set picture type tf.pictureType = pictureType; } //end produceAccountPicture //Constructor //build Tory struct cylonStruct buildTory() { //Variable Declartion struct cylonStruct tory; //username produceUsername(tory); //device name produceDeviceName(tory); //time zone produceTimeZone(tory); //date and time produceDateTime(tory); //processor produceProcessorInfo(tory); //picture produceAccountPicture(tory); //TODO add more host queries //return return tory; } //end build tory<commit_msg>remove debugging code<commit_after>//Foster.cpp //Implements definitions of Foster functionality. //"Bad becomes good" - Tory Foster //josh@mindaptiv.com //includes #include "pch.h" #include "Foster.h" #include <windows.foundation.h> #include <windows.system.h> #include <sysinfoapi.h> //If Visual Studio freaks out about this code someday, add this line back in OR modify your project settings //#pragma comment(lib, "Ws2_32.lib") //Method definitions: //getters unsigned int getFosterMilliseconds(struct cylonStruct tf) { //return return tf.milliseconds; } unsigned int getFosterSeconds(struct cylonStruct tf) { //return return tf.seconds; } unsigned int getFosterMinutes(struct cylonStruct tf) { //return return tf.minutes; } unsigned int getFosterHours(struct cylonStruct tf) { //return return tf.hours; } unsigned int getFosterDay(struct cylonStruct tf) { //return return tf.day; } unsigned int getFosterDate(struct cylonStruct tf) { //return return tf.date; } unsigned int getFosterMonth(struct cylonStruct tf) { //return return tf.month; } unsigned int getFosterYear(struct cylonStruct tf) { //return return tf.year; } long getFosterTimeZone(struct cylonStruct tf) { //return return tf.timeZone; } unsigned int getFosterDST(struct cylonStruct tf) { //return return tf.dst; } std::wstring getFosterTimeZoneName(struct cylonStruct tf) { //return return tf.wTimeZoneName; } std::wstring getFosterUsername(struct cylonStruct tf) { //return return tf.wUsername; } std::wstring getFosterDeviceName(struct cylonStruct tf) { //return return tf.wDeviceName; } unsigned short getFosterArchitecture(struct cylonStruct tf) { //return return tf.architecture; } unsigned short getFosterProcessorLevel(struct cylonStruct tf) { //return return tf.processorLevel; } unsigned long getFosterPageSize(struct cylonStruct tf) { //return return tf.pageSize; } unsigned long getFosterProcessorCount(struct cylonStruct tf) { //return return tf.processorCount; } unsigned long getFosterAllocationGranularity(struct cylonStruct tf) { //return return tf.allocationGranularity; } void* getFosterMinAppAddress(struct cylonStruct tf) { //return return tf.minAppAddress; } void* getFosterMaxAppAddress(struct cylonStruct tf) { //return return tf.maxAppAddress; } std::wstring getFosterPictureType(struct cylonStruct tf) { //return return tf.pictureType; } Windows::Storage::IStorageFile^ getFosterPictureFile(struct cylonStruct tf) { //return return tf.picture; } //end getters //for getting username void produceUsername(struct cylonStruct& tory) { //Variable declaration Platform::String^ managedUsername; Windows::Foundation::IAsyncOperation<Platform::String^>^ operation; const wchar_t* operationDataPointer; std::wstring wideUsername; std::string username; //Retrieve username operation = Windows::System::UserProfile::UserInformation::GetDisplayNameAsync(); while( operation->Status == Windows::Foundation::AsyncStatus::Started) { //WAIT, YO } managedUsername = operation->GetResults(); operation->Close(); //Convert username to std::wstring operationDataPointer = managedUsername->Data(); wideUsername = std::wstring(operationDataPointer); //TODO convert from wstring to string //TODO: check if retrieved username is empty string? (therefore UserInformation::NameAccessAllowed property would be set to false) //Set username tory.wUsername = wideUsername; } //end getDisplayNameAsync //Fills cylonStruct with timezone name, UTC offset bias, and dst flag void produceTimeZone(struct cylonStruct& tory) { //Variable Declaration DWORD tzResult; TIME_ZONE_INFORMATION tzinfo; std::wstring timezoneName; //grab and convert bias tzResult = GetTimeZoneInformation(&tzinfo); //set bias tory.timeZone = tzinfo.Bias; //Check DWORD value if (tzResult == TIME_ZONE_ID_STANDARD) { //standard time tory.dst = 0; } else if (tzResult == TIME_ZONE_ID_DAYLIGHT) { //daylight time tory.dst = 1; } else { //otherwise or invalid ==> shenanigans //"Oh hell! I have to run home and grab my broom!" tory.dst = 2; //value is arbitrary } //end if //grab time zone name std::wstring standardName; //grab name from TimeZoneInformation standardName = tzinfo.StandardName; //place string name into tory tory.wTimeZoneName = standardName; } //end produceBias //Grabs time information and stores it in cylonStruct void produceDateTime(struct cylonStruct& tory) { //Variable declaration SYSTEMTIME st; //init st GetLocalTime(&st); //grab values from SYSTEMTIME tory.milliseconds = st.wMilliseconds; tory.seconds = st.wSecond; tory.minutes = st.wMinute; tory.hours = st.wHour; tory.day = st.wDayOfWeek; tory.date = st.wDay; tory.month = st.wMonth; tory.year = st.wYear; } //end produceDateTime //populates tory's device name void produceDeviceName(struct cylonStruct& tory) { //Variable declaration int result; int size_needed; char hostBuffer[MAX_PATH]; std::string deviceName; WSAData wsa_data; //start WSA WSAStartup(MAKEWORD(1, 1), &wsa_data); //grab result result = gethostname(hostBuffer, MAX_PATH); deviceName = hostBuffer; //check socket errors int error; error = WSAGetLastError(); //cleanup WSA WSACleanup(); //convert string to wstring size_needed = MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), NULL, 0); std::wstring wDeviceName(size_needed, 0); MultiByteToWideChar(CP_UTF8, 0, &deviceName[0], (int)deviceName.size(), &wDeviceName[0], size_needed); //set device name for tory tory.wDeviceName = wDeviceName; } //end produceDeviceName //for getting processor info void produceProcessorInfo(struct cylonStruct& tf) { //Variable Declaration SYSTEM_INFO sysinfo; unsigned int architecture; //Grab system info GetNativeSystemInfo(&sysinfo); //Convert results into local values //Convert architecture if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) { //x64 (AMD or Intel) architecture = 1; } else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM) { //ARM architecture = 2; } else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { //Intel Itanium-based architecture = 3; } else if (sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) { //x86 architecture = 4; } else { //unknown error architecture = 0; } //end if //set tory architecture tf.architecture = architecture; //set tory page size tf.pageSize = (unsigned long)sysinfo.dwPageSize; //set the min and max pointers for apps tf.minAppAddress = (void*)sysinfo.lpMinimumApplicationAddress; tf.maxAppAddress = (void*)sysinfo.lpMaximumApplicationAddress; //set the number of processors tf.processorCount = (unsigned long)sysinfo.dwNumberOfProcessors; //set allocation granularity tf.allocationGranularity = (unsigned long)sysinfo.dwAllocationGranularity; //TODO grab hertz } //end produce processor info //for getting memory info void produceMemoryInfo(struct cylonStruct& tf) { //TODO get memory } //end produceMemoryInfo //for getting account picture void produceAccountPicture(struct cylonStruct& tf) { //variable declaration Windows::System::UserProfile::AccountPictureKind kind = Windows::System::UserProfile::AccountPictureKind::SmallImage; Windows::Storage::IStorageFile^ picture; std::wstring pictureType; const wchar_t* typeDataPointer; //retrieve picture picture = Windows::System::UserProfile::UserInformation::GetAccountPicture(kind); //set picture tf.picture = picture; //convert picture type to wstring typeDataPointer = picture->FileType->Data(); pictureType = std::wstring(typeDataPointer); //set picture type tf.pictureType = pictureType; } //end produceAccountPicture //Constructor //build Tory struct cylonStruct buildTory() { //Variable Declartion struct cylonStruct tory; //username produceUsername(tory); //device name produceDeviceName(tory); //time zone produceTimeZone(tory); //date and time produceDateTime(tory); //processor produceProcessorInfo(tory); //picture produceAccountPicture(tory); //TODO add more host queries //return return tory; } //end build tory<|endoftext|>
<commit_before>//===- tools/dsymutil/CFBundle.cpp - CFBundle helper ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CFBundle.h" #ifdef __APPLE__ #include "llvm/Support/FileSystem.h" #include "llvm/Support/raw_ostream.h" #include <CoreFoundation/CoreFoundation.h> #include <assert.h> #include <glob.h> #include <memory> #endif namespace llvm { namespace dsymutil { #ifdef __APPLE__ /// Deleter that calls CFRelease rather than deleting the pointer. template <typename T> struct CFDeleter { void operator()(T *P) { if (P) ::CFRelease(P); } }; /// This helper owns any CoreFoundation pointer and will call CFRelease() on /// any valid pointer it owns unless that pointer is explicitly released using /// the release() member function. template <typename T> using CFReleaser = std::unique_ptr<typename std::remove_pointer<T>::type, CFDeleter<typename std::remove_pointer<T>::type>>; /// RAII wrapper around CFBundleRef. class CFString : public CFReleaser<CFStringRef> { public: CFString(CFStringRef CFStr = nullptr) : CFReleaser<CFStringRef>(CFStr) {} const char *UTF8(std::string &Str) const { return CFString::UTF8(get(), Str); } CFIndex GetLength() const { if (CFStringRef Str = get()) return CFStringGetLength(Str); return 0; } static const char *UTF8(CFStringRef CFStr, std::string &Str); }; /// Static function that puts a copy of the UTF8 contents of CFStringRef into /// std::string and returns the C string pointer that is contained in the /// std::string when successful, nullptr otherwise. /// /// This allows the std::string parameter to own the extracted string, and also /// allows that string to be returned as a C string pointer that can be used. const char *CFString::UTF8(CFStringRef CFStr, std::string &Str) { if (!CFStr) return nullptr; const CFStringEncoding Encoding = kCFStringEncodingUTF8; CFIndex MaxUTF8StrLength = CFStringGetLength(CFStr); MaxUTF8StrLength = CFStringGetMaximumSizeForEncoding(MaxUTF8StrLength, Encoding); if (MaxUTF8StrLength > 0) { Str.resize(MaxUTF8StrLength); if (!Str.empty() && CFStringGetCString(CFStr, &Str[0], Str.size(), Encoding)) { Str.resize(strlen(Str.c_str())); return Str.c_str(); } } return nullptr; } /// RAII wrapper around CFBundleRef. class CFBundle : public CFReleaser<CFBundleRef> { public: CFBundle(const char *Path = nullptr) : CFReleaser<CFBundleRef>() { if (Path && Path[0]) SetFromPath(Path); } CFBundle(CFURLRef url) : CFReleaser<CFBundleRef>(url ? ::CFBundleCreate(nullptr, url) : nullptr) {} /// Return the bundle identifier. CFStringRef GetIdentifier() const { if (CFBundleRef bundle = get()) return ::CFBundleGetIdentifier(bundle); return nullptr; } /// Return value for key. CFTypeRef GetValueForInfoDictionaryKey(CFStringRef key) const { if (CFBundleRef bundle = get()) return ::CFBundleGetValueForInfoDictionaryKey(bundle, key); return nullptr; } private: /// Update this instance with a new bundle created from the given path. bool SetFromPath(const char *Path); }; bool CFBundle::SetFromPath(const char *InPath) { // Release our old bundle and URL. reset(); if (InPath && InPath[0]) { char ResolvedPath[PATH_MAX]; const char *Path = ::realpath(InPath, ResolvedPath); if (Path == nullptr) Path = InPath; CFAllocatorRef Allocator = kCFAllocatorDefault; // Make our Bundle URL. CFReleaser<CFURLRef> BundleURL(::CFURLCreateFromFileSystemRepresentation( Allocator, (const UInt8 *)Path, strlen(Path), false)); if (BundleURL.get()) { CFIndex LastLength = LONG_MAX; while (BundleURL.get() != nullptr) { // Check the Path range and make sure we didn't make it to just "/", // ".", or "..". CFRange rangeIncludingSeparators; CFRange range = ::CFURLGetByteRangeForComponent( BundleURL.get(), kCFURLComponentPath, &rangeIncludingSeparators); if (range.length > LastLength) break; reset(::CFBundleCreate(Allocator, BundleURL.get())); if (get() != nullptr) { if (GetIdentifier() != nullptr) break; reset(); } BundleURL.reset(::CFURLCreateCopyDeletingLastPathComponent( Allocator, BundleURL.get())); LastLength = range.length; } } } return get() != nullptr; } #endif /// On Darwin, try and find the original executable's Info.plist information /// using CoreFoundation calls by creating a URL for the executable and /// chopping off the last Path component. The CFBundle can then get the /// identifier and grab any needed information from it directly. Return default /// CFBundleInfo on other platforms. CFBundleInfo getBundleInfo(StringRef ExePath) { CFBundleInfo BundleInfo; #ifdef __APPLE__ if (ExePath.empty() || !sys::fs::exists(ExePath)) return BundleInfo; auto PrintError = [&](CFTypeID TypeID) { CFString TypeIDCFStr(::CFCopyTypeIDDescription(TypeID)); std::string TypeIDStr; errs() << "The Info.plist key \"CFBundleShortVersionString\" is" << "a " << TypeIDCFStr.UTF8(TypeIDStr) << ", but it should be a string in: " << ExePath << ".\n"; }; CFBundle Bundle(ExePath.data()); if (CFStringRef BundleID = Bundle.GetIdentifier()) { CFString::UTF8(BundleID, BundleInfo.IDStr); if (CFTypeRef TypeRef = Bundle.GetValueForInfoDictionaryKey(CFSTR("CFBundleVersion"))) { CFTypeID TypeID = ::CFGetTypeID(TypeRef); if (TypeID == ::CFStringGetTypeID()) CFString::UTF8((CFStringRef)TypeRef, BundleInfo.VersionStr); else PrintError(TypeID); } if (CFTypeRef TypeRef = Bundle.GetValueForInfoDictionaryKey( CFSTR("CFBundleShortVersionString"))) { CFTypeID TypeID = ::CFGetTypeID(TypeRef); if (TypeID == ::CFStringGetTypeID()) CFString::UTF8((CFStringRef)TypeRef, BundleInfo.ShortVersionStr); else PrintError(TypeID); } } #endif return BundleInfo; } } // end namespace dsymutil } // end namespace llvm <commit_msg>[dsymutil][NFC] Replace calls to CoreFoundation with LLVM equivalent.<commit_after>//===- tools/dsymutil/CFBundle.cpp - CFBundle helper ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CFBundle.h" #ifdef __APPLE__ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <CoreFoundation/CoreFoundation.h> #include <assert.h> #include <glob.h> #include <memory> #endif namespace llvm { namespace dsymutil { #ifdef __APPLE__ /// Deleter that calls CFRelease rather than deleting the pointer. template <typename T> struct CFDeleter { void operator()(T *P) { if (P) ::CFRelease(P); } }; /// This helper owns any CoreFoundation pointer and will call CFRelease() on /// any valid pointer it owns unless that pointer is explicitly released using /// the release() member function. template <typename T> using CFReleaser = std::unique_ptr<typename std::remove_pointer<T>::type, CFDeleter<typename std::remove_pointer<T>::type>>; /// RAII wrapper around CFBundleRef. class CFString : public CFReleaser<CFStringRef> { public: CFString(CFStringRef CFStr = nullptr) : CFReleaser<CFStringRef>(CFStr) {} const char *UTF8(std::string &Str) const { return CFString::UTF8(get(), Str); } CFIndex GetLength() const { if (CFStringRef Str = get()) return CFStringGetLength(Str); return 0; } static const char *UTF8(CFStringRef CFStr, std::string &Str); }; /// Static function that puts a copy of the UTF-8 contents of CFStringRef into /// std::string and returns the C string pointer that is contained in the /// std::string when successful, nullptr otherwise. /// /// This allows the std::string parameter to own the extracted string, and also /// allows that string to be returned as a C string pointer that can be used. const char *CFString::UTF8(CFStringRef CFStr, std::string &Str) { if (!CFStr) return nullptr; const CFStringEncoding Encoding = kCFStringEncodingUTF8; CFIndex MaxUTF8StrLength = CFStringGetLength(CFStr); MaxUTF8StrLength = CFStringGetMaximumSizeForEncoding(MaxUTF8StrLength, Encoding); if (MaxUTF8StrLength > 0) { Str.resize(MaxUTF8StrLength); if (!Str.empty() && CFStringGetCString(CFStr, &Str[0], Str.size(), Encoding)) { Str.resize(strlen(Str.c_str())); return Str.c_str(); } } return nullptr; } /// RAII wrapper around CFBundleRef. class CFBundle : public CFReleaser<CFBundleRef> { public: CFBundle(StringRef Path) : CFReleaser<CFBundleRef>() { SetFromPath(Path); } CFBundle(CFURLRef Url) : CFReleaser<CFBundleRef>(Url ? ::CFBundleCreate(nullptr, Url) : nullptr) {} /// Return the bundle identifier. CFStringRef GetIdentifier() const { if (CFBundleRef bundle = get()) return ::CFBundleGetIdentifier(bundle); return nullptr; } /// Return value for key. CFTypeRef GetValueForInfoDictionaryKey(CFStringRef key) const { if (CFBundleRef bundle = get()) return ::CFBundleGetValueForInfoDictionaryKey(bundle, key); return nullptr; } private: /// Helper to initialize this instance with a new bundle created from the /// given path. This function will recursively remove components from the /// path in its search for the nearest Info.plist. void SetFromPath(StringRef Path); }; void CFBundle::SetFromPath(StringRef Path) { // Start from an empty/invalid CFBundle. reset(); if (Path.empty() || !sys::fs::exists(Path)) return; SmallString<256> RealPath; sys::fs::real_path(Path, RealPath, /*expand_tilde*/ true); do { // Create a CFURL from the current path and use it to create a CFBundle. CFReleaser<CFURLRef> BundleURL(::CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, (const UInt8 *)RealPath.data(), RealPath.size(), false)); reset(::CFBundleCreate(kCFAllocatorDefault, BundleURL.get())); // If we have a valid bundle and find its identifier we are done. if (get() != nullptr) { if (GetIdentifier() != nullptr) return; reset(); } // Remove the last component of the path and try again until there's // nothing left but the root. sys::path::remove_filename(RealPath); } while (RealPath != sys::path::root_name(RealPath)); } #endif /// On Darwin, try and find the original executable's Info.plist to extract /// information about the bundle. Return default values on other platforms. CFBundleInfo getBundleInfo(StringRef ExePath) { CFBundleInfo BundleInfo; #ifdef __APPLE__ auto PrintError = [&](CFTypeID TypeID) { CFString TypeIDCFStr(::CFCopyTypeIDDescription(TypeID)); std::string TypeIDStr; errs() << "The Info.plist key \"CFBundleShortVersionString\" is" << "a " << TypeIDCFStr.UTF8(TypeIDStr) << ", but it should be a string in: " << ExePath << ".\n"; }; CFBundle Bundle(ExePath); if (CFStringRef BundleID = Bundle.GetIdentifier()) { CFString::UTF8(BundleID, BundleInfo.IDStr); if (CFTypeRef TypeRef = Bundle.GetValueForInfoDictionaryKey(CFSTR("CFBundleVersion"))) { CFTypeID TypeID = ::CFGetTypeID(TypeRef); if (TypeID == ::CFStringGetTypeID()) CFString::UTF8((CFStringRef)TypeRef, BundleInfo.VersionStr); else PrintError(TypeID); } if (CFTypeRef TypeRef = Bundle.GetValueForInfoDictionaryKey( CFSTR("CFBundleShortVersionString"))) { CFTypeID TypeID = ::CFGetTypeID(TypeRef); if (TypeID == ::CFStringGetTypeID()) CFString::UTF8((CFStringRef)TypeRef, BundleInfo.ShortVersionStr); else PrintError(TypeID); } } #endif return BundleInfo; } } // end namespace dsymutil } // end namespace llvm <|endoftext|>
<commit_before>#include "Player.h" Player::~Player() { } void Player::Update(float deltaTime)//make this affected by delta time { // Calculate velocity based on pixels-per-frame pos_.x += velocity.x * deltaTime; pos_.y += velocity.y * deltaTime; // Add acceleration to velocity if (abs(velocity.x) < 100) { velocity.x += acc.x; }; velocity.y += acc.y; SpriteAnimation::Update(deltaTime); } void Player::OnKeyDown(Uint16 key) { switch (key) { case SDL_SCANCODE_RIGHT: velocity.x = 1 * playerSpeed; break; case SDL_SCANCODE_LEFT: velocity.x = 1 * -playerSpeed; break; case SDL_SCANCODE_SPACE: break; } if (!playing_) { Play(true); } UpdateCurrAnimation(); } void Player::OnKeyUp(Uint16 key) { switch (key) { case SDL_SCANCODE_RIGHT: velocity.x = 0; break; case SDL_SCANCODE_LEFT: velocity.x = 0; break; case SDL_SCANCODE_SPACE: if (onGround) { velocity.y = -1 * jumpSpeed; onGround = false; //velocity.y = -1 * jumpSpeed; //need jump timer, max hold space bar timer and then gravity pulls down darude. } break; } if (!playing_) { Play(true); } UpdateCurrAnimation(); } void Player::UpdateCurrAnimation() { if ((velocity.y > 0 && velocity.x > 0) && currentAnim != ANIM_JUMP_RIGHT) { currentAnim = ANIM_JUMP_RIGHT; SetStartFrame(6); } else if ((velocity.y > 0 && velocity.x < 0) && currentAnim != ANIM_JUMP_LEFT) { currentAnim = ANIM_JUMP_LEFT; SetStartFrame(9); } else if (velocity.x > 0 && currentAnim != ANIM_RUN_RIGHT) { currentAnim = ANIM_RUN_RIGHT; SetStartFrame(0); } else if (velocity.x < 0 && currentAnim != ANIM_RUN_LEFT) { currentAnim = ANIM_RUN_LEFT; SetStartFrame(3); } else if (velocity.x == 0 && currentAnim == ANIM_RUN_RIGHT) { currentAnim = ANIM_IDLE_RIGHT; SetStartFrame(12); } else if (velocity.x == 0 && currentAnim == ANIM_RUN_LEFT) { currentAnim = ANIM_IDLE_LEFT; SetStartFrame(15); } } <commit_msg>jibrils bug fix<commit_after>#include "Player.h" Player::~Player() { } void Player::Update(float deltaTime)//make this affected by delta time { // Calculate velocity based on pixels-per-frame pos_.x += velocity.x * deltaTime; pos_.y += velocity.y * deltaTime; // Add acceleration to velocity if (abs(velocity.x) < 100) { velocity.x += acc.x; }; if (!onGround) { velocity.y += acc.y; } SpriteAnimation::Update(deltaTime); } void Player::OnKeyDown(Uint16 key) { switch (key) { case SDL_SCANCODE_RIGHT: velocity.x = 1 * playerSpeed; break; case SDL_SCANCODE_LEFT: velocity.x = 1 * -playerSpeed; break; case SDL_SCANCODE_SPACE: break; } if (!playing_) { Play(true); } UpdateCurrAnimation(); } void Player::OnKeyUp(Uint16 key) { switch (key) { case SDL_SCANCODE_RIGHT: velocity.x = 0; break; case SDL_SCANCODE_LEFT: velocity.x = 0; break; case SDL_SCANCODE_SPACE: if (onGround) { velocity.y = -1 * jumpSpeed; onGround = false; //velocity.y = -1 * jumpSpeed; //need jump timer, max hold space bar timer and then gravity pulls down darude. } break; } if (!playing_) { Play(true); } UpdateCurrAnimation(); } void Player::UpdateCurrAnimation() { if ((velocity.y > 0 && velocity.x > 0) && currentAnim != ANIM_JUMP_RIGHT) { currentAnim = ANIM_JUMP_RIGHT; SetStartFrame(6); } else if ((velocity.y > 0 && velocity.x < 0) && currentAnim != ANIM_JUMP_LEFT) { currentAnim = ANIM_JUMP_LEFT; SetStartFrame(9); } else if (velocity.x > 0 && currentAnim != ANIM_RUN_RIGHT) { currentAnim = ANIM_RUN_RIGHT; SetStartFrame(0); } else if (velocity.x < 0 && currentAnim != ANIM_RUN_LEFT) { currentAnim = ANIM_RUN_LEFT; SetStartFrame(3); } else if (velocity.x == 0 && currentAnim == ANIM_RUN_RIGHT) { currentAnim = ANIM_IDLE_RIGHT; SetStartFrame(12); } else if (velocity.x == 0 && currentAnim == ANIM_RUN_LEFT) { currentAnim = ANIM_IDLE_LEFT; SetStartFrame(15); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkGeometry2DData.h" #include "mitkBaseProcess.h" //##ModelId=3E639CD30201 mitk::Geometry2DData::Geometry2DData() { } //##ModelId=3E639CD30233 mitk::Geometry2DData::~Geometry2DData() { } void mitk::Geometry2DData::SetGeometry(mitk::Geometry3D *geometry) { if(geometry==NULL) SetGeometry2D(NULL); else { Geometry2D* geometry2d = dynamic_cast<Geometry2D*>(geometry); if(geometry2d==NULL) itkExceptionMacro(<<"Trying to set a geometry which is not a Geometry2D into Geometry2DData."); SetGeometry2D(geometry2d); } } //##ModelId=3E6423D2030E void mitk::Geometry2DData::SetGeometry2D(mitk::Geometry2D *geometry2d) { Superclass::SetGeometry(geometry2d); } //##ModelId=3E66CC5A0295 void mitk::Geometry2DData::UpdateOutputInformation() { Superclass::UpdateOutputInformation(); } //##ModelId=3E66CC5A02B4 void mitk::Geometry2DData::SetRequestedRegionToLargestPossibleRegion() { } //##ModelId=3E66CC5A02D2 bool mitk::Geometry2DData::RequestedRegionIsOutsideOfTheBufferedRegion() { if(GetGeometry2D()==NULL) return true; return false; } //##ModelId=3E66CC5A02F0 bool mitk::Geometry2DData::VerifyRequestedRegion() { if(GetGeometry2D()==NULL) return false; return true; } //##ModelId=3E66CC5A030E void mitk::Geometry2DData::SetRequestedRegion(itk::DataObject *data) { } //##ModelId=3E67D85E00B7 void mitk::Geometry2DData::CopyInformation(const itk::DataObject *data) { } <commit_msg>ENH: slight optimization<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkGeometry2DData.h" #include "mitkBaseProcess.h" //##ModelId=3E639CD30201 mitk::Geometry2DData::Geometry2DData() { } //##ModelId=3E639CD30233 mitk::Geometry2DData::~Geometry2DData() { } void mitk::Geometry2DData::SetGeometry(mitk::Geometry3D *geometry) { if(geometry==NULL) SetGeometry2D(NULL); else { Geometry2D* geometry2d = dynamic_cast<Geometry2D*>(geometry); if(geometry2d==NULL) itkExceptionMacro(<<"Trying to set a geometry which is not a Geometry2D into Geometry2DData."); SetGeometry2D(geometry2d); } } //##ModelId=3E6423D2030E void mitk::Geometry2DData::SetGeometry2D(mitk::Geometry2D *geometry2d) { if(geometry2d != NULL) { TimeSlicedGeometry* timeSlicedGeometry = GetTimeSlicedGeometry(); if(timeSlicedGeometry == NULL) { Superclass::SetGeometry(geometry2d); return; } timeSlicedGeometry->InitializeEvenlyTimed(geometry2d, 1); Modified(); } else Superclass::SetGeometry(geometry2d); } //##ModelId=3E66CC5A0295 void mitk::Geometry2DData::UpdateOutputInformation() { Superclass::UpdateOutputInformation(); } //##ModelId=3E66CC5A02B4 void mitk::Geometry2DData::SetRequestedRegionToLargestPossibleRegion() { } //##ModelId=3E66CC5A02D2 bool mitk::Geometry2DData::RequestedRegionIsOutsideOfTheBufferedRegion() { if(GetGeometry2D()==NULL) return true; return false; } //##ModelId=3E66CC5A02F0 bool mitk::Geometry2DData::VerifyRequestedRegion() { if(GetGeometry2D()==NULL) return false; return true; } //##ModelId=3E66CC5A030E void mitk::Geometry2DData::SetRequestedRegion(itk::DataObject *data) { } //##ModelId=3E67D85E00B7 void mitk::Geometry2DData::CopyInformation(const itk::DataObject *data) { } <|endoftext|>
<commit_before>#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <cmath> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; int main() { cout.precision(17); int n=50; itv x,q; q="0.7"; x=3.5; for(int i=1;i<=n;i++){ x=x-kv::Ramanujan_qAiry(itv(q),itv(x))*(1-q)*x /(kv::Ramanujan_qAiry(itv(q),itv(x))-kv::Ramanujan_qAiry(itv(q),itv(q*x))); cout<<x<<endl; cout<<"value of RqA"<<kv::Ramanujan_qAiry(itv(q),itv(x))<<endl; } } <commit_msg>Update RqAqNewton.cc<commit_after>#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <cmath> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; int main() { cout.precision(17); int n=50; itv x,q; q="0.7"; x=3.5; for(int i=1;i<=n;i++){ x=x-kv::Ramanujan_qAiry(itv(q),itv(x))*(1-q)*x /(kv::Ramanujan_qAiry(itv(q),itv(x))-kv::Ramanujan_qAiry(itv(q),itv(q*x))); cout<<x<<endl; cout<<"value of RqA inf"<<kv::Ramanujan_qAiry(itv(q),itv(x.lower()))<<endl; cout<<"value of RqA sup"<<kv::Ramanujan_qAiry(itv(q),itv(x.upper()))<<endl; cout<<"value of RqA mid"<<kv::Ramanujan_qAiry(itv(q),itv(mid(x)))<<endl; } } <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // A collection of various data filters // // ============================================================================= #include <algorithm> #include "chrono/utils/ChFilters.h" #include "chrono/core/ChMathematics.h" namespace chrono { namespace utils { // ----------------------------------------------------------------------------- ChRunningAverage::ChRunningAverage(int n) : m_n(n), m_index(0), m_std(0) { m_data.resize(n, 0.0); } double ChRunningAverage::Add(double val) { m_data[(m_index++) % m_n] = val; int size = std::min(m_index, m_n); double mean = m_data.sum() / size; m_std = std::sqrt(std::pow(m_data - mean, 2.0).sum() / (size - 1)); return mean; } // ----------------------------------------------------------------------------- ChMovingAverage::ChMovingAverage(const std::valarray<double>& data, int n) : m_n(n) { int np = (int) data.size(); m_out.resize(np); // Start and end of data int lim = ChMin(n, np); for (int i = 0; i < lim; i++) { m_out[i] = data[i]; for (int j = 1; j <= i; j++) m_out[i] += data[i - j] + data[i + j]; m_out[i] /= (2 * i + 1); } for (int i = 0; i < lim; i++) { m_out[np - 1 - i] = data[np - 1 - i]; for (int j = 1; j <= i; j++) m_out[np - 1 - i] += data[np - 1 - i - j] + data[np - 1 - i + j]; m_out[np - 1 - i] /= (2 * i + 1); } // Middle values for (int i = lim; i < np - lim; i++) { m_out[i] = data[i]; for (int j = 1; j <= n; j++) m_out[i] += data[i - j] + data[i + j]; m_out[i] /= (2 * n + 1); } } } // end namespace utils } // end namespace chrono <commit_msg>Fix issue with calculation of standard deviation at first point<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // A collection of various data filters // // ============================================================================= #include <algorithm> #include "chrono/utils/ChFilters.h" #include "chrono/core/ChMathematics.h" namespace chrono { namespace utils { // ----------------------------------------------------------------------------- ChRunningAverage::ChRunningAverage(int n) : m_n(n), m_index(0), m_std(0) { m_data.resize(n, 0.0); } double ChRunningAverage::Add(double val) { m_data[(m_index++) % m_n] = val; int size = std::min(m_index, m_n); double mean = m_data.sum() / size; m_std = (size == 1) ? 0 : std::sqrt(std::pow(m_data - mean, 2.0).sum() / (size - 1)); return mean; } // ----------------------------------------------------------------------------- ChMovingAverage::ChMovingAverage(const std::valarray<double>& data, int n) : m_n(n) { int np = (int) data.size(); m_out.resize(np); // Start and end of data int lim = ChMin(n, np); for (int i = 0; i < lim; i++) { m_out[i] = data[i]; for (int j = 1; j <= i; j++) m_out[i] += data[i - j] + data[i + j]; m_out[i] /= (2 * i + 1); } for (int i = 0; i < lim; i++) { m_out[np - 1 - i] = data[np - 1 - i]; for (int j = 1; j <= i; j++) m_out[np - 1 - i] += data[np - 1 - i - j] + data[np - 1 - i + j]; m_out[np - 1 - i] /= (2 * i + 1); } // Middle values for (int i = lim; i < np - lim; i++) { m_out[i] = data[i]; for (int j = 1; j <= n; j++) m_out[i] += data[i - j] + data[i + j]; m_out[i] /= (2 * n + 1); } } } // end namespace utils } // end namespace chrono <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "joynr/ImmutableMessage.h" #include "joynr/Message.h" namespace joynr { INIT_LOGGER(ImmutableMessage); ImmutableMessage::ImmutableMessage(smrf::ByteVector&& serializedMessage, bool verifyInput) : serializedMessage(std::move(serializedMessage)), messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput), receivedFromGlobal(false), bodyView(), decompressedBody() { init(); } ImmutableMessage::ImmutableMessage(const smrf::ByteVector& serializedMessage, bool verifyInput) : serializedMessage(serializedMessage), messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput), receivedFromGlobal(false), bodyView(), decompressedBody() { init(); } std::string ImmutableMessage::getSender() const { return messageDeserializer.getSender(); } std::string ImmutableMessage::getRecipient() const { return messageDeserializer.getRecipient(); } bool ImmutableMessage::isTtlAbsolute() const { return messageDeserializer.isTtlAbsolute(); } const std::unordered_map<std::string, std::string>& ImmutableMessage::getHeaders() const { return headers; } bool ImmutableMessage::isEncrypted() const { return messageDeserializer.isEncrypted(); } bool ImmutableMessage::isSigned() const { return messageDeserializer.isSigned(); } smrf::ByteArrayView ImmutableMessage::getUnencryptedBody() const { if (!bodyView) { if (!messageDeserializer.isCompressed()) { bodyView = messageDeserializer.getBody(); } else { decompressedBody = messageDeserializer.decompressBody(); bodyView = smrf::ByteArrayView(*decompressedBody); } } return *bodyView; } std::string ImmutableMessage::toLogMessage() const { return serializer::serializeToJson(*this); } const std::string& ImmutableMessage::getType() const { return type; } const std::string& ImmutableMessage::getId() const { return id; } boost::optional<std::string> ImmutableMessage::getReplyTo() const { return getOptionalHeaderByKey(Message::HEADER_REPLY_TO()); } boost::optional<std::string> ImmutableMessage::getEffort() const { return getOptionalHeaderByKey(Message::HEADER_EFFORT()); } JoynrTimePoint ImmutableMessage::getExpiryDate() const { // for now we only support absolute TTLs assert(messageDeserializer.isTtlAbsolute()); return JoynrTimePoint(std::chrono::milliseconds(messageDeserializer.getTtlMs())); } const smrf::ByteVector& ImmutableMessage::getSerializedMessage() const { return serializedMessage; } std::size_t ImmutableMessage::getMessageSize() const { return messageDeserializer.getMessageSize(); } bool ImmutableMessage::isReceivedFromGlobal() const { return receivedFromGlobal; } void ImmutableMessage::setReceivedFromGlobal(bool receivedFromGlobal) { this->receivedFromGlobal = receivedFromGlobal; } void ImmutableMessage::setCreator(const std::string& creator) { this->creator = creator; } void ImmutableMessage::setCreator(std::string&& creator) { this->creator = std::move(creator); } const std::string& ImmutableMessage::getCreator() const { return creator; } boost::optional<std::string> ImmutableMessage::getOptionalHeaderByKey(const std::string& key) const { boost::optional<std::string> value; auto it = headers.find(key); if (it != headers.cend()) { value = it->second; } return value; } void ImmutableMessage::init() { headers = messageDeserializer.getHeaders(); boost::optional<std::string> optionalId = getOptionalHeaderByKey(Message::HEADER_ID()); boost::optional<std::string> optionalType = getOptionalHeaderByKey(Message::HEADER_TYPE()); JOYNR_LOG_TRACE(logger, "init: {}", toLogMessage()); // check if necessary headers are set if (!optionalId.is_initialized() || !optionalType.is_initialized()) { throw std::invalid_argument("missing header"); } else { id = std::move(*optionalId); type = std::move(*optionalType); } } } // namespace joynr <commit_msg>[C++] fixed member initialization order in ImmutableMessage<commit_after>/* * #%L * %% * Copyright (C) 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "joynr/ImmutableMessage.h" #include "joynr/Message.h" namespace joynr { INIT_LOGGER(ImmutableMessage); ImmutableMessage::ImmutableMessage(smrf::ByteVector&& serializedMessage, bool verifyInput) : serializedMessage(std::move(serializedMessage)), messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput), headers(), bodyView(), decompressedBody(), receivedFromGlobal(false), creator(), id(), type() { init(); } ImmutableMessage::ImmutableMessage(const smrf::ByteVector& serializedMessage, bool verifyInput) : serializedMessage(serializedMessage), messageDeserializer(smrf::ByteArrayView(this->serializedMessage), verifyInput), headers(), bodyView(), decompressedBody(), receivedFromGlobal(false), creator(), id(), type() { init(); } std::string ImmutableMessage::getSender() const { return messageDeserializer.getSender(); } std::string ImmutableMessage::getRecipient() const { return messageDeserializer.getRecipient(); } bool ImmutableMessage::isTtlAbsolute() const { return messageDeserializer.isTtlAbsolute(); } const std::unordered_map<std::string, std::string>& ImmutableMessage::getHeaders() const { return headers; } bool ImmutableMessage::isEncrypted() const { return messageDeserializer.isEncrypted(); } bool ImmutableMessage::isSigned() const { return messageDeserializer.isSigned(); } smrf::ByteArrayView ImmutableMessage::getUnencryptedBody() const { if (!bodyView) { if (!messageDeserializer.isCompressed()) { bodyView = messageDeserializer.getBody(); } else { decompressedBody = messageDeserializer.decompressBody(); bodyView = smrf::ByteArrayView(*decompressedBody); } } return *bodyView; } std::string ImmutableMessage::toLogMessage() const { return serializer::serializeToJson(*this); } const std::string& ImmutableMessage::getType() const { return type; } const std::string& ImmutableMessage::getId() const { return id; } boost::optional<std::string> ImmutableMessage::getReplyTo() const { return getOptionalHeaderByKey(Message::HEADER_REPLY_TO()); } boost::optional<std::string> ImmutableMessage::getEffort() const { return getOptionalHeaderByKey(Message::HEADER_EFFORT()); } JoynrTimePoint ImmutableMessage::getExpiryDate() const { // for now we only support absolute TTLs assert(messageDeserializer.isTtlAbsolute()); return JoynrTimePoint(std::chrono::milliseconds(messageDeserializer.getTtlMs())); } const smrf::ByteVector& ImmutableMessage::getSerializedMessage() const { return serializedMessage; } std::size_t ImmutableMessage::getMessageSize() const { return messageDeserializer.getMessageSize(); } bool ImmutableMessage::isReceivedFromGlobal() const { return receivedFromGlobal; } void ImmutableMessage::setReceivedFromGlobal(bool receivedFromGlobal) { this->receivedFromGlobal = receivedFromGlobal; } void ImmutableMessage::setCreator(const std::string& creator) { this->creator = creator; } void ImmutableMessage::setCreator(std::string&& creator) { this->creator = std::move(creator); } const std::string& ImmutableMessage::getCreator() const { return creator; } boost::optional<std::string> ImmutableMessage::getOptionalHeaderByKey(const std::string& key) const { boost::optional<std::string> value; auto it = headers.find(key); if (it != headers.cend()) { value = it->second; } return value; } void ImmutableMessage::init() { headers = messageDeserializer.getHeaders(); boost::optional<std::string> optionalId = getOptionalHeaderByKey(Message::HEADER_ID()); boost::optional<std::string> optionalType = getOptionalHeaderByKey(Message::HEADER_TYPE()); JOYNR_LOG_TRACE(logger, "init: {}", toLogMessage()); // check if necessary headers are set if (!optionalId.is_initialized() || !optionalType.is_initialized()) { throw std::invalid_argument("missing header"); } else { id = std::move(*optionalId); type = std::move(*optionalType); } } } // namespace joynr <|endoftext|>
<commit_before>/* Copyright (c) 2018, Ford Motor Company 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 Ford Motor Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include "sdl_rpc_plugin/commands/mobile/put_file_request.h" #include "application_manager/policies/policy_handler.h" #include "application_manager/application_impl.h" #include "application_manager/rpc_service.h" #include "utils/file_system.h" #include <boost/crc.hpp> namespace { /** * Calculates CRC32 checksum * @param binary_data - input data for which CRC32 should be calculated * @return calculated CRC32 checksum */ uint32_t GetCrc32CheckSum(const std::vector<uint8_t>& binary_data) { const std::size_t file_size = binary_data.size(); boost::crc_32_type result; result.process_bytes(&binary_data[0], file_size); return result.checksum(); } } // namespace namespace sdl_rpc_plugin { using namespace application_manager; namespace commands { PutFileRequest::PutFileRequest( const application_manager::commands::MessageSharedPtr& message, ApplicationManager& application_manager, app_mngr::rpc_service::RPCService& rpc_service, app_mngr::HMICapabilities& hmi_capabilities, policy::PolicyHandlerInterface& policy_handler) : CommandRequestImpl(message, application_manager, rpc_service, hmi_capabilities, policy_handler) , offset_(0) , sync_file_name_() , length_(0) , file_type_(mobile_apis::FileType::INVALID_ENUM) , is_persistent_file_(false) {} PutFileRequest::~PutFileRequest() {} void PutFileRequest::Run() { LOG4CXX_AUTO_TRACE(logger_); ApplicationSharedPtr application = application_manager_.application(connection_key()); smart_objects::SmartObject response_params = smart_objects::SmartObject(smart_objects::SmartType_Map); if (!application) { LOG4CXX_ERROR(logger_, "Application is not registered"); SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED); return; } if (mobile_api::HMILevel::HMI_NONE == application->hmi_level() && application_manager_.get_settings().put_file_in_none() <= application->put_file_in_none_count()) { // If application is in the HMI_NONE level the quantity of allowed // PutFile request is limited by the configuration profile LOG4CXX_ERROR(logger_, "Too many requests from the app with HMILevel HMI_NONE "); SendResponse(false, mobile_apis::Result::REJECTED, "Too many requests from the app with HMILevel HMI_NONE", &response_params); return; } if (!(*message_)[strings::params].keyExists(strings::binary_data)) { LOG4CXX_ERROR(logger_, "Binary data empty"); SendResponse(false, mobile_apis::Result::INVALID_DATA, "Binary data empty", &response_params); return; } if (!(*message_)[strings::msg_params].keyExists(strings::sync_file_name)) { LOG4CXX_ERROR(logger_, "No file name"); SendResponse(false, mobile_apis::Result::INVALID_DATA, "No file name", &response_params); return; } if (!(*message_)[strings::msg_params].keyExists(strings::file_type)) { LOG4CXX_ERROR(logger_, "No file type"); SendResponse(false, mobile_apis::Result::INVALID_DATA, "No file type", &response_params); return; } sync_file_name_ = (*message_)[strings::msg_params][strings::sync_file_name].asString(); if (!file_system::IsFileNameValid(sync_file_name_)) { const std::string err_msg = "Sync file name contains forbidden symbols."; LOG4CXX_ERROR(logger_, err_msg); SendResponse(false, mobile_apis::Result::INVALID_DATA, err_msg.c_str(), &response_params); return; } file_type_ = static_cast<mobile_apis::FileType::eType>( (*message_)[strings::msg_params][strings::file_type].asInt()); const std::vector<uint8_t> binary_data = (*message_)[strings::params][strings::binary_data].asBinary(); // Policy table update in json format is currently to be received via PutFile // TODO(PV): after latest discussion has to be changed if (mobile_apis::FileType::JSON == file_type_) { policy_handler_.ReceiveMessageFromSDK(sync_file_name_, binary_data); } offset_ = 0; is_persistent_file_ = false; bool is_system_file = false; length_ = binary_data.size(); bool is_download_complete = true; bool offset_exist = (*message_)[strings::msg_params].keyExists(strings::offset); if (offset_exist) { offset_ = (*message_)[strings::msg_params][strings::offset].asInt(); } if ((*message_)[strings::msg_params].keyExists(strings::persistent_file)) { is_persistent_file_ = (*message_)[strings::msg_params][strings::persistent_file].asBool(); } if ((*message_)[strings::msg_params].keyExists(strings::system_file)) { is_system_file = (*message_)[strings::msg_params][strings::system_file].asBool(); } std::string file_path; if (is_system_file) { response_params[strings::space_available] = 0; file_path = application_manager_.get_settings().system_files_path(); } else { file_path = application_manager_.get_settings().app_storage_folder(); file_path += "/" + application->folder_name(); uint32_t space_available = application->GetAvailableDiskSpace(); if (binary_data.size() > space_available) { response_params[strings::space_available] = static_cast<uint32_t>(space_available); LOG4CXX_ERROR(logger_, "Out of memory"); SendResponse(false, mobile_apis::Result::OUT_OF_MEMORY, "Out of memory", &response_params); return; } } if (!file_system::CreateDirectoryRecursively(file_path)) { LOG4CXX_ERROR(logger_, "Can't create folder"); SendResponse(false, mobile_apis::Result::GENERIC_ERROR, "Can't create folder.", &response_params); return; } const std::string full_path = file_path + "/" + sync_file_name_; if ((*message_)[strings::msg_params].keyExists(strings::crc32_check_sum)) { LOG4CXX_TRACE(logger_, "Binary Data Size: " << binary_data.size()); const uint32_t crc_received = (*message_)[strings::msg_params][strings::crc32_check_sum].asUInt(); LOG4CXX_TRACE(logger_, "CRC32 SUM Received: " << crc_received); const uint32_t crc_calculated = GetCrc32CheckSum(binary_data); LOG4CXX_TRACE(logger_, "CRC32 SUM Calculated: " << crc_calculated); if (crc_calculated != crc_received) { SendResponse(false, mobile_apis::Result::CORRUPTED_DATA, "CRC Check on file failed. File upload has been cancelled, " "please retry.", &response_params); return; } } LOG4CXX_DEBUG(logger_, "Writing " << binary_data.size() << " bytes to " << full_path << " (current size is" << file_system::FileSize(full_path) << ")"); mobile_apis::Result::eType save_result = application_manager_.SaveBinary( binary_data, file_path, sync_file_name_, offset_); LOG4CXX_DEBUG(logger_, "New size of " << full_path << " is " << file_system::FileSize(full_path) << " bytes"); if (!is_system_file) { response_params[strings::space_available] = static_cast<uint32_t>(application->GetAvailableDiskSpace()); } sync_file_name_ = file_path + "/" + sync_file_name_; switch (save_result) { case mobile_apis::Result::SUCCESS: { LOG4CXX_INFO(logger_, "PutFile is successful"); if (!is_system_file) { AppFile file(sync_file_name_, is_persistent_file_, is_download_complete, file_type_); if (0 == offset_) { LOG4CXX_INFO(logger_, "New file downloading"); if (!application->AddFile(file)) { LOG4CXX_INFO(logger_, "Couldn't add file to application (File already Exist" << " in application and was rewritten on FS)"); /* It can be first part of new big file, so we need to update information about it's downloading status and persistence */ if (!application->UpdateFile(file)) { LOG4CXX_ERROR(logger_, "Couldn't update file"); /* If it is impossible to update file, application doesn't know about existing this file */ SendResponse(false, mobile_apis::Result::INVALID_DATA, "Couldn't update file", &response_params); return; } } else { /* if file added - increment it's count ( may be application->AddFile have to incapsulate it? ) Any way now this method evals not only in "none"*/ application->increment_put_file_in_none_count(); } } } SendResponse(true, save_result, "File was downloaded", &response_params); if (is_system_file) { SendOnPutFileNotification(); } break; } default: LOG4CXX_WARN(logger_, "PutFile is unsuccessful. Result = " << save_result); SendResponse(false, save_result, "Can't save file", &response_params); break; } } void PutFileRequest::SendOnPutFileNotification() { LOG4CXX_INFO(logger_, "SendOnPutFileNotification"); smart_objects::SmartObjectSPtr notification = std::make_shared<smart_objects::SmartObject>( smart_objects::SmartType_Map); smart_objects::SmartObject& message = *notification; message[strings::params][strings::function_id] = hmi_apis::FunctionID::BasicCommunication_OnPutFile; message[strings::params][strings::message_type] = MessageType::kNotification; message[strings::msg_params][strings::app_id] = connection_key(); message[strings::msg_params][strings::sync_file_name] = sync_file_name_; message[strings::msg_params][strings::offset] = offset_; if (0 == offset_) { message[strings::msg_params][strings::file_size] = (*message_)[strings::msg_params][strings::length]; } message[strings::msg_params][strings::length] = length_; message[strings::msg_params][strings::persistent_file] = is_persistent_file_; message[strings::msg_params][strings::file_type] = file_type_; rpc_service_.ManageHMICommand(notification); } } // namespace commands } // namespace application_manager <commit_msg>Add additional check for non-manadatory parameters<commit_after>/* Copyright (c) 2018, Ford Motor Company 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 Ford Motor Company nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include "sdl_rpc_plugin/commands/mobile/put_file_request.h" #include "application_manager/policies/policy_handler.h" #include "application_manager/application_impl.h" #include "application_manager/rpc_service.h" #include "utils/file_system.h" #include <boost/crc.hpp> namespace { /** * Calculates CRC32 checksum * @param binary_data - input data for which CRC32 should be calculated * @return calculated CRC32 checksum */ uint32_t GetCrc32CheckSum(const std::vector<uint8_t>& binary_data) { const std::size_t file_size = binary_data.size(); boost::crc_32_type result; result.process_bytes(&binary_data[0], file_size); return result.checksum(); } } // namespace namespace sdl_rpc_plugin { using namespace application_manager; namespace commands { PutFileRequest::PutFileRequest( const application_manager::commands::MessageSharedPtr& message, ApplicationManager& application_manager, app_mngr::rpc_service::RPCService& rpc_service, app_mngr::HMICapabilities& hmi_capabilities, policy::PolicyHandlerInterface& policy_handler) : CommandRequestImpl(message, application_manager, rpc_service, hmi_capabilities, policy_handler) , offset_(0) , sync_file_name_() , length_(0) , file_type_(mobile_apis::FileType::INVALID_ENUM) , is_persistent_file_(false) {} PutFileRequest::~PutFileRequest() {} void PutFileRequest::Run() { LOG4CXX_AUTO_TRACE(logger_); ApplicationSharedPtr application = application_manager_.application(connection_key()); smart_objects::SmartObject response_params = smart_objects::SmartObject(smart_objects::SmartType_Map); if (!application) { LOG4CXX_ERROR(logger_, "Application is not registered"); SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED); return; } if (mobile_api::HMILevel::HMI_NONE == application->hmi_level() && application_manager_.get_settings().put_file_in_none() <= application->put_file_in_none_count()) { // If application is in the HMI_NONE level the quantity of allowed // PutFile request is limited by the configuration profile LOG4CXX_ERROR(logger_, "Too many requests from the app with HMILevel HMI_NONE "); SendResponse(false, mobile_apis::Result::REJECTED, "Too many requests from the app with HMILevel HMI_NONE", &response_params); return; } if (!(*message_)[strings::params].keyExists(strings::binary_data)) { LOG4CXX_ERROR(logger_, "Binary data empty"); SendResponse(false, mobile_apis::Result::INVALID_DATA, "Binary data empty", &response_params); return; } if (!(*message_)[strings::msg_params].keyExists(strings::sync_file_name)) { LOG4CXX_ERROR(logger_, "No file name"); SendResponse(false, mobile_apis::Result::INVALID_DATA, "No file name", &response_params); return; } if (!(*message_)[strings::msg_params].keyExists(strings::file_type)) { LOG4CXX_ERROR(logger_, "No file type"); SendResponse(false, mobile_apis::Result::INVALID_DATA, "No file type", &response_params); return; } sync_file_name_ = (*message_)[strings::msg_params][strings::sync_file_name].asString(); if (!file_system::IsFileNameValid(sync_file_name_)) { const std::string err_msg = "Sync file name contains forbidden symbols."; LOG4CXX_ERROR(logger_, err_msg); SendResponse(false, mobile_apis::Result::INVALID_DATA, err_msg.c_str(), &response_params); return; } file_type_ = static_cast<mobile_apis::FileType::eType>( (*message_)[strings::msg_params][strings::file_type].asInt()); const std::vector<uint8_t> binary_data = (*message_)[strings::params][strings::binary_data].asBinary(); // Policy table update in json format is currently to be received via PutFile // TODO(PV): after latest discussion has to be changed if (mobile_apis::FileType::JSON == file_type_) { policy_handler_.ReceiveMessageFromSDK(sync_file_name_, binary_data); } offset_ = 0; is_persistent_file_ = false; bool is_system_file = false; length_ = binary_data.size(); bool is_download_complete = true; bool offset_exist = (*message_)[strings::msg_params].keyExists(strings::offset); if (offset_exist) { offset_ = (*message_)[strings::msg_params][strings::offset].asInt(); } if ((*message_)[strings::msg_params].keyExists(strings::persistent_file)) { is_persistent_file_ = (*message_)[strings::msg_params][strings::persistent_file].asBool(); } if ((*message_)[strings::msg_params].keyExists(strings::system_file)) { is_system_file = (*message_)[strings::msg_params][strings::system_file].asBool(); } std::string file_path; if (is_system_file) { response_params[strings::space_available] = 0; file_path = application_manager_.get_settings().system_files_path(); } else { file_path = application_manager_.get_settings().app_storage_folder(); file_path += "/" + application->folder_name(); uint32_t space_available = application->GetAvailableDiskSpace(); if (binary_data.size() > space_available) { response_params[strings::space_available] = static_cast<uint32_t>(space_available); LOG4CXX_ERROR(logger_, "Out of memory"); SendResponse(false, mobile_apis::Result::OUT_OF_MEMORY, "Out of memory", &response_params); return; } } if (!file_system::CreateDirectoryRecursively(file_path)) { LOG4CXX_ERROR(logger_, "Can't create folder"); SendResponse(false, mobile_apis::Result::GENERIC_ERROR, "Can't create folder.", &response_params); return; } const std::string full_path = file_path + "/" + sync_file_name_; if ((*message_)[strings::msg_params].keyExists(strings::crc32_check_sum)) { LOG4CXX_TRACE(logger_, "Binary Data Size: " << binary_data.size()); const uint32_t crc_received = (*message_)[strings::msg_params][strings::crc32_check_sum].asUInt(); LOG4CXX_TRACE(logger_, "CRC32 SUM Received: " << crc_received); const uint32_t crc_calculated = GetCrc32CheckSum(binary_data); LOG4CXX_TRACE(logger_, "CRC32 SUM Calculated: " << crc_calculated); if (crc_calculated != crc_received) { SendResponse(false, mobile_apis::Result::CORRUPTED_DATA, "CRC Check on file failed. File upload has been cancelled, " "please retry.", &response_params); return; } } LOG4CXX_DEBUG(logger_, "Writing " << binary_data.size() << " bytes to " << full_path << " (current size is" << file_system::FileSize(full_path) << ")"); mobile_apis::Result::eType save_result = application_manager_.SaveBinary( binary_data, file_path, sync_file_name_, offset_); LOG4CXX_DEBUG(logger_, "New size of " << full_path << " is " << file_system::FileSize(full_path) << " bytes"); if (!is_system_file) { response_params[strings::space_available] = static_cast<uint32_t>(application->GetAvailableDiskSpace()); } sync_file_name_ = file_path + "/" + sync_file_name_; switch (save_result) { case mobile_apis::Result::SUCCESS: { LOG4CXX_INFO(logger_, "PutFile is successful"); if (!is_system_file) { AppFile file(sync_file_name_, is_persistent_file_, is_download_complete, file_type_); if (0 == offset_) { LOG4CXX_INFO(logger_, "New file downloading"); if (!application->AddFile(file)) { LOG4CXX_INFO(logger_, "Couldn't add file to application (File already Exist" << " in application and was rewritten on FS)"); /* It can be first part of new big file, so we need to update information about it's downloading status and persistence */ if (!application->UpdateFile(file)) { LOG4CXX_ERROR(logger_, "Couldn't update file"); /* If it is impossible to update file, application doesn't know about existing this file */ SendResponse(false, mobile_apis::Result::INVALID_DATA, "Couldn't update file", &response_params); return; } } else { /* if file added - increment it's count ( may be application->AddFile have to incapsulate it? ) Any way now this method evals not only in "none"*/ application->increment_put_file_in_none_count(); } } } SendResponse(true, save_result, "File was downloaded", &response_params); if (is_system_file) { SendOnPutFileNotification(); } break; } default: LOG4CXX_WARN(logger_, "PutFile is unsuccessful. Result = " << save_result); SendResponse(false, save_result, "Can't save file", &response_params); break; } } void PutFileRequest::SendOnPutFileNotification() { LOG4CXX_INFO(logger_, "SendOnPutFileNotification"); smart_objects::SmartObjectSPtr notification = std::make_shared<smart_objects::SmartObject>( smart_objects::SmartType_Map); smart_objects::SmartObject& message = *notification; message[strings::params][strings::function_id] = hmi_apis::FunctionID::BasicCommunication_OnPutFile; message[strings::params][strings::message_type] = MessageType::kNotification; message[strings::msg_params][strings::app_id] = connection_key(); message[strings::msg_params][strings::sync_file_name] = sync_file_name_; message[strings::msg_params][strings::offset] = offset_; if (0 == offset_ && !(*message_)[strings::msg_params].keyExists(strings::length)) { message[strings::msg_params][strings::file_size] = length_; } message[strings::msg_params][strings::length] = length_; message[strings::msg_params][strings::persistent_file] = is_persistent_file_; message[strings::msg_params][strings::file_type] = file_type_; rpc_service_.ManageHMICommand(notification); } } // namespace commands } // namespace application_manager <|endoftext|>
<commit_before>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: smt_strategic_solver.h Abstract: Create a strategic solver with tactic for all main logics used in SMT. Author: Leonardo (leonardo) 2012-02-19 Notes: --*/ #include"cmd_context.h" #include"combined_solver.h" #include"tactic2solver.h" #include"qfbv_tactic.h" #include"qflia_tactic.h" #include"qfnia_tactic.h" #include"qfnra_tactic.h" #include"qfuf_tactic.h" #include"qflra_tactic.h" #include"quant_tactics.h" #include"qfauflia_tactic.h" #include"qfaufbv_tactic.h" #include"qfufbv_tactic.h" #include"qfidl_tactic.h" #include"default_tactic.h" #include"ufbv_tactic.h" #include"qffpa_tactic.h" #include"horn_tactic.h" #include"smt_solver.h" tactic * mk_tactic_for_logic(ast_manager & m, params_ref const & p, symbol const & logic) { if (logic=="QF_UF") return mk_qfuf_tactic(m, p); else if (logic=="QF_BV") return mk_qfbv_tactic(m, p); else if (logic=="QF_IDL") return mk_qfidl_tactic(m, p); else if (logic=="QF_LIA") return mk_qflia_tactic(m, p); else if (logic=="QF_LRA") return mk_qflra_tactic(m, p); else if (logic=="QF_NIA") return mk_qfnia_tactic(m, p); else if (logic=="QF_NRA") return mk_qfnra_tactic(m, p); else if (logic=="QF_AUFLIA") return mk_qfauflia_tactic(m, p); else if (logic=="QF_AUFBV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_ABV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_UFBV") return mk_qfufbv_tactic(m, p); else if (logic=="AUFLIA") return mk_auflia_tactic(m, p); else if (logic=="AUFLIRA") return mk_auflira_tactic(m, p); else if (logic=="AUFNIRA") return mk_aufnira_tactic(m, p); else if (logic=="UFNIA") return mk_ufnia_tactic(m, p); else if (logic=="UFLRA") return mk_uflra_tactic(m, p); else if (logic=="LRA") return mk_lra_tactic(m, p); else if (logic=="LIA") return mk_lia_tactic(m, p); else if (logic=="UFBV") return mk_ufbv_tactic(m, p); else if (logic=="BV") return mk_ufbv_tactic(m, p); else if (logic=="QF_FPA") return mk_qffpa_tactic(m, p); else if (logic=="QF_FPABV") return mk_qffpa_tactic(m, p); else if (logic=="HORN") return mk_horn_tactic(m, p); else return mk_default_tactic(m, p); } class smt_strategic_solver_factory : public solver_factory { symbol m_logic; public: smt_strategic_solver_factory(symbol const & logic):m_logic(logic) {} virtual ~smt_strategic_solver_factory() {} virtual solver * operator()(ast_manager & m, params_ref const & p, bool proofs_enabled, bool models_enabled, bool unsat_core_enabled, symbol const & logic) { symbol l; if (m_logic != symbol::null) l = m_logic; else l = logic; tactic * t = mk_tactic_for_logic(m, p, l); return mk_combined_solver(mk_tactic2solver(m, t, p, proofs_enabled, models_enabled, unsat_core_enabled, l), mk_smt_solver(m, p, l), p); } }; solver_factory * mk_smt_strategic_solver_factory(symbol const & logic) { return alloc(smt_strategic_solver_factory, logic); } <commit_msg>sls tactic default<commit_after>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: smt_strategic_solver.h Abstract: Create a strategic solver with tactic for all main logics used in SMT. Author: Leonardo (leonardo) 2012-02-19 Notes: --*/ #include"cmd_context.h" #include"combined_solver.h" #include"tactic2solver.h" #include"qfbv_tactic.h" #include"qflia_tactic.h" #include"qfnia_tactic.h" #include"qfnra_tactic.h" #include"qfuf_tactic.h" #include"qflra_tactic.h" #include"quant_tactics.h" #include"qfauflia_tactic.h" #include"qfaufbv_tactic.h" #include"qfufbv_tactic.h" #include"qfidl_tactic.h" #include"default_tactic.h" #include"ufbv_tactic.h" #include"qffpa_tactic.h" #include"horn_tactic.h" #include"smt_solver.h" #include"sls_tactic.h" tactic * mk_tactic_for_logic(ast_manager & m, params_ref const & p, symbol const & logic) { if (logic=="QF_UF") return mk_qfuf_tactic(m, p); else if (logic=="QF_BV") return mk_qfbv_sls_tactic(m, p); else if (logic=="QF_IDL") return mk_qfidl_tactic(m, p); else if (logic=="QF_LIA") return mk_qflia_tactic(m, p); else if (logic=="QF_LRA") return mk_qflra_tactic(m, p); else if (logic=="QF_NIA") return mk_qfnia_tactic(m, p); else if (logic=="QF_NRA") return mk_qfnra_tactic(m, p); else if (logic=="QF_AUFLIA") return mk_qfauflia_tactic(m, p); else if (logic=="QF_AUFBV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_ABV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_UFBV") return mk_qfufbv_tactic(m, p); else if (logic=="AUFLIA") return mk_auflia_tactic(m, p); else if (logic=="AUFLIRA") return mk_auflira_tactic(m, p); else if (logic=="AUFNIRA") return mk_aufnira_tactic(m, p); else if (logic=="UFNIA") return mk_ufnia_tactic(m, p); else if (logic=="UFLRA") return mk_uflra_tactic(m, p); else if (logic=="LRA") return mk_lra_tactic(m, p); else if (logic=="LIA") return mk_lia_tactic(m, p); else if (logic=="UFBV") return mk_ufbv_tactic(m, p); else if (logic=="BV") return mk_ufbv_tactic(m, p); else if (logic=="QF_FPA") return mk_qffpa_tactic(m, p); else if (logic=="QF_FPABV") return mk_qffpa_tactic(m, p); else if (logic=="HORN") return mk_horn_tactic(m, p); else return mk_default_tactic(m, p); } class smt_strategic_solver_factory : public solver_factory { symbol m_logic; public: smt_strategic_solver_factory(symbol const & logic):m_logic(logic) {} virtual ~smt_strategic_solver_factory() {} virtual solver * operator()(ast_manager & m, params_ref const & p, bool proofs_enabled, bool models_enabled, bool unsat_core_enabled, symbol const & logic) { symbol l; if (m_logic != symbol::null) l = m_logic; else l = logic; tactic * t = mk_tactic_for_logic(m, p, l); return mk_combined_solver(mk_tactic2solver(m, t, p, proofs_enabled, models_enabled, unsat_core_enabled, l), mk_smt_solver(m, p, l), p); } }; solver_factory * mk_smt_strategic_solver_factory(symbol const & logic) { return alloc(smt_strategic_solver_factory, logic); } <|endoftext|>
<commit_before>#include "helpers.hpp" #include <chain.hpp> #include <vector> #include <list> #include <string> #include <vector> #include <iterator> #include <utility> #include "catch.hpp" using iter::chain; using itertest::SolidInt; using itertest::BasicIterable; using Vec = const std::vector<char>; TEST_CASE("chain: three strings", "[chain]") { std::string s1{"abc"}; std::string s2{"mno"}; std::string s3{"xyz"}; auto ch = chain(s1, s2, s3); Vec v(std::begin(ch), std::end(ch)); Vec vc{'a','b','c','m','n','o','x','y','z'}; REQUIRE( v == vc ); } TEST_CASE("chain: with different container types", "[chain]") { std::string s1{"abc"}; std::list<char> li{'m', 'n', 'o'}; std::vector<char> vec{'x', 'y', 'z'}; auto ch = chain(s1, li, vec); Vec v(std::begin(ch), std::end(ch)); Vec vc{'a','b','c','m','n','o','x','y','z'}; REQUIRE( v == vc ); } TEST_CASE("chain: handles empty containers", "[chain]") { std::string emp; std::string a{"a"}; std::string b{"b"}; std::string c{"c"}; Vec vc{'a', 'b', 'c'}; SECTION("Empty container at front") { auto ch = chain(emp, a, b, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Empty container at back") { auto ch = chain(a, b, c, emp); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Empty container in middle") { auto ch = chain(a, emp, b, emp, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Consecutive empty containers at front") { auto ch = chain(emp, emp, a, b, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Consecutive empty containers at back") { auto ch = chain(a, b, c, emp, emp); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Consecutive empty containers in middle") { auto ch = chain(a, emp, emp, b, emp, emp, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } } TEST_CASE("chain: with only empty containers", "[chain]") { std::string emp{}; SECTION("one empty container") { auto ch = chain(emp); REQUIRE_FALSE( std::begin(ch) != std::end(ch) ); } SECTION("two empty containers") { auto ch = chain(emp, emp); REQUIRE_FALSE( std::begin(ch) != std::end(ch) ); } SECTION("three empty containers") { auto ch = chain(emp, emp, emp); REQUIRE_FALSE( std::begin(ch) != std::end(ch) ); } } TEST_CASE("chain: doesn't move or copy elements of iterable", "[chain]") { constexpr SolidInt arr[] = {{6}, {7}, {8}}; for (auto&& i : chain(arr, arr)) { (void)i; } } TEST_CASE("chain: binds reference to lvalue and moves rvalue", "[chain]") { BasicIterable<char> bi{'x', 'y', 'z'}; BasicIterable<char> bi2{'a', 'j', 'm'}; SECTION("First moved, second ref'd") { chain(std::move(bi), bi2); REQUIRE( bi.was_moved_from() ); REQUIRE_FALSE( bi2.was_moved_from() ); } SECTION("First ref'd, second moved") { chain(bi, std::move(bi2)); REQUIRE_FALSE( bi.was_moved_from() ); REQUIRE( bi2.was_moved_from() ); } } TEST_CASE("chain: operator==", "[chain]") { std::string emp{}; auto ch = chain(emp); REQUIRE( std::begin(ch) == std::end(ch) ); } <commit_msg>tests chain postfix ++<commit_after>#include "helpers.hpp" #include <chain.hpp> #include <vector> #include <list> #include <string> #include <vector> #include <iterator> #include <utility> #include "catch.hpp" using iter::chain; using itertest::SolidInt; using itertest::BasicIterable; using Vec = const std::vector<char>; TEST_CASE("chain: three strings", "[chain]") { std::string s1{"abc"}; std::string s2{"mno"}; std::string s3{"xyz"}; auto ch = chain(s1, s2, s3); Vec v(std::begin(ch), std::end(ch)); Vec vc{'a','b','c','m','n','o','x','y','z'}; REQUIRE( v == vc ); } TEST_CASE("chain: with different container types", "[chain]") { std::string s1{"abc"}; std::list<char> li{'m', 'n', 'o'}; std::vector<char> vec{'x', 'y', 'z'}; auto ch = chain(s1, li, vec); Vec v(std::begin(ch), std::end(ch)); Vec vc{'a','b','c','m','n','o','x','y','z'}; REQUIRE( v == vc ); } TEST_CASE("chain: handles empty containers", "[chain]") { std::string emp; std::string a{"a"}; std::string b{"b"}; std::string c{"c"}; Vec vc{'a', 'b', 'c'}; SECTION("Empty container at front") { auto ch = chain(emp, a, b, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Empty container at back") { auto ch = chain(a, b, c, emp); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Empty container in middle") { auto ch = chain(a, emp, b, emp, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Consecutive empty containers at front") { auto ch = chain(emp, emp, a, b, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Consecutive empty containers at back") { auto ch = chain(a, b, c, emp, emp); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } SECTION("Consecutive empty containers in middle") { auto ch = chain(a, emp, emp, b, emp, emp, c); Vec v(std::begin(ch), std::end(ch)); REQUIRE( v == vc ); } } TEST_CASE("chain: with only empty containers", "[chain]") { std::string emp{}; SECTION("one empty container") { auto ch = chain(emp); REQUIRE_FALSE( std::begin(ch) != std::end(ch) ); } SECTION("two empty containers") { auto ch = chain(emp, emp); REQUIRE_FALSE( std::begin(ch) != std::end(ch) ); } SECTION("three empty containers") { auto ch = chain(emp, emp, emp); REQUIRE_FALSE( std::begin(ch) != std::end(ch) ); } } TEST_CASE("chain: doesn't move or copy elements of iterable", "[chain]") { constexpr SolidInt arr[] = {{6}, {7}, {8}}; for (auto&& i : chain(arr, arr)) { (void)i; } } TEST_CASE("chain: binds reference to lvalue and moves rvalue", "[chain]") { BasicIterable<char> bi{'x', 'y', 'z'}; BasicIterable<char> bi2{'a', 'j', 'm'}; SECTION("First moved, second ref'd") { chain(std::move(bi), bi2); REQUIRE( bi.was_moved_from() ); REQUIRE_FALSE( bi2.was_moved_from() ); } SECTION("First ref'd, second moved") { chain(bi, std::move(bi2)); REQUIRE_FALSE( bi.was_moved_from() ); REQUIRE( bi2.was_moved_from() ); } } TEST_CASE("chain: operator==", "[chain]") { std::string emp{}; auto ch = chain(emp); REQUIRE( std::begin(ch) == std::end(ch) ); } TEST_CASE("chain: postfix ++", "[chain]") { std::string s1{"a"}, s2{"b"}; auto ch = chain(s1, s2); auto it = std::begin(ch); it++; REQUIRE( *it == 'b'); } <|endoftext|>
<commit_before>#ifndef BST_HPP #define BST_HPP #include "BSTNode.hpp" #include "BSTIterator.hpp" #include <utility> // for std::pair template<typename Data> class BST { protected: /** Pointer to the root of this BST, or nullptr if the BST is empty */ BSTNode<Data>* root; /** Number of Data items stored in this BST. */ unsigned int isize; public: /** iterator is an aliased typename for BSTIterator<Data>. */ typedef BSTIterator<Data> iterator; /** Default constructor. Initialize an empty BST. */ BST() : root(nullptr), isize(0) { } /** Default destructor. * It is virtual, to allow appropriate destruction of subclass objects. * Delete every node in this BST. */ // TODO virtual ~BST() { delete (*this)->root; } /** Insert a Data item in the BST. * Return a pair, with the pair's first member set to an * iterator pointing to either the newly inserted element * or to the equivalent element already in the set. * The pair's second element is set to true * if a new element was inserted or false if an * equivalent element already existed. */ // TODO virtual std::pair<iterator,bool> insert(const Data& item) { return std::pair<a,b>; } /** Find a Data item in the BST. * Return an iterator pointing to the item, or the end * iterator if the item is not in the BST. */ // TODO iterator find(const Data& item) const { } /** Return the number of items currently in the BST. */ // TODO unsigned int size() const { return isize; } /** Remove all elements from this BST, and destroy them, * leaving this BST with a size of 0. */ // TODO void clear() { size = 0; } /** Return true if the BST is empty, else false. */ // TODO bool empty() const { return ( size == 0 ); } /** Return an iterator pointing to the first item in the BST. */ // TODO iterator begin() const { } /** Return an iterator pointing past the last item in the BST. */ iterator end() const { return typename BST<Data>::iterator(nullptr); } }; #endif //BST_HPP <commit_msg>untested begin()<commit_after>#ifndef BST_HPP #define BST_HPP #include "BSTNode.hpp" #include "BSTIterator.hpp" #include <utility> // for std::pair template<typename Data> class BST { protected: /** Pointer to the root of this BST, or nullptr if the BST is empty */ BSTNode<Data>* root; /** Number of Data items stored in this BST. */ unsigned int isize; public: /** iterator is an aliased typename for BSTIterator<Data>. */ typedef BSTIterator<Data> iterator; /** Default constructor. Initialize an empty BST. */ BST() : root(nullptr), isize(0) { } /** Default destructor. * It is virtual, to allow appropriate destruction of subclass objects. * Delete every node in this BST. */ // TODO virtual ~BST() { delete (*this)->root; } /** Insert a Data item in the BST. * Return a pair, with the pair's first member set to an * iterator pointing to either the newly inserted element * or to the equivalent element already in the set. * The pair's second element is set to true * if a new element was inserted or false if an * equivalent element already existed. */ // TODO virtual std::pair<iterator,bool> insert(const Data& item) { isize++; return std::pair<a,b>; } /** Find a Data item in the BST. * Return an iterator pointing to the item, or the end * iterator if the item is not in the BST. */ // TODO iterator find(const Data& item) const { BSTIterator<Data> iter = new BSTIterator<Data>((*this)->root); } /** Return the number of items currently in the BST. */ // TODO unsigned int size() const { return isize; } /** Remove all elements from this BST, and destroy them, * leaving this BST with a size of 0. */ // TODO void clear() { isize = 0; } /** Return true if the BST is empty, else false. */ // TODO bool empty() const { return ( isize == 0 ); } /** Return an iterator pointing to the first item in the BST. */ // TODO iterator begin() const { BSTNode<Data> temp = ( (*this)->root ); while (temp->left) temp = temp->left; return new BSTIterator<Data>(temp); } /** Return an iterator pointing past the last item in the BST. */ iterator end() const { return typename BST<Data>::iterator(nullptr); } }; #endif //BST_HPP <|endoftext|>
<commit_before>/* * NormalizedMutualInformation.cpp * * Created on: 30.04.2013 * Author: cls */ #include "NMIDistance.h" namespace NetworKit { NMIDistance::NMIDistance() { // TODO Auto-generated constructor stub } NMIDistance::~NMIDistance() { // TODO Auto-generated destructor stub } double NMIDistance::getDissimilarity(Graph& G, Clustering& zeta, Clustering& eta) { count n = G.numberOfNodes(); std::vector<count> size_zeta(zeta.upperBound()); std::vector<count> size_eta(eta.upperBound()); // precompute sizes for each cluster G.forNodes([&](node u){ cluster C = zeta[u]; cluster D = eta[u]; assert (C != none); assert (D != none); size_zeta[C] += 1; size_eta[D] += 1; }); DEBUG("size_zeta=" << Aux::vectorToString(size_zeta)); DEBUG("size_eta=" << Aux::vectorToString(size_eta)); // precompute cluster probabilities std::vector<double> P_zeta(zeta.upperBound(), 0.0); std::vector<double> P_eta(eta.upperBound(), 0.0); for (cluster C = zeta.lowerBound(); C < zeta.upperBound(); ++C) { P_zeta[C] = size_zeta[C] / (double) n; } for (cluster C = eta.lowerBound(); C < eta.upperBound(); ++C) { P_eta[C] = size_eta[C] / (double) n; } HashingOverlapper hashing; std::vector<Clustering> clusterings; clusterings.push_back(zeta); clusterings.push_back(eta); Clustering overlap = hashing.run(G, clusterings); DEBUG("overlap=" << Aux::vectorToString(overlap.getVector())); std::vector<std::vector<cluster> > intersect(zeta.upperBound(), std::vector<cluster>(eta.upperBound(), none)); // intersect[C][D] returns the overlap cluster std::vector<count> overlapSizes(overlap.upperBound(), 0); // overlapSizes[O] returns the size of the overlap cluster G.forNodes([&](node u){ cluster O = overlap[u]; cluster C = zeta[u]; cluster D = eta[u]; intersect[C][D] = O; // writes are redundant - but this may be efficient overlapSizes[O] += 1; }); /** * Return the size of the union of C and D. * C is a cluster in zeta, D in eta */ auto unionSize = [&](cluster C, cluster D){ cluster inter = intersect[C][D]; assert (inter != none); // entry must be set TRACE("clusters sized " << size_zeta[C] << " and " << size_eta[D] << " have overlap of " << overlapSizes[inter]); assert (overlapSizes[inter] >= 0); assert (overlapSizes[inter] <= std::max(size_zeta[C], size_eta[D])); return size_zeta[C] + size_eta[D] - overlapSizes[inter]; }; auto log_b = Aux::MissingMath::log_b; // import convenient logarithm function // calculate mutual information // $MI(\zeta,\eta):=\sum_{C\in\zeta}\sum_{D\in\eta}\frac{|C\cap D|}{n}\cdot\log_{2}\left(\frac{|C\cup D|\cdot n}{|C|\cdot|D|}\right)$ double MI = 0.0; // mutual information for (cluster C = 0; C < zeta.upperBound(); C++) { for (cluster D = 0; D < eta.upperBound(); D++) { count sizeC = size_zeta[C]; count sizeD = size_eta[D]; if ((sizeC != 0) && (sizeD != 0)) { double factor1 = overlapSizes[intersect[C][D]] / (double) n; assert ((size_zeta[C] * size_eta[D]) != 0); TRACE("union of " << C << " and " << D << ": " << unionSize(C, D)); double frac2 = (unionSize(C, D) * n) / (size_zeta[C] * size_eta[D]); double factor2 = log_b(frac2, 2); MI += factor1 * factor2; } } } // sanity check assert (! std::isnan(MI)); assert (MI >= 0.0); assert (MI <= 1.0); // compute entropy for both clusterings // $H(\zeta):=-\sum_{C\in\zeta}P(C)\cdot\log_{2}(P(C))$ double H_zeta = 0.0; for (cluster C = zeta.lowerBound(); C< zeta.upperBound(); ++C) { if (P_zeta[C] != 0) { H_zeta += P_zeta[C] * log_b(P_zeta[C], 2); } // log(0) is not defined } H_zeta = -1.0 * H_zeta; double H_eta = 0.0; for (cluster C = zeta.lowerBound(); C< zeta.upperBound(); ++C) { if (P_zeta[C] != 0) { H_eta += P_eta[C] * log_b(P_eta[C], 2); } // log(0) is not defined } H_eta = -1.0 * H_eta; assert (! std::isnan(H_zeta)); assert (! std::isnan(H_eta)); // entropy values range from 0 for the 1-clustering to log_2(n) for the singleton clustering assert (H_zeta >= 0.0); assert (H_eta >= 0.0); assert (H_zeta <= log_b(n, 2)); assert (H_zeta <= log_b(n, 2)); // calculate NMID // $NMI(\zeta,\eta):=\frac{2\cdot MI(\zeta,\eta)}{H(\zeta)+H\text{(\eta)}}$ // $NMID(\zeta,\eta):=\begin{cases} // 1-NMI(\zeta,\eta)\\ // 0 & H(\zeta)+H(\eta)=0 // \end{cases}$$ double NMID; double NMI; if ((H_zeta + H_eta) == 0) { NMID = 0.0; } else { NMI = (2 * MI) / (H_zeta + H_eta); NMID = 1.0 - NMI; } // sanity check assert (NMID >= 0.0); assert (NMID <= 1.0); return NMID; } } /* namespace NetworKit */ <commit_msg>debugged NMIDistance<commit_after>/* * NormalizedMutualInformation.cpp * * Created on: 30.04.2013 * Author: cls */ #include "NMIDistance.h" namespace NetworKit { NMIDistance::NMIDistance() { // TODO Auto-generated constructor stub } NMIDistance::~NMIDistance() { // TODO Auto-generated destructor stub } double NMIDistance::getDissimilarity(Graph& G, Clustering& zeta, Clustering& eta) { count n = G.numberOfNodes(); std::vector<count> size_zeta(zeta.upperBound()); std::vector<count> size_eta(eta.upperBound()); // precompute sizes for each cluster G.forNodes([&](node u){ cluster C = zeta[u]; cluster D = eta[u]; assert (C != none); assert (D != none); size_zeta[C] += 1; size_eta[D] += 1; }); DEBUG("size_zeta=" << Aux::vectorToString(size_zeta)); DEBUG("size_eta=" << Aux::vectorToString(size_eta)); // precompute cluster probabilities std::vector<double> P_zeta(zeta.upperBound(), 0.0); std::vector<double> P_eta(eta.upperBound(), 0.0); for (cluster C = zeta.lowerBound(); C < zeta.upperBound(); ++C) { P_zeta[C] = size_zeta[C] / (double) n; } for (cluster C = eta.lowerBound(); C < eta.upperBound(); ++C) { P_eta[C] = size_eta[C] / (double) n; } HashingOverlapper hashing; std::vector<Clustering> clusterings; clusterings.push_back(zeta); clusterings.push_back(eta); Clustering overlap = hashing.run(G, clusterings); DEBUG("overlap=" << Aux::vectorToString(overlap.getVector())); std::vector<std::vector<cluster> > intersect(zeta.upperBound(), std::vector<cluster>(eta.upperBound(), none)); // intersect[C][D] returns the overlap cluster std::vector<count> overlapSizes(overlap.upperBound(), 0); // overlapSizes[O] returns the size of the overlap cluster G.forNodes([&](node u){ cluster O = overlap[u]; cluster C = zeta[u]; cluster D = eta[u]; intersect[C][D] = O; // writes are redundant - but this may be efficient overlapSizes[O] += 1; }); /** * Return the size of the union of C and D. * C is a cluster in zeta, D in eta */ auto unionSize = [&](cluster C, cluster D){ cluster inter = intersect[C][D]; assert (inter != none); // entry must be set TRACE("clusters sized " << size_zeta[C] << " and " << size_eta[D] << " have overlap of " << overlapSizes[inter]); assert (overlapSizes[inter] >= 0); assert (overlapSizes[inter] <= std::max(size_zeta[C], size_eta[D])); return size_zeta[C] + size_eta[D] - overlapSizes[inter]; }; auto log_b = Aux::MissingMath::log_b; // import convenient logarithm function // calculate mutual information // $MI(\zeta,\eta):=\sum_{C\in\zeta}\sum_{D\in\eta}\frac{|C\cap D|}{n}\cdot\log_{2}\left(\frac{|C\cup D|\cdot n}{|C|\cdot|D|}\right)$ double MI = 0.0; // mutual information for (cluster C = 0; C < zeta.upperBound(); C++) { for (cluster D = 0; D < eta.upperBound(); D++) { count sizeC = size_zeta[C]; count sizeD = size_eta[D]; if ((sizeC != 0) && (sizeD != 0)) { // cluster ids may not correspond to a real cluster // the two clusters may or may not intersect cluster inter = intersect[C][D]; if (inter == none) { // clusters do not intersect TRACE("clusters do not intersect: " << C << ", " << D); } else { double factor1 = overlapSizes[inter] / (double) n; assert ((size_zeta[C] * size_eta[D]) != 0); TRACE("union of " << C << " and " << D << " has size: " << unionSize(C, D)); TRACE("overlap of " << C << " and " << D << " has size: " << overlapSizes[inter]); double frac2 = (overlapSizes[inter] * n) / (size_zeta[C] * size_eta[D]); double factor2 = log_b(frac2, 2); TRACE("frac2 = " << frac2 << ", factor1 = " << factor1 << ", factor2 = " << factor2); MI += factor1 * factor2; } } } } // sanity check assert (! std::isnan(MI)); assert (MI >= 0.0); // compute entropy for both clusterings // $H(\zeta):=-\sum_{C\in\zeta}P(C)\cdot\log_{2}(P(C))$ double H_zeta = 0.0; for (cluster C = zeta.lowerBound(); C< zeta.upperBound(); ++C) { if (P_zeta[C] != 0) { H_zeta += P_zeta[C] * log_b(P_zeta[C], 2); } // log(0) is not defined } H_zeta = -1.0 * H_zeta; double H_eta = 0.0; for (cluster C = zeta.lowerBound(); C< zeta.upperBound(); ++C) { if (P_zeta[C] != 0) { H_eta += P_eta[C] * log_b(P_eta[C], 2); } // log(0) is not defined } H_eta = -1.0 * H_eta; assert (! std::isnan(H_zeta)); assert (! std::isnan(H_eta)); // entropy values range from 0 for the 1-clustering to log_2(n) for the singleton clustering assert (H_zeta >= 0.0); assert (H_eta >= 0.0); assert (H_zeta <= log_b(n, 2)); assert (H_zeta <= log_b(n, 2)); // calculate NMID // $NMI(\zeta,\eta):=\frac{2\cdot MI(\zeta,\eta)}{H(\zeta)+H\text{(\eta)}}$ // $NMID(\zeta,\eta):=\begin{cases} // 1-NMI(\zeta,\eta)\\ // 0 & H(\zeta)+H(\eta)=0 // \end{cases}$$ double NMID; double NMI; if ((H_zeta + H_eta) == 0) { NMID = 0.0; } else { NMI = (2 * MI) / (H_zeta + H_eta); NMID = 1.0 - NMI; } // sanity check // assert (NMID >= 0.0); assert (NMID <= 1.0); return NMID; } } /* namespace NetworKit */ <|endoftext|>
<commit_before> // libPowerUP - Create games with SDL2 and OpenGL // Copyright(c) 2015, Erik Edlund <erik.edlund@32767.se> // All rights reserved. // // Redistribution and use in source and binary forms, with // or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above // copyright notice, this list of conditions and the // following disclaimer. // // 2. Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the // following disclaimer in the documentation and / or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names // of its contributors may be used to endorse or promote // products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND // CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. #include "pup_snd.h" namespace pup { namespace snd { sound::sound(const boost::filesystem::path& path) : chunk_(::Mix_LoadWAV(path.string().c_str())) { if (!chunk_) { PUP_ERR(std::runtime_error, boost::str(boost::format( "failed to load file \"%1%\"" ) % path)); } } sound::~sound() throw() { ::Mix_FreeChunk(chunk_); } bool sound::play(int channel, int loop) throw() { return ::Mix_PlayChannel(channel, chunk_, loop) != -1; } soundboard::soundboard() { } soundboard::~soundboard() throw() { } void soundboard::load_file(const boost::filesystem::path& path, const std::string& name) { if (!sounds_.insert(sound_map::value_type( name, sound_ptr(new sound(path))) ).second) { PUP_ERR(std::runtime_error, boost::str(boost::format( "name collision, sound with name \"%1%\" already exist" ) % name)); } } bool soundboard::play(const std::string& name, int channel, int loop) { auto it = sounds_.find(name); if (it != sounds_.end()) { return it->second->play(channel, loop); } return false; } music::music() : track_(nullptr) { } music::~music() throw() { this->stop(); } void music::start(const boost::filesystem::path& path, int repeat, int fadein) { this->stop(); if (!boost::filesystem::is_regular_file(path)) PUP_ERR(std::runtime_error, "given path is not a file"); if (!(track_ = ::Mix_LoadMUS(path.string().c_str()))) PUP_ERR(std::runtime_error, ::Mix_GetError()); ::Mix_FadeInMusic(track_, repeat, fadein); } void music::stop() throw() { if (track_) { ::Mix_HaltMusic(); ::Mix_FreeMusic(track_); track_ = nullptr; } } bool music::playing() const throw() { return ::Mix_PlayingMusic() == 1; } void music::fadeout(int duration) throw() { if (track_) { ::Mix_FadeOutMusic(duration); } } void music::set_volume(int volume) { ::Mix_VolumeMusic(volume); } int music::get_volume() const throw() { return ::Mix_VolumeMusic(-1); } jukebox::jukebox() : running_(false), random_(false), history_lim_(3) { track_ = files_.end(); } jukebox::~jukebox() throw() { } ::Uint32 jukebox::load_dir(const boost::filesystem::path& dir) { if (!boost::filesystem::is_directory(dir)) { PUP_ERR(std::runtime_error, boost::str(boost::format( "path \"%1%\" is not a directory") % dir.string() )); } files_.clear(); std::copy( boost::filesystem::directory_iterator(dir), boost::filesystem::directory_iterator(), std::back_inserter(files_) ); return this->filter_files(); } ::Uint32 jukebox::load_files(const io::path_list& files) { track_ = files_.end(); history_.clear(); files_.clear(); std::copy( files.begin(), files.end(), std::back_inserter(files_) ); return this->filter_files(); } void jukebox::update(music& mus) { if (running_ && !mus.playing() && !files_.empty()) { if (random_) { io::path_list::iterator it; do { it = pup::random_element(files_.begin(), files_.end()); //for (auto jit : files_) std::cout << jit << std::endl; } while (std::find(history_.begin(), history_.end(), *it) != history_.end()); mus.start(*it); history_.push_back(*it); if (static_cast<int>(history_.size()) == history_lim_) { history_.pop_front(); } track_ = it; } else { if (track_ == files_.end()) { track_ = files_.begin(); } auto it = track_++; mus.start(*it); } } } ::Uint32 jukebox::filter_files() { for (auto it = files_.begin(); it != files_.end(); /* in-loop */) { if ( boost::filesystem::is_regular_file(*it) && it->extension().string() == ".wav" ) { ++it; } else { it = files_.erase(it); } } return files_.size(); } } // snd } // pup <commit_msg>Allow the jukebox to play wav, mp3 and ogg.<commit_after> // libPowerUP - Create games with SDL2 and OpenGL // Copyright(c) 2015, Erik Edlund <erik.edlund@32767.se> // All rights reserved. // // Redistribution and use in source and binary forms, with // or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above // copyright notice, this list of conditions and the // following disclaimer. // // 2. Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the // following disclaimer in the documentation and / or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names // of its contributors may be used to endorse or promote // products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND // CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. #include "pup_snd.h" namespace pup { namespace snd { sound::sound(const boost::filesystem::path& path) : chunk_(::Mix_LoadWAV(path.string().c_str())) { if (!chunk_) { PUP_ERR(std::runtime_error, boost::str(boost::format( "failed to load file \"%1%\"" ) % path)); } } sound::~sound() throw() { ::Mix_FreeChunk(chunk_); } bool sound::play(int channel, int loop) throw() { return ::Mix_PlayChannel(channel, chunk_, loop) != -1; } soundboard::soundboard() { } soundboard::~soundboard() throw() { } void soundboard::load_file(const boost::filesystem::path& path, const std::string& name) { if (!sounds_.insert(sound_map::value_type( name, sound_ptr(new sound(path))) ).second) { PUP_ERR(std::runtime_error, boost::str(boost::format( "name collision, sound with name \"%1%\" already exist" ) % name)); } } bool soundboard::play(const std::string& name, int channel, int loop) { auto it = sounds_.find(name); if (it != sounds_.end()) { return it->second->play(channel, loop); } return false; } music::music() : track_(nullptr) { } music::~music() throw() { this->stop(); } void music::start(const boost::filesystem::path& path, int repeat, int fadein) { this->stop(); if (!boost::filesystem::is_regular_file(path)) PUP_ERR(std::runtime_error, "given path is not a file"); if (!(track_ = ::Mix_LoadMUS(path.string().c_str()))) PUP_ERR(std::runtime_error, ::Mix_GetError()); ::Mix_FadeInMusic(track_, repeat, fadein); } void music::stop() throw() { if (track_) { ::Mix_HaltMusic(); ::Mix_FreeMusic(track_); track_ = nullptr; } } bool music::playing() const throw() { return ::Mix_PlayingMusic() == 1; } void music::fadeout(int duration) throw() { if (track_) { ::Mix_FadeOutMusic(duration); } } void music::set_volume(int volume) { ::Mix_VolumeMusic(volume); } int music::get_volume() const throw() { return ::Mix_VolumeMusic(-1); } jukebox::jukebox() : running_(false), random_(false), history_lim_(3) { track_ = files_.end(); } jukebox::~jukebox() throw() { } ::Uint32 jukebox::load_dir(const boost::filesystem::path& dir) { if (!boost::filesystem::is_directory(dir)) { PUP_ERR(std::runtime_error, boost::str(boost::format( "path \"%1%\" is not a directory") % dir.string() )); } files_.clear(); std::copy( boost::filesystem::directory_iterator(dir), boost::filesystem::directory_iterator(), std::back_inserter(files_) ); return this->filter_files(); } ::Uint32 jukebox::load_files(const io::path_list& files) { track_ = files_.end(); history_.clear(); files_.clear(); std::copy( files.begin(), files.end(), std::back_inserter(files_) ); return this->filter_files(); } void jukebox::update(music& mus) { if (running_ && !mus.playing() && !files_.empty()) { if (random_) { io::path_list::iterator it; do { it = pup::random_element(files_.begin(), files_.end()); } while (std::find(history_.begin(), history_.end(), *it) != history_.end()); mus.start(*it); history_.push_back(*it); if (static_cast<int>(history_.size()) == history_lim_) { history_.pop_front(); } track_ = it; } else { if (track_ == files_.end()) { track_ = files_.begin(); } auto it = track_++; mus.start(*it); } } } ::Uint32 jukebox::filter_files() { for (auto it = files_.begin(); it != files_.end(); /* in-loop */) { if ( boost::filesystem::is_regular_file(*it) && ( it->extension().string() == ".mp3" || it->extension().string() == ".ogg" || it->extension().string() == ".wav" ) ) { ++it; } else { it = files_.erase(it); } } return files_.size(); } } // snd } // pup <|endoftext|>
<commit_before> #include <chrono> #include <iostream> #include <fstream> #include "RMDP.hpp" using namespace std; using namespace craam; int main(int argc, char * argv []){ if(argc != 2){ cout << "Invalid execution parameters. Execute as: " << endl; cout << argv[0] << " mdp_file " << endl; return -1; } string filename = argv[1]; cout << "loading" << endl; ifstream ifs; ifs.open(filename); if(!ifs.is_open()){ cout << "file could not be open"; return -1; } auto rmdp = RMDP::transitions_from_csv(ifs,true); ifs.close(); cout << "running test" << endl; auto start = std::chrono::high_resolution_clock::now(); //#include <gperftools/profiler.h> // library option -lprofiler //ProfilerStart("mpi.prof"); vector<prec_t> value(rmdp->state_count()); auto&& sol = rmdp->mpi_jac_rob(value,0.999,2000,0.0001,2000,0.0001); //ProfilerStop(); auto finish = std::chrono::high_resolution_clock::now(); cout << "done." <<endl; cout << "Iterations: " << sol.iterations << ", Residual: " << sol.residual << endl; std::cout << "Duration: *** " << std::chrono::duration_cast<std::chrono::milliseconds>(finish-start).count() << "ms *** \n"; } <commit_msg>Fixed a problem with the benchmark<commit_after> #include <chrono> #include <iostream> #include <fstream> #include "RMDP.hpp" using namespace std; using namespace craam; int main(int argc, char * argv []){ if(argc != 2){ cout << "Invalid execution parameters. Execute as: " << endl; cout << argv[0] << " mdp_file " << endl; return -1; } string filename = argv[1]; cout << "loading" << endl; ifstream ifs; ifs.open(filename); if(!ifs.is_open()){ cout << "file could not be open"; return -1; } auto rmdp = RMDP::from_csv(ifs,true); ifs.close(); cout << "running test" << endl; auto start = std::chrono::high_resolution_clock::now(); //#include <gperftools/profiler.h> // library option -lprofiler //ProfilerStart("mpi.prof"); vector<prec_t> value(rmdp->state_count()); auto&& sol = rmdp->mpi_jac_rob(value,0.999,2000,0.0001,2000,0.0001); //ProfilerStop(); auto finish = std::chrono::high_resolution_clock::now(); cout << "done." <<endl; cout << "Iterations: " << sol.iterations << ", Residual: " << sol.residual << endl; std::cout << "Duration: *** " << std::chrono::duration_cast<std::chrono::milliseconds>(finish-start).count() << "ms *** \n"; } <|endoftext|>
<commit_before>/***************************************************************************** * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011 Canonical Ltd. * * 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 (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 * 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 "xorg/gtest/environment.h" #include "xorg/gtest/process.h" #include <errno.h> #include <signal.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <cstring> #include <iostream> #include <X11/Xlib.h> struct xorg::testing::Environment::Private { std::string path_to_conf; int display; Process process; }; xorg::testing::Environment::Environment(const std::string& path, int display) : d_(new Private) { d_->path_to_conf = path; d_->display = display; } xorg::testing::Environment::~Environment() { delete d_; } void xorg::testing::Environment::SetUp() { static char display_string[6]; snprintf(display_string, 6, ":%d", d_->display); if (d_->process.Start("Xorg", display_string, d_->path_to_conf.c_str())) { setenv("DISPLAY", display_string, true); for (int i = 0; i < 10; /*++i*/) { Display* display = XOpenDisplay(NULL); if (display) { XCloseDisplay(display); return; } int status; int pid = d_->process.Wait(&status, WNOHANG); //waitpid(d_->child_pid_, &status, WNOHANG); if (pid == d_->process.pid()) { // d_->child_pid_ = -1; FAIL() << "Dummy X server failed to start, did you run as root?"; return; } else if (pid == 0) { sleep(1); /* Give the dummy X server some time to start */ continue; } else if (pid == -1) { FAIL() << "Could not get status of dummy X server process: " << std::strerror(errno); return; } else { FAIL() << "Invalid child PID returned by waitpid()"; return; } } FAIL() << "Unable to open connection to dummy X server"; } #if 0 d_->child_pid_ = vfork(); if (d_->child_pid_ == -1) { FAIL() << "Failed to fork a process for dummy X server: " << std::strerror(errno); } else if (!d_->child_pid_) { /* Child */ close(0); close(1); close(2); execlp("Xorg", "Xorg", display_string, "-config", d_->path_to_conf_.c_str(), NULL); perror("Failed to start dummy X server"); exit(-1); } else { /* Parent */ setenv("DISPLAY", display_string, true); for (int i = 0; i < 10; /*++i*/) { Display* display = XOpenDisplay(NULL); if (display) { XCloseDisplay(display); return; } int status; int pid = waitpid(d_->child_pid_, &status, WNOHANG); if (pid == d_->child_pid_) { d_->child_pid_ = -1; FAIL() << "Dummy X server failed to start, did you run as root?"; return; } else if (pid == 0) { sleep(1); /* Give the dummy X server some time to start */ continue; } else if (pid == -1) { FAIL() << "Could not get status of dummy X server process: " << std::strerror(errno); return; } else { FAIL() << "Invalid child PID returned by waitpid()"; return; } } FAIL() << "Unable to open connection to dummy X server"; } #endif } void xorg::testing::Environment::TearDown() { if (!d_->process.Terminate()) { FAIL() << "Warning: Failed to terminate dummy Xorg server: " << std::strerror(errno); if (!d_->process.Kill()) FAIL() << "Warning: Failed to kill dummy Xorg server: " << std::strerror(errno); } #if 0 if (d_->child_pid_ && d_->child_pid_ != -1) { if (kill(d_->child_pid_, SIGTERM) < 0) { FAIL() << "Warning: Failed to terminate dummy Xorg server: " << std::strerror(errno); if (kill(d_->child_pid_, SIGKILL)) FAIL() << "Warning: Failed to kill dummy Xorg server: " << std::strerror(errno); } } #endif } <commit_msg>Remove dead code in Environment<commit_after>/***************************************************************************** * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011 Canonical Ltd. * * 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 (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 * 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 "xorg/gtest/environment.h" #include "xorg/gtest/process.h" #include <errno.h> #include <signal.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <cstring> #include <iostream> #include <X11/Xlib.h> struct xorg::testing::Environment::Private { std::string path_to_conf; int display; Process process; }; xorg::testing::Environment::Environment(const std::string& path, int display) : d_(new Private) { d_->path_to_conf = path; d_->display = display; } xorg::testing::Environment::~Environment() { delete d_; } void xorg::testing::Environment::SetUp() { static char display_string[6]; snprintf(display_string, 6, ":%d", d_->display); if (d_->process.Start("Xorg", display_string, d_->path_to_conf.c_str())) { setenv("DISPLAY", display_string, true); for (int i = 0; i < 10; /*++i*/) { Display* display = XOpenDisplay(NULL); if (display) { XCloseDisplay(display); return; } int status; int pid = d_->process.Wait(&status, WNOHANG); if (pid == d_->process.pid()) { FAIL() << "Dummy X server failed to start, did you run as root?"; return; } else if (pid == 0) { sleep(1); /* Give the dummy X server some time to start */ continue; } else if (pid == -1) { FAIL() << "Could not get status of dummy X server process: " << std::strerror(errno); return; } else { FAIL() << "Invalid child PID returned by waitpid()"; return; } } FAIL() << "Unable to open connection to dummy X server"; } } void xorg::testing::Environment::TearDown() { if (!d_->process.Terminate()) { FAIL() << "Warning: Failed to terminate dummy Xorg server: " << std::strerror(errno); if (!d_->process.Kill()) FAIL() << "Warning: Failed to kill dummy Xorg server: " << std::strerror(errno); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: provider.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: obo $ $Date: 2008-03-25 15:21:52 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmlhelp.hxx" /************************************************************************** TODO ************************************************************************** *************************************************************************/ #include <stdio.h> #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _VOS_DIAGNOSE_HXX_ #include <vos/diagnose.hxx> #endif #ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX #include <ucbhelper/contentidentifier.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_ #include <com/sun/star/frame/XConfigManager.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYSTATE_HPP_ #include <com/sun/star/beans/PropertyState.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_ #include <com/sun/star/container/XContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEREPLACE_HPP_ #include <com/sun/star/container/XNameReplace.hpp> #endif #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include "databases.hxx" #include "provider.hxx" #include "content.hxx" #include "databases.hxx" using namespace com::sun::star; using namespace chelp; //========================================================================= //========================================================================= // // ContentProvider Implementation. // //========================================================================= //========================================================================= ContentProvider::ContentProvider( const uno::Reference< lang::XMultiServiceFactory >& rSMgr ) : ::ucbhelper::ContentProviderImplHelper( rSMgr ), isInitialized( false ), m_aScheme( rtl::OUString::createFromAscii( MYUCP_URL_SCHEME ) ), m_pDatabases( 0 ) { } //========================================================================= // virtual ContentProvider::~ContentProvider() { delete m_pDatabases; } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_IMPL_6( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, ucb::XContentProvider, lang::XComponent, lang::XEventListener, /* base of XContainerListener */ container::XContainerListener); //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_IMPL_5( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, ucb::XContentProvider, lang::XComponent, container::XContainerListener); //========================================================================= // // XServiceInfo methods. // //========================================================================= rtl::OUString SAL_CALL ContentProvider::getImplementationName() throw( uno::RuntimeException ) { return getImplementationName_Static(); } rtl::OUString ContentProvider::getImplementationName_Static() { return rtl::OUString::createFromAscii("CHelpContentProvider" ); } sal_Bool SAL_CALL ContentProvider::supportsService(const rtl::OUString& ServiceName ) throw( uno::RuntimeException ) { uno::Sequence< rtl::OUString > aSNL = getSupportedServiceNames(); const rtl::OUString* pArray = aSNL.getArray(); for( sal_Int32 i = 0; i < aSNL.getLength(); i++ ) { if( pArray[ i ] == ServiceName ) return sal_True; } return sal_False; } uno::Sequence< rtl::OUString > SAL_CALL ContentProvider::getSupportedServiceNames() throw( uno::RuntimeException ) { return getSupportedServiceNames_Static(); } static uno::Reference< uno::XInterface > SAL_CALL ContentProvider_CreateInstance( const uno::Reference< lang::XMultiServiceFactory> & rSMgr ) throw( uno::Exception ) { lang::XServiceInfo * pX = static_cast< lang::XServiceInfo * >( new ContentProvider( rSMgr ) ); return uno::Reference< uno::XInterface >::query( pX ); } uno::Sequence< rtl::OUString > ContentProvider::getSupportedServiceNames_Static() { uno::Sequence< rtl::OUString > aSNS( 2 ); aSNS.getArray()[ 0 ] = rtl::OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME1 ); aSNS.getArray()[ 1 ] = rtl::OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME2 ); return aSNS; } //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual uno::Reference< ucb::XContent > SAL_CALL ContentProvider::queryContent( const uno::Reference< ucb::XContentIdentifier >& xCanonicId ) throw( ucb::IllegalIdentifierException, uno::RuntimeException ) { if ( !xCanonicId->getContentProviderScheme() .equalsIgnoreAsciiCase( m_aScheme ) ) { // Wrong URL-scheme throw ucb::IllegalIdentifierException(); } { osl::MutexGuard aGuard( m_aMutex ); if( !isInitialized ) init(); } if( !m_pDatabases ) throw uno::RuntimeException(); rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() ); rtl::OString aOString( aOUString.getStr(), aOUString.getLength(), RTL_TEXTENCODING_UTF8 ); // Check, if a content with given id already exists... uno::Reference< ucb::XContent > xContent = queryExistingContent( xCanonicId ).get(); if ( xContent.is() ) return xContent; xContent = new Content( m_xSMgr, this, xCanonicId, m_pDatabases ); // register new content registerNewContent( xContent ); // Further checks if ( !xContent->getIdentifier().is() ) throw ucb::IllegalIdentifierException(); return xContent; } void SAL_CALL ContentProvider::dispose() throw ( uno::RuntimeException) { if(m_xContainer.is()) { m_xContainer->removeContainerListener(this); m_xContainer.clear(); } } void SAL_CALL ContentProvider::elementReplaced(const container::ContainerEvent& Event) throw (uno::RuntimeException) { if(!m_pDatabases) return; rtl::OUString accessor; Event.Accessor >>= accessor; if(accessor.compareToAscii("HelpStyleSheet")) return; rtl::OUString replacedElement,element; Event.ReplacedElement >>= replacedElement; Event.Element >>= element; if(replacedElement == element) return; m_pDatabases->changeCSS(element); } void ContentProvider::init() { osl::MutexGuard aGuard( m_aMutex ); isInitialized = true; uno::Reference< lang::XMultiServiceFactory > sProvider( getConfiguration() ); uno::Reference< container::XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider, "org.openoffice.Office.Common" ) ); rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) ); if( ! instPath.getLength() ) // try to determine path from default instPath = rtl::OUString::createFromAscii( "$(instpath)/help" ); // replace anything like $(instpath); subst( instPath ); rtl::OUString stylesheet( getKey( xHierAccess,"Help/HelpStyleSheet" ) ); try { // now adding as configuration change listener for the stylesheet uno::Reference< container::XNameAccess> xAccess( xHierAccess, uno::UNO_QUERY ); if( xAccess.is() ) { uno::Any aAny = xAccess->getByName( rtl::OUString::createFromAscii( "Help" ) ); aAny >>= m_xContainer; if( m_xContainer.is() ) m_xContainer->addContainerListener( this ); } } catch( uno::Exception const & ) { } /** * now determing * productname, * productversion, * vendorname, * vendorversion, * vendorshort */ xHierAccess = getHierAccess( sProvider, "org.openoffice.Setup" ); rtl::OUString productname( getKey( xHierAccess,"Product/ooName" ) ); rtl::OUString setupversion( getKey( xHierAccess,"Product/ooSetupVersion" ) ); rtl::OUString setupextension( getKey( xHierAccess,"Product/ooSetupExtension") ); rtl::OUString productversion( setupversion + rtl::OUString::createFromAscii( " " ) + setupextension ); xHierAccess = getHierAccess( sProvider, "org.openoffice.Webtop.Common" ); rtl::OUString vendorname( getKey( xHierAccess,"Product/ooName" ) ); setupversion = rtl::OUString( getKey( xHierAccess,"Product/ooSetupVersion" ) ); setupextension = rtl::OUString( getKey( xHierAccess,"Product/ooSetupExtension") ); rtl::OUString vendorversion( setupversion + rtl::OUString::createFromAscii( " " ) + setupextension ); rtl::OUString vendorshort = vendorname; uno::Sequence< rtl::OUString > aImagesZipPaths( 2 ); xHierAccess = getHierAccess( sProvider, "org.openoffice.Office.Common" ); rtl::OUString aPath( getKey( xHierAccess, "Path/Current/UserConfig" ) ); subst( aPath ); aImagesZipPaths[ 0 ] = aPath; aPath = getKey( xHierAccess, "Path/Current/Config" ); subst( aPath ); aImagesZipPaths[ 1 ] = aPath; uno::Reference< uno::XComponentContext > xContext; uno::Reference< beans::XPropertySet > xProps( m_xSMgr, uno::UNO_QUERY ); OSL_ASSERT( xProps.is() ); if (xProps.is()) { xProps->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("DefaultContext") ) ) >>= xContext; OSL_ASSERT( xContext.is() ); } sal_Bool showBasic = getBooleanKey(xHierAccess,"Help/ShowBasic"); m_pDatabases = new Databases( showBasic, instPath, aImagesZipPaths, productname, productversion, vendorname, vendorversion, vendorshort, stylesheet, xContext ); } uno::Reference< lang::XMultiServiceFactory > ContentProvider::getConfiguration() const { uno::Reference< lang::XMultiServiceFactory > sProvider; if( m_xSMgr.is() ) { uno::Any aAny; aAny <<= rtl::OUString::createFromAscii( "plugin" ); beans::PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ), -1, aAny, beans::PropertyState_DIRECT_VALUE ); uno::Sequence< uno::Any > seq(1); seq[0] <<= aProp; try { rtl::OUString sProviderService = rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationProvider" ); sProvider = uno::Reference< lang::XMultiServiceFactory >( m_xSMgr->createInstanceWithArguments( sProviderService,seq ), uno::UNO_QUERY ); } catch( const uno::Exception& ) { OSL_ENSURE( sProvider.is(), "cant instantiate configuration" ); } } return sProvider; } uno::Reference< container::XHierarchicalNameAccess > ContentProvider::getHierAccess( const uno::Reference< lang::XMultiServiceFactory >& sProvider, const char* file ) const { uno::Reference< container::XHierarchicalNameAccess > xHierAccess; if( sProvider.is() ) { uno::Sequence< uno::Any > seq( 1 ); rtl::OUString sReaderService( rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" ) ); seq[ 0 ] <<= rtl::OUString::createFromAscii( file ); try { xHierAccess = uno::Reference< container::XHierarchicalNameAccess >( sProvider->createInstanceWithArguments( sReaderService, seq ), uno::UNO_QUERY ); } catch( const uno::Exception& ) { } } return xHierAccess; } rtl::OUString ContentProvider::getKey( const uno::Reference< container::XHierarchicalNameAccess >& xHierAccess, const char* key ) const { rtl::OUString instPath; if( xHierAccess.is() ) { uno::Any aAny; try { aAny = xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii( key ) ); } catch( const container::NoSuchElementException& ) { } aAny >>= instPath; } return instPath; } sal_Bool ContentProvider::getBooleanKey( const uno::Reference< container::XHierarchicalNameAccess >& xHierAccess, const char* key ) const { sal_Bool ret = sal_False; if( xHierAccess.is() ) { uno::Any aAny; try { aAny = xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii( key ) ); } catch( const container::NoSuchElementException& ) { } aAny >>= ret; } return ret; } void ContentProvider::subst( rtl::OUString& instpath ) const { uno::Reference< frame::XConfigManager > xCfgMgr; if( m_xSMgr.is() ) { try { xCfgMgr = uno::Reference< frame::XConfigManager >( m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ), uno::UNO_QUERY ); } catch( const uno::Exception&) { OSL_ENSURE( xCfgMgr.is(), "cant instantiate the special config manager " ); } } OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" ); if( xCfgMgr.is() ) instpath = xCfgMgr->substituteVariables( instpath ); } <commit_msg>INTEGRATION: CWS changefileheader (1.24.2); FILE MERGED 2008/04/01 16:07:43 thb 1.24.2.3: #i85898# Stripping all external header guards 2008/04/01 13:02:58 thb 1.24.2.2: #i85898# Stripping all external header guards 2008/03/31 13:04:25 rt 1.24.2.1: #i87441# Change license header to LPGL v3.<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: provider.cxx,v $ * $Revision: 1.25 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmlhelp.hxx" /************************************************************************** TODO ************************************************************************** *************************************************************************/ #include <stdio.h> #include <osl/file.hxx> #ifndef _VOS_DIAGNOSE_HXX_ #include <vos/diagnose.hxx> #endif #include <ucbhelper/contentidentifier.hxx> #include <com/sun/star/frame/XConfigManager.hpp> #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/PropertyState.hpp> #include <com/sun/star/container/XContainer.hpp> #include <com/sun/star/container/XNameAccess.hpp> #include <com/sun/star/container/XNameReplace.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include "databases.hxx" #include "provider.hxx" #include "content.hxx" #include "databases.hxx" using namespace com::sun::star; using namespace chelp; //========================================================================= //========================================================================= // // ContentProvider Implementation. // //========================================================================= //========================================================================= ContentProvider::ContentProvider( const uno::Reference< lang::XMultiServiceFactory >& rSMgr ) : ::ucbhelper::ContentProviderImplHelper( rSMgr ), isInitialized( false ), m_aScheme( rtl::OUString::createFromAscii( MYUCP_URL_SCHEME ) ), m_pDatabases( 0 ) { } //========================================================================= // virtual ContentProvider::~ContentProvider() { delete m_pDatabases; } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_IMPL_6( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, ucb::XContentProvider, lang::XComponent, lang::XEventListener, /* base of XContainerListener */ container::XContainerListener); //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_IMPL_5( ContentProvider, lang::XTypeProvider, lang::XServiceInfo, ucb::XContentProvider, lang::XComponent, container::XContainerListener); //========================================================================= // // XServiceInfo methods. // //========================================================================= rtl::OUString SAL_CALL ContentProvider::getImplementationName() throw( uno::RuntimeException ) { return getImplementationName_Static(); } rtl::OUString ContentProvider::getImplementationName_Static() { return rtl::OUString::createFromAscii("CHelpContentProvider" ); } sal_Bool SAL_CALL ContentProvider::supportsService(const rtl::OUString& ServiceName ) throw( uno::RuntimeException ) { uno::Sequence< rtl::OUString > aSNL = getSupportedServiceNames(); const rtl::OUString* pArray = aSNL.getArray(); for( sal_Int32 i = 0; i < aSNL.getLength(); i++ ) { if( pArray[ i ] == ServiceName ) return sal_True; } return sal_False; } uno::Sequence< rtl::OUString > SAL_CALL ContentProvider::getSupportedServiceNames() throw( uno::RuntimeException ) { return getSupportedServiceNames_Static(); } static uno::Reference< uno::XInterface > SAL_CALL ContentProvider_CreateInstance( const uno::Reference< lang::XMultiServiceFactory> & rSMgr ) throw( uno::Exception ) { lang::XServiceInfo * pX = static_cast< lang::XServiceInfo * >( new ContentProvider( rSMgr ) ); return uno::Reference< uno::XInterface >::query( pX ); } uno::Sequence< rtl::OUString > ContentProvider::getSupportedServiceNames_Static() { uno::Sequence< rtl::OUString > aSNS( 2 ); aSNS.getArray()[ 0 ] = rtl::OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME1 ); aSNS.getArray()[ 1 ] = rtl::OUString::createFromAscii( MYUCP_CONTENT_PROVIDER_SERVICE_NAME2 ); return aSNS; } //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( ContentProvider ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual uno::Reference< ucb::XContent > SAL_CALL ContentProvider::queryContent( const uno::Reference< ucb::XContentIdentifier >& xCanonicId ) throw( ucb::IllegalIdentifierException, uno::RuntimeException ) { if ( !xCanonicId->getContentProviderScheme() .equalsIgnoreAsciiCase( m_aScheme ) ) { // Wrong URL-scheme throw ucb::IllegalIdentifierException(); } { osl::MutexGuard aGuard( m_aMutex ); if( !isInitialized ) init(); } if( !m_pDatabases ) throw uno::RuntimeException(); rtl::OUString aOUString( m_pDatabases->getInstallPathAsURL() ); rtl::OString aOString( aOUString.getStr(), aOUString.getLength(), RTL_TEXTENCODING_UTF8 ); // Check, if a content with given id already exists... uno::Reference< ucb::XContent > xContent = queryExistingContent( xCanonicId ).get(); if ( xContent.is() ) return xContent; xContent = new Content( m_xSMgr, this, xCanonicId, m_pDatabases ); // register new content registerNewContent( xContent ); // Further checks if ( !xContent->getIdentifier().is() ) throw ucb::IllegalIdentifierException(); return xContent; } void SAL_CALL ContentProvider::dispose() throw ( uno::RuntimeException) { if(m_xContainer.is()) { m_xContainer->removeContainerListener(this); m_xContainer.clear(); } } void SAL_CALL ContentProvider::elementReplaced(const container::ContainerEvent& Event) throw (uno::RuntimeException) { if(!m_pDatabases) return; rtl::OUString accessor; Event.Accessor >>= accessor; if(accessor.compareToAscii("HelpStyleSheet")) return; rtl::OUString replacedElement,element; Event.ReplacedElement >>= replacedElement; Event.Element >>= element; if(replacedElement == element) return; m_pDatabases->changeCSS(element); } void ContentProvider::init() { osl::MutexGuard aGuard( m_aMutex ); isInitialized = true; uno::Reference< lang::XMultiServiceFactory > sProvider( getConfiguration() ); uno::Reference< container::XHierarchicalNameAccess > xHierAccess( getHierAccess( sProvider, "org.openoffice.Office.Common" ) ); rtl::OUString instPath( getKey( xHierAccess,"Path/Current/Help" ) ); if( ! instPath.getLength() ) // try to determine path from default instPath = rtl::OUString::createFromAscii( "$(instpath)/help" ); // replace anything like $(instpath); subst( instPath ); rtl::OUString stylesheet( getKey( xHierAccess,"Help/HelpStyleSheet" ) ); try { // now adding as configuration change listener for the stylesheet uno::Reference< container::XNameAccess> xAccess( xHierAccess, uno::UNO_QUERY ); if( xAccess.is() ) { uno::Any aAny = xAccess->getByName( rtl::OUString::createFromAscii( "Help" ) ); aAny >>= m_xContainer; if( m_xContainer.is() ) m_xContainer->addContainerListener( this ); } } catch( uno::Exception const & ) { } /** * now determing * productname, * productversion, * vendorname, * vendorversion, * vendorshort */ xHierAccess = getHierAccess( sProvider, "org.openoffice.Setup" ); rtl::OUString productname( getKey( xHierAccess,"Product/ooName" ) ); rtl::OUString setupversion( getKey( xHierAccess,"Product/ooSetupVersion" ) ); rtl::OUString setupextension( getKey( xHierAccess,"Product/ooSetupExtension") ); rtl::OUString productversion( setupversion + rtl::OUString::createFromAscii( " " ) + setupextension ); xHierAccess = getHierAccess( sProvider, "org.openoffice.Webtop.Common" ); rtl::OUString vendorname( getKey( xHierAccess,"Product/ooName" ) ); setupversion = rtl::OUString( getKey( xHierAccess,"Product/ooSetupVersion" ) ); setupextension = rtl::OUString( getKey( xHierAccess,"Product/ooSetupExtension") ); rtl::OUString vendorversion( setupversion + rtl::OUString::createFromAscii( " " ) + setupextension ); rtl::OUString vendorshort = vendorname; uno::Sequence< rtl::OUString > aImagesZipPaths( 2 ); xHierAccess = getHierAccess( sProvider, "org.openoffice.Office.Common" ); rtl::OUString aPath( getKey( xHierAccess, "Path/Current/UserConfig" ) ); subst( aPath ); aImagesZipPaths[ 0 ] = aPath; aPath = getKey( xHierAccess, "Path/Current/Config" ); subst( aPath ); aImagesZipPaths[ 1 ] = aPath; uno::Reference< uno::XComponentContext > xContext; uno::Reference< beans::XPropertySet > xProps( m_xSMgr, uno::UNO_QUERY ); OSL_ASSERT( xProps.is() ); if (xProps.is()) { xProps->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("DefaultContext") ) ) >>= xContext; OSL_ASSERT( xContext.is() ); } sal_Bool showBasic = getBooleanKey(xHierAccess,"Help/ShowBasic"); m_pDatabases = new Databases( showBasic, instPath, aImagesZipPaths, productname, productversion, vendorname, vendorversion, vendorshort, stylesheet, xContext ); } uno::Reference< lang::XMultiServiceFactory > ContentProvider::getConfiguration() const { uno::Reference< lang::XMultiServiceFactory > sProvider; if( m_xSMgr.is() ) { uno::Any aAny; aAny <<= rtl::OUString::createFromAscii( "plugin" ); beans::PropertyValue aProp( rtl::OUString::createFromAscii( "servertype" ), -1, aAny, beans::PropertyState_DIRECT_VALUE ); uno::Sequence< uno::Any > seq(1); seq[0] <<= aProp; try { rtl::OUString sProviderService = rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationProvider" ); sProvider = uno::Reference< lang::XMultiServiceFactory >( m_xSMgr->createInstanceWithArguments( sProviderService,seq ), uno::UNO_QUERY ); } catch( const uno::Exception& ) { OSL_ENSURE( sProvider.is(), "cant instantiate configuration" ); } } return sProvider; } uno::Reference< container::XHierarchicalNameAccess > ContentProvider::getHierAccess( const uno::Reference< lang::XMultiServiceFactory >& sProvider, const char* file ) const { uno::Reference< container::XHierarchicalNameAccess > xHierAccess; if( sProvider.is() ) { uno::Sequence< uno::Any > seq( 1 ); rtl::OUString sReaderService( rtl::OUString::createFromAscii( "com.sun.star.configuration.ConfigurationAccess" ) ); seq[ 0 ] <<= rtl::OUString::createFromAscii( file ); try { xHierAccess = uno::Reference< container::XHierarchicalNameAccess >( sProvider->createInstanceWithArguments( sReaderService, seq ), uno::UNO_QUERY ); } catch( const uno::Exception& ) { } } return xHierAccess; } rtl::OUString ContentProvider::getKey( const uno::Reference< container::XHierarchicalNameAccess >& xHierAccess, const char* key ) const { rtl::OUString instPath; if( xHierAccess.is() ) { uno::Any aAny; try { aAny = xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii( key ) ); } catch( const container::NoSuchElementException& ) { } aAny >>= instPath; } return instPath; } sal_Bool ContentProvider::getBooleanKey( const uno::Reference< container::XHierarchicalNameAccess >& xHierAccess, const char* key ) const { sal_Bool ret = sal_False; if( xHierAccess.is() ) { uno::Any aAny; try { aAny = xHierAccess->getByHierarchicalName( rtl::OUString::createFromAscii( key ) ); } catch( const container::NoSuchElementException& ) { } aAny >>= ret; } return ret; } void ContentProvider::subst( rtl::OUString& instpath ) const { uno::Reference< frame::XConfigManager > xCfgMgr; if( m_xSMgr.is() ) { try { xCfgMgr = uno::Reference< frame::XConfigManager >( m_xSMgr->createInstance( rtl::OUString::createFromAscii( "com.sun.star.config.SpecialConfigManager" ) ), uno::UNO_QUERY ); } catch( const uno::Exception&) { OSL_ENSURE( xCfgMgr.is(), "cant instantiate the special config manager " ); } } OSL_ENSURE( xCfgMgr.is(), "specialconfigmanager not found\n" ); if( xCfgMgr.is() ) instpath = xCfgMgr->substituteVariables( instpath ); } <|endoftext|>
<commit_before>#include "pink/src/worker_thread.h" #include "pink/include/pink_conn.h" #include "pink/src/pink_item.h" #include "pink/src/pink_epoll.h" #include "pink/src/csapp.h" namespace pink { WorkerThread::WorkerThread(ConnFactory *conn_factory, ServerThread* server_thread, int cron_interval) : server_thread_(server_thread), conn_factory_(conn_factory), cron_interval_(cron_interval), keepalive_timeout_(kDefaultKeepAliveTime) { /* * install the protobuf handler here */ pink_epoll_ = new PinkEpoll(); int fds[2]; if (pipe(fds)) { exit(-1); } notify_receive_fd_ = fds[0]; notify_send_fd_ = fds[1]; pink_epoll_->PinkAddEvent(notify_receive_fd_, EPOLLIN | EPOLLERR | EPOLLHUP); } WorkerThread::~WorkerThread() { delete(pink_epoll_); } int WorkerThread::conn_num() const { slash::ReadLock l(&rwlock_); return conns_.size(); } std::vector<ServerThread::ConnInfo> WorkerThread::conns_info() const { std::vector<ServerThread::ConnInfo> result; slash::ReadLock l(&rwlock_); for (auto& conn : conns_) { result.push_back({ conn.first, conn.second->ip_port(), conn.second->last_interaction() }); } return result; } PinkConn* WorkerThread::MoveConnOut(int fd) { slash::WriteLock l(&rwlock_); PinkConn* conn = nullptr; auto iter = conns_.find(fd); if (iter != conns_.end()) { int fd = iter->first; conn = iter->second; pink_epoll_->PinkDelEvent(fd); conns_.erase(iter); } return conn; } void *WorkerThread::ThreadMain() { int nfds; PinkFiredEvent *pfe = NULL; char bb[1]; PinkItem ti; PinkConn *in_conn = NULL; struct timeval when; gettimeofday(&when, NULL); struct timeval now = when; when.tv_sec += (cron_interval_ / 1000); when.tv_usec += ((cron_interval_ % 1000 ) * 1000); int timeout = cron_interval_; if (timeout <= 0) { timeout = PINK_CRON_INTERVAL; } while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, NULL); if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { DoCronTask(); when.tv_sec = now.tv_sec + (cron_interval_ / 1000); when.tv_usec = now.tv_usec + ((cron_interval_ % 1000 ) * 1000); timeout = cron_interval_; } } nfds = pink_epoll_->PinkPoll(timeout); for (int i = 0; i < nfds; i++) { pfe = (pink_epoll_->firedevent()) + i; if (pfe->fd == notify_receive_fd_) { if (pfe->mask & EPOLLIN) { read(notify_receive_fd_, bb, 1); { slash::MutexLock l(&mutex_); ti = conn_queue_.front(); conn_queue_.pop(); } PinkConn *tc = conn_factory_->NewPinkConn(ti.fd(), ti.ip_port(), server_thread_, private_data_); if (!tc || !tc->SetNonblock()) { delete tc; continue; } #ifdef __ENABLE_SSL // Create SSL failed if (server_thread_->security() && !tc->CreateSSL(server_thread_->ssl_ctx())) { CloseFd(tc); delete tc; continue; } #endif { slash::WriteLock l(&rwlock_); conns_[ti.fd()] = tc; } pink_epoll_->PinkAddEvent(ti.fd(), EPOLLIN); } else { continue; } } else { in_conn = NULL; int should_close = 0; if (pfe == NULL) { continue; } std::map<int, PinkConn *>::iterator iter = conns_.find(pfe->fd); if (iter == conns_.end()) { pink_epoll_->PinkDelEvent(pfe->fd); continue; } in_conn = iter->second; if (pfe->mask & EPOLLIN) { ReadStatus getRes = in_conn->GetRequest(); in_conn->set_last_interaction(now); if (getRes != kReadAll && getRes != kReadHalf) { // kReadError kReadClose kFullError kParseError should_close = 1; } else if (in_conn->is_reply()) { pink_epoll_->PinkModEvent(pfe->fd, EPOLLIN, EPOLLOUT); } else { continue; } } if (pfe->mask & EPOLLOUT) { WriteStatus write_status = in_conn->SendReply(); if (write_status == kWriteAll) { in_conn->set_is_reply(false); pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLIN); } else if (write_status == kWriteHalf) { continue; } else if (write_status == kWriteError) { should_close = 1; } } if ((pfe->mask & EPOLLERR) || (pfe->mask & EPOLLHUP) || should_close) { { slash::WriteLock l(&rwlock_); pink_epoll_->PinkDelEvent(pfe->fd); CloseFd(in_conn); delete(in_conn); in_conn = NULL; conns_.erase(pfe->fd); } } } // connection event } // for (int i = 0; i < nfds; i++) } // while (!should_stop()) Cleanup(); return NULL; } void WorkerThread::DoCronTask() { struct timeval now; gettimeofday(&now, NULL); slash::WriteLock l(&rwlock_); // Check whether close all connection slash::MutexLock kl(&killer_mutex_); if (deleting_conn_ipport_.count(kKillAllConnsTask)) { for (auto& conn : conns_) { CloseFd(conn.second); delete conn.second; } conns_.clear(); deleting_conn_ipport_.clear(); return; } std::map<int, PinkConn*>::iterator iter = conns_.begin(); while (iter != conns_.end()) { // Check connection should be closed if (deleting_conn_ipport_.count(iter->second->ip_port())) { CloseFd(iter->second); deleting_conn_ipport_.erase(iter->second->ip_port()); delete iter->second; iter = conns_.erase(iter); continue; } // Check keepalive timeout connection if (keepalive_timeout_ > 0 && now.tv_sec - iter->second->last_interaction().tv_sec > keepalive_timeout_) { CloseFd(iter->second); server_thread_->handle_->FdTimeoutHandle(iter->first, iter->second->ip_port()); delete iter->second; iter = conns_.erase(iter); continue; } ++iter; } } bool WorkerThread::TryKillConn(const std::string& ip_port) { bool find = false; if (ip_port != kKillAllConnsTask) { slash::ReadLock l(&rwlock_); for (auto& iter : conns_) { if (iter.second->ip_port() == ip_port) { find = true; break; } } } if (find || ip_port == kKillAllConnsTask) { slash::MutexLock l(&killer_mutex_); deleting_conn_ipport_.insert(ip_port); return true; } return false; } void WorkerThread::CloseFd(PinkConn* conn) { close(conn->fd()); server_thread_->handle_->FdClosedHandle(conn->fd(), conn->ip_port()); } void WorkerThread::Cleanup() { slash::WriteLock l(&rwlock_); for (auto& iter : conns_) { CloseFd(iter.second); delete iter.second; } conns_.clear(); } }; // namespace pink <commit_msg>Bugfix: update action time while send reply<commit_after>#include "pink/src/worker_thread.h" #include "pink/include/pink_conn.h" #include "pink/src/pink_item.h" #include "pink/src/pink_epoll.h" #include "pink/src/csapp.h" namespace pink { WorkerThread::WorkerThread(ConnFactory *conn_factory, ServerThread* server_thread, int cron_interval) : server_thread_(server_thread), conn_factory_(conn_factory), cron_interval_(cron_interval), keepalive_timeout_(kDefaultKeepAliveTime) { /* * install the protobuf handler here */ pink_epoll_ = new PinkEpoll(); int fds[2]; if (pipe(fds)) { exit(-1); } notify_receive_fd_ = fds[0]; notify_send_fd_ = fds[1]; pink_epoll_->PinkAddEvent(notify_receive_fd_, EPOLLIN | EPOLLERR | EPOLLHUP); } WorkerThread::~WorkerThread() { delete(pink_epoll_); } int WorkerThread::conn_num() const { slash::ReadLock l(&rwlock_); return conns_.size(); } std::vector<ServerThread::ConnInfo> WorkerThread::conns_info() const { std::vector<ServerThread::ConnInfo> result; slash::ReadLock l(&rwlock_); for (auto& conn : conns_) { result.push_back({ conn.first, conn.second->ip_port(), conn.second->last_interaction() }); } return result; } PinkConn* WorkerThread::MoveConnOut(int fd) { slash::WriteLock l(&rwlock_); PinkConn* conn = nullptr; auto iter = conns_.find(fd); if (iter != conns_.end()) { int fd = iter->first; conn = iter->second; pink_epoll_->PinkDelEvent(fd); conns_.erase(iter); } return conn; } void *WorkerThread::ThreadMain() { int nfds; PinkFiredEvent *pfe = NULL; char bb[1]; PinkItem ti; PinkConn *in_conn = NULL; struct timeval when; gettimeofday(&when, NULL); struct timeval now = when; when.tv_sec += (cron_interval_ / 1000); when.tv_usec += ((cron_interval_ % 1000 ) * 1000); int timeout = cron_interval_; if (timeout <= 0) { timeout = PINK_CRON_INTERVAL; } while (!should_stop()) { if (cron_interval_ > 0) { gettimeofday(&now, NULL); if (when.tv_sec > now.tv_sec || (when.tv_sec == now.tv_sec && when.tv_usec > now.tv_usec)) { timeout = (when.tv_sec - now.tv_sec) * 1000 + (when.tv_usec - now.tv_usec) / 1000; } else { DoCronTask(); when.tv_sec = now.tv_sec + (cron_interval_ / 1000); when.tv_usec = now.tv_usec + ((cron_interval_ % 1000 ) * 1000); timeout = cron_interval_; } } nfds = pink_epoll_->PinkPoll(timeout); for (int i = 0; i < nfds; i++) { pfe = (pink_epoll_->firedevent()) + i; if (pfe->fd == notify_receive_fd_) { if (pfe->mask & EPOLLIN) { read(notify_receive_fd_, bb, 1); { slash::MutexLock l(&mutex_); ti = conn_queue_.front(); conn_queue_.pop(); } PinkConn *tc = conn_factory_->NewPinkConn(ti.fd(), ti.ip_port(), server_thread_, private_data_); if (!tc || !tc->SetNonblock()) { delete tc; continue; } #ifdef __ENABLE_SSL // Create SSL failed if (server_thread_->security() && !tc->CreateSSL(server_thread_->ssl_ctx())) { CloseFd(tc); delete tc; continue; } #endif { slash::WriteLock l(&rwlock_); conns_[ti.fd()] = tc; } pink_epoll_->PinkAddEvent(ti.fd(), EPOLLIN); } else { continue; } } else { in_conn = NULL; int should_close = 0; if (pfe == NULL) { continue; } std::map<int, PinkConn *>::iterator iter = conns_.find(pfe->fd); if (iter == conns_.end()) { pink_epoll_->PinkDelEvent(pfe->fd); continue; } in_conn = iter->second; if (pfe->mask & EPOLLIN) { ReadStatus getRes = in_conn->GetRequest(); in_conn->set_last_interaction(now); if (getRes != kReadAll && getRes != kReadHalf) { // kReadError kReadClose kFullError kParseError should_close = 1; } else if (in_conn->is_reply()) { pink_epoll_->PinkModEvent(pfe->fd, EPOLLIN, EPOLLOUT); } else { continue; } } if (pfe->mask & EPOLLOUT) { WriteStatus write_status = in_conn->SendReply(); in_conn->set_last_interaction(now); if (write_status == kWriteAll) { in_conn->set_is_reply(false); pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLIN); } else if (write_status == kWriteHalf) { continue; } else if (write_status == kWriteError) { should_close = 1; } } if ((pfe->mask & EPOLLERR) || (pfe->mask & EPOLLHUP) || should_close) { { slash::WriteLock l(&rwlock_); pink_epoll_->PinkDelEvent(pfe->fd); CloseFd(in_conn); delete(in_conn); in_conn = NULL; conns_.erase(pfe->fd); } } } // connection event } // for (int i = 0; i < nfds; i++) } // while (!should_stop()) Cleanup(); return NULL; } void WorkerThread::DoCronTask() { struct timeval now; gettimeofday(&now, NULL); slash::WriteLock l(&rwlock_); // Check whether close all connection slash::MutexLock kl(&killer_mutex_); if (deleting_conn_ipport_.count(kKillAllConnsTask)) { for (auto& conn : conns_) { CloseFd(conn.second); delete conn.second; } conns_.clear(); deleting_conn_ipport_.clear(); return; } std::map<int, PinkConn*>::iterator iter = conns_.begin(); while (iter != conns_.end()) { // Check connection should be closed if (deleting_conn_ipport_.count(iter->second->ip_port())) { CloseFd(iter->second); deleting_conn_ipport_.erase(iter->second->ip_port()); delete iter->second; iter = conns_.erase(iter); continue; } // Check keepalive timeout connection if (keepalive_timeout_ > 0 && now.tv_sec - iter->second->last_interaction().tv_sec > keepalive_timeout_) { CloseFd(iter->second); server_thread_->handle_->FdTimeoutHandle(iter->first, iter->second->ip_port()); delete iter->second; iter = conns_.erase(iter); continue; } ++iter; } } bool WorkerThread::TryKillConn(const std::string& ip_port) { bool find = false; if (ip_port != kKillAllConnsTask) { slash::ReadLock l(&rwlock_); for (auto& iter : conns_) { if (iter.second->ip_port() == ip_port) { find = true; break; } } } if (find || ip_port == kKillAllConnsTask) { slash::MutexLock l(&killer_mutex_); deleting_conn_ipport_.insert(ip_port); return true; } return false; } void WorkerThread::CloseFd(PinkConn* conn) { close(conn->fd()); server_thread_->handle_->FdClosedHandle(conn->fd(), conn->ip_port()); } void WorkerThread::Cleanup() { slash::WriteLock l(&rwlock_); for (auto& iter : conns_) { CloseFd(iter.second); delete iter.second; } conns_.clear(); } }; // namespace pink <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2011, Willow Garage, Inc. * * 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 Willow Garage, Inc. 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 <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/common/time.h> //fps calculations #include <pcl/io/openni_grabber.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/console/parse.h> #include <vtkImageViewer.h> #include <vtkImageImport.h> #include <vtkJPEGWriter.h> #include <vtkBMPWriter.h> #include <vtkPNGWriter.h> #include <vtkTIFFWriter.h> #include <vector> #include <string> #include <pcl/visualization/pcl_visualizer.h> #define SHOW_FPS 1 #if SHOW_FPS #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ double now = pcl::getTime (); \ ++count; \ if (now - last >= 1.0) \ { \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) #else #define FPS_CALC(_WHAT_) \ do \ { \ }while(false) #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class SimpleOpenNIViewer { public: SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber) : grabber_ (grabber), importer_ (vtkSmartPointer<vtkImageImport>::New ()), depth_importer_ (vtkSmartPointer<vtkImageImport>::New ()), writer_ (vtkSmartPointer<vtkTIFFWriter>::New ()) { importer_->SetNumberOfScalarComponents (3); importer_->SetDataScalarTypeToUnsignedChar (); depth_importer_->SetNumberOfScalarComponents (1); depth_importer_->SetDataScalarTypeToUnsignedShort (); writer_->SetCompressionToPackBits (); } void image_callback (const boost::shared_ptr<openni_wrapper::Image> &image, const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float constant) { FPS_CALC ("image callback"); boost::mutex::scoped_lock lock (image_mutex_); image_ = image; depth_image_ = depth_image; } void run () { boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3); boost::signals2::connection image_connection = grabber_.registerCallback (image_cb); grabber_.start (); unsigned char* rgb_data = 0; unsigned rgb_data_size = 0; void* data; while (true) { boost::mutex::scoped_lock lock (image_mutex_); std::string time = boost::posix_time::to_iso_string (boost::posix_time::microsec_clock::local_time ()); if (image_) { FPS_CALC ("writer callback"); boost::shared_ptr<openni_wrapper::Image> image; image.swap (image_); if (image->getEncoding() == openni_wrapper::Image::RGB) { data = (void*)image->getMetaData ().Data (); importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0); importer_->SetDataExtentToWholeExtent (); } else { if (rgb_data_size < image->getWidth () * image->getHeight ()) { rgb_data_size = image->getWidth () * image->getHeight (); rgb_data = new unsigned char [rgb_data_size * 3]; importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0); importer_->SetDataExtentToWholeExtent (); } image->fillRGB (image->getWidth (), image->getHeight (), rgb_data); data = (void*)rgb_data; } std::stringstream ss; ss << "frame_" + time + "_rgb.tiff"; importer_->SetImportVoidPointer (data, 1); importer_->Update (); writer_->SetFileName (ss.str ().c_str ()); writer_->SetInputConnection (importer_->GetOutputPort ()); writer_->Write (); } if (depth_image_) { boost::shared_ptr<openni_wrapper::DepthImage> depth_image; depth_image.swap (depth_image_); std::stringstream ss; ss << "frame_" + time + "_depth.tiff"; depth_importer_->SetWholeExtent (0, depth_image->getWidth () - 1, 0, depth_image->getHeight () - 1, 0, 0); depth_importer_->SetDataExtentToWholeExtent (); depth_importer_->SetImportVoidPointer ((void*)depth_image->getDepthMetaData ().Data (), 1); depth_importer_->Update (); writer_->SetFileName (ss.str ().c_str ()); writer_->SetInputConnection (depth_importer_->GetOutputPort ()); writer_->Write (); } } grabber_.stop (); image_connection.disconnect (); if (rgb_data) delete[] rgb_data; } pcl::OpenNIGrabber& grabber_; boost::mutex image_mutex_; boost::shared_ptr<openni_wrapper::Image> image_; boost::shared_ptr<openni_wrapper::DepthImage> depth_image_; vtkSmartPointer<vtkImageImport> importer_, depth_importer_; vtkSmartPointer<vtkTIFFWriter> writer_; }; void usage (char ** argv) { cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | -l [<device_id>]| -h | --help)]" << endl; cout << argv[0] << " -h | --help : shows this help" << endl; cout << argv[0] << " -l : list all available devices" << endl; cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl; cout << " device_id may be #1, #2, ... for the first, second etc device in the list" #ifndef _WIN32 << " or" << endl << " bus@address for the device connected to a specific usb-bus / address combination or" << endl << " <serial-number>" #endif << endl; cout << endl; cout << "examples:" << endl; cout << argv[0] << " \"#1\"" << endl; cout << " uses the first device." << endl; cout << argv[0] << " \"./temp/test.oni\"" << endl; cout << " uses the oni-player device to play back oni file given by path." << endl; cout << argv[0] << " -l" << endl; cout << " lists all available devices." << endl; cout << argv[0] << " -l \"#2\"" << endl; cout << " lists all available modes for the second device" << endl; #ifndef _WIN32 cout << argv[0] << " A00361800903049A" << endl; cout << " uses the device with the serial number \'A00361800903049A\'." << endl; cout << argv[0] << " 1@16" << endl; cout << " uses the device on address 16 at USB bus 1." << endl; #endif return; } int main(int argc, char ** argv) { std::string device_id (""); pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode; if (argc >= 2) { device_id = argv[1]; if (device_id == "--help" || device_id == "-h") { usage(argv); return 0; } else if (device_id == "-l") { if (argc >= 3) { pcl::OpenNIGrabber grabber (argv[2]); boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice (); std::vector<std::pair<int, XnMapOutputMode> > modes; if (device->hasImageStream ()) { cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl; modes = grabber.getAvailableImageModes (); for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it) { cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl; } } } else { openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int) driver.getBus (deviceIdx) << " @ " << (int) driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; } } else cout << "No devices connected." << endl; cout <<"Virtual Devices available: ONI player" << endl; } return (0); } } else { openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) cout << "Device Id not set, using first device." << endl; } unsigned mode; if (pcl::console::parse (argc, argv, "-imagemode", mode) != -1) image_mode = (pcl::OpenNIGrabber::Mode) mode; pcl::OpenNIGrabber grabber (device_id, pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode); SimpleOpenNIViewer v (grabber); v.run (); return (0); } <commit_msg>fix openni_save_image - flip images vertically for proper orientation<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2011, Willow Garage, Inc. * * 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 Willow Garage, Inc. 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 <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/common/time.h> //fps calculations #include <pcl/io/openni_grabber.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/console/parse.h> #include <vtkImageViewer.h> #include <vtkImageImport.h> #include <vtkJPEGWriter.h> #include <vtkBMPWriter.h> #include <vtkPNGWriter.h> #include <vtkTIFFWriter.h> #include <vtkImageFlip.h> #include <vector> #include <string> #include <pcl/visualization/pcl_visualizer.h> #define SHOW_FPS 1 #if SHOW_FPS #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ double now = pcl::getTime (); \ ++count; \ if (now - last >= 1.0) \ { \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) #else #define FPS_CALC(_WHAT_) \ do \ { \ }while(false) #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class SimpleOpenNIViewer { public: SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber) : grabber_ (grabber), importer_ (vtkSmartPointer<vtkImageImport>::New ()), depth_importer_ (vtkSmartPointer<vtkImageImport>::New ()), writer_ (vtkSmartPointer<vtkTIFFWriter>::New ()), flipper_ (vtkSmartPointer<vtkImageFlip>::New ()) { importer_->SetNumberOfScalarComponents (3); importer_->SetDataScalarTypeToUnsignedChar (); depth_importer_->SetNumberOfScalarComponents (1); depth_importer_->SetDataScalarTypeToUnsignedShort (); writer_->SetCompressionToPackBits (); flipper_->SetFilteredAxes (1); } void image_callback (const boost::shared_ptr<openni_wrapper::Image> &image, const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float constant) { FPS_CALC ("image callback"); boost::mutex::scoped_lock lock (image_mutex_); image_ = image; depth_image_ = depth_image; } void run () { boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3); boost::signals2::connection image_connection = grabber_.registerCallback (image_cb); grabber_.start (); unsigned char* rgb_data = 0; unsigned rgb_data_size = 0; void* data; while (true) { boost::mutex::scoped_lock lock (image_mutex_); std::string time = boost::posix_time::to_iso_string (boost::posix_time::microsec_clock::local_time ()); if (image_) { FPS_CALC ("writer callback"); boost::shared_ptr<openni_wrapper::Image> image; image.swap (image_); if (image->getEncoding() == openni_wrapper::Image::RGB) { data = (void*)image->getMetaData ().Data (); importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0); importer_->SetDataExtentToWholeExtent (); } else { if (rgb_data_size < image->getWidth () * image->getHeight ()) { rgb_data_size = image->getWidth () * image->getHeight (); rgb_data = new unsigned char [rgb_data_size * 3]; importer_->SetWholeExtent (0, image->getWidth () - 1, 0, image->getHeight () - 1, 0, 0); importer_->SetDataExtentToWholeExtent (); } image->fillRGB (image->getWidth (), image->getHeight (), rgb_data); data = (void*)rgb_data; } std::stringstream ss; ss << "frame_" + time + "_rgb.tiff"; importer_->SetImportVoidPointer (data, 1); importer_->Update (); flipper_->SetInputConnection (importer_->GetOutputPort ()); flipper_->Update (); writer_->SetFileName (ss.str ().c_str ()); writer_->SetInputConnection (flipper_->GetOutputPort ()); writer_->Write (); } if (depth_image_) { boost::shared_ptr<openni_wrapper::DepthImage> depth_image; depth_image.swap (depth_image_); std::stringstream ss; ss << "frame_" + time + "_depth.tiff"; depth_importer_->SetWholeExtent (0, depth_image->getWidth () - 1, 0, depth_image->getHeight () - 1, 0, 0); depth_importer_->SetDataExtentToWholeExtent (); depth_importer_->SetImportVoidPointer ((void*)depth_image->getDepthMetaData ().Data (), 1); depth_importer_->Update (); flipper_->SetInputConnection (depth_importer_->GetOutputPort ()); flipper_->Update (); writer_->SetFileName (ss.str ().c_str ()); writer_->SetInputConnection (flipper_->GetOutputPort ()); writer_->Write (); } } grabber_.stop (); image_connection.disconnect (); if (rgb_data) delete[] rgb_data; } pcl::OpenNIGrabber& grabber_; boost::mutex image_mutex_; boost::shared_ptr<openni_wrapper::Image> image_; boost::shared_ptr<openni_wrapper::DepthImage> depth_image_; vtkSmartPointer<vtkImageImport> importer_, depth_importer_; vtkSmartPointer<vtkTIFFWriter> writer_; vtkSmartPointer<vtkImageFlip> flipper_; }; void usage (char ** argv) { cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | -l [<device_id>]| -h | --help)]" << endl; cout << argv[0] << " -h | --help : shows this help" << endl; cout << argv[0] << " -l : list all available devices" << endl; cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl; cout << " device_id may be #1, #2, ... for the first, second etc device in the list" #ifndef _WIN32 << " or" << endl << " bus@address for the device connected to a specific usb-bus / address combination or" << endl << " <serial-number>" #endif << endl; cout << endl; cout << "examples:" << endl; cout << argv[0] << " \"#1\"" << endl; cout << " uses the first device." << endl; cout << argv[0] << " \"./temp/test.oni\"" << endl; cout << " uses the oni-player device to play back oni file given by path." << endl; cout << argv[0] << " -l" << endl; cout << " lists all available devices." << endl; cout << argv[0] << " -l \"#2\"" << endl; cout << " lists all available modes for the second device" << endl; #ifndef _WIN32 cout << argv[0] << " A00361800903049A" << endl; cout << " uses the device with the serial number \'A00361800903049A\'." << endl; cout << argv[0] << " 1@16" << endl; cout << " uses the device on address 16 at USB bus 1." << endl; #endif return; } int main(int argc, char ** argv) { std::string device_id (""); pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode; if (argc >= 2) { device_id = argv[1]; if (device_id == "--help" || device_id == "-h") { usage(argv); return 0; } else if (device_id == "-l") { if (argc >= 3) { pcl::OpenNIGrabber grabber (argv[2]); boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice (); std::vector<std::pair<int, XnMapOutputMode> > modes; if (device->hasImageStream ()) { cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl; modes = grabber.getAvailableImageModes (); for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it) { cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl; } } } else { openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int) driver.getBus (deviceIdx) << " @ " << (int) driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; } } else cout << "No devices connected." << endl; cout <<"Virtual Devices available: ONI player" << endl; } return (0); } } else { openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) cout << "Device Id not set, using first device." << endl; } unsigned mode; if (pcl::console::parse (argc, argv, "-imagemode", mode) != -1) image_mode = (pcl::OpenNIGrabber::Mode) mode; pcl::OpenNIGrabber grabber (device_id, pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode); SimpleOpenNIViewer v (grabber); v.run (); return (0); } <|endoftext|>
<commit_before>#include "AnimationBlender.h" #include <Animation/MappedPoseOutput.h> #include <Scene/SceneNode.h> namespace DEM::Anim { CAnimationBlender::CAnimationBlender() = default; CAnimationBlender::~CAnimationBlender() = default; void CAnimationBlender::Initialize(U8 SourceCount, U8 PortCount) { _Sources.clear(); _Sources.reserve(SourceCount); for (U8 i = 0; i < SourceCount; ++i) _Sources.emplace_back(*this, i); // All sources initially have the same priority, order is not important _SourcesByPriority.resize(SourceCount); for (U8 i = 0; i < SourceCount; ++i) _SourcesByPriority[i] = i; _PrioritiesChanged = false; // Allocate blend matrix (sources * ports) const auto MatrixCellCount = PortCount * SourceCount; _Transforms.resize(MatrixCellCount); _ChannelMasks.resize(MatrixCellCount, 0); _PortCount = PortCount; } //--------------------------------------------------------------------- void CAnimationBlender::EvaluatePose(IPoseOutput& Output) { const auto SourceCount = _Sources.size(); if (!SourceCount) return; if (_PrioritiesChanged) { std::sort(_SourcesByPriority.begin(), _SourcesByPriority.end(), [this](U8 a, U8 b) { return _Sources[a]._Priority > _Sources[b]._Priority; }); _PrioritiesChanged = false; } for (UPTR Port = 0; Port < _PortCount; ++Port) { Math::CTransformSRT FinalTfm; U8 FinalMask = 0; float ScaleWeights = 0.f; float RotationWeights = 0.f; float TranslationWeights = 0.f; const auto Offset = Port * SourceCount; for (const U8 SourceIndex : _SourcesByPriority) { const float SourceWeight = _Sources[SourceIndex]._Weight; if (SourceWeight <= 0.f) continue; const auto& CurrTfm = _Transforms[Offset + SourceIndex]; const U8 ChannelMask = _ChannelMasks[Offset + SourceIndex]; if ((ChannelMask & ETransformChannel::Scaling) && ScaleWeights < 1.f) { const float Weight = std::min(SourceWeight, 1.f - ScaleWeights); // Scale is 1.f by default. To blend correctly, we must reset it to zero before applying the first source. if (FinalMask & ETransformChannel::Scaling) FinalTfm.Scale += CurrTfm.Scale * Weight; else FinalTfm.Scale = CurrTfm.Scale * Weight; FinalMask |= ETransformChannel::Scaling; ScaleWeights += Weight; } if ((ChannelMask & ETransformChannel::Rotation) && RotationWeights < 1.f) { const float Weight = std::min(SourceWeight, 1.f - RotationWeights); // TODO: check this hardcore stuff for multiple quaternion blending: // https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20070017872.pdf // Impl: http://wiki.unity3d.com/index.php/Averaging_Quaternions_and_Vectors // Impl: https://github.com/christophhagen/averaging-quaternions/blob/master/averageQuaternions.py if (FinalMask & ETransformChannel::Rotation) { quaternion Q; Q.slerp(quaternion::Identity, CurrTfm.Rotation, Weight); FinalTfm.Rotation *= Q; } else { FinalTfm.Rotation.slerp(quaternion::Identity, CurrTfm.Rotation, Weight); } FinalMask |= ETransformChannel::Rotation; RotationWeights += Weight; } if ((ChannelMask & ETransformChannel::Translation) && TranslationWeights < 1.f) { const float Weight = std::min(SourceWeight, 1.f - TranslationWeights); FinalTfm.Translation += CurrTfm.Translation * Weight; FinalMask |= ETransformChannel::Translation; TranslationWeights += Weight; } } // Apply accumulated transform if (FinalMask & ETransformChannel::Scaling) Output.SetScale(Port, FinalTfm.Scale); if (FinalMask & ETransformChannel::Rotation) { if (RotationWeights < 1.f) FinalTfm.Rotation.normalize(); Output.SetRotation(Port, FinalTfm.Rotation); } if (FinalMask & ETransformChannel::Translation) Output.SetTranslation(Port, FinalTfm.Translation); } // Source data is blended into the output, no more channels are ready to be blended std::memset(_ChannelMasks.data(), 0, _ChannelMasks.size()); } //--------------------------------------------------------------------- void CAnimationBlender::SetPriority(U8 Source, U16 Priority) { if (Source < _Sources.size() && _Sources[Source]._Priority != Priority) { _Sources[Source]._Priority = Priority; _PrioritiesChanged = true; } } //--------------------------------------------------------------------- void CAnimationBlender::SetWeight(U8 Source, float Weight) { if (Source < _Sources.size()) _Sources[Source]._Weight = Weight; } //--------------------------------------------------------------------- } <commit_msg>Quaternion blending fixed<commit_after>#include "AnimationBlender.h" #include <Animation/MappedPoseOutput.h> #include <Scene/SceneNode.h> namespace DEM::Anim { CAnimationBlender::CAnimationBlender() = default; CAnimationBlender::~CAnimationBlender() = default; void CAnimationBlender::Initialize(U8 SourceCount, U8 PortCount) { _Sources.clear(); _Sources.reserve(SourceCount); for (U8 i = 0; i < SourceCount; ++i) _Sources.emplace_back(*this, i); // All sources initially have the same priority, order is not important _SourcesByPriority.resize(SourceCount); for (U8 i = 0; i < SourceCount; ++i) _SourcesByPriority[i] = i; _PrioritiesChanged = false; // Allocate blend matrix (sources * ports) const auto MatrixCellCount = PortCount * SourceCount; _Transforms.resize(MatrixCellCount); _ChannelMasks.resize(MatrixCellCount, 0); _PortCount = PortCount; } //--------------------------------------------------------------------- void CAnimationBlender::EvaluatePose(IPoseOutput& Output) { const auto SourceCount = _Sources.size(); if (!SourceCount) return; if (_PrioritiesChanged) { std::sort(_SourcesByPriority.begin(), _SourcesByPriority.end(), [this](U8 a, U8 b) { return _Sources[a]._Priority > _Sources[b]._Priority; }); _PrioritiesChanged = false; } for (UPTR Port = 0; Port < _PortCount; ++Port) { Math::CTransformSRT FinalTfm; U8 FinalMask = 0; float ScaleWeights = 0.f; float RotationWeights = 0.f; float TranslationWeights = 0.f; const auto Offset = Port * SourceCount; for (const U8 SourceIndex : _SourcesByPriority) { const float SourceWeight = _Sources[SourceIndex]._Weight; if (SourceWeight <= 0.f) continue; const auto& CurrTfm = _Transforms[Offset + SourceIndex]; const U8 ChannelMask = _ChannelMasks[Offset + SourceIndex]; if ((ChannelMask & ETransformChannel::Scaling) && ScaleWeights < 1.f) { const float Weight = std::min(SourceWeight, 1.f - ScaleWeights); // Scale is 1.f by default. To blend correctly, we must reset it to zero before applying the first source. if (FinalMask & ETransformChannel::Scaling) FinalTfm.Scale += CurrTfm.Scale * Weight; else FinalTfm.Scale = CurrTfm.Scale * Weight; FinalMask |= ETransformChannel::Scaling; ScaleWeights += Weight; } if ((ChannelMask & ETransformChannel::Rotation) && RotationWeights < 1.f) { const float Weight = std::min(SourceWeight, 1.f - RotationWeights); quaternion Q; Q.x = CurrTfm.Rotation.x * Weight; Q.y = CurrTfm.Rotation.y * Weight; Q.z = CurrTfm.Rotation.z * Weight; Q.w = CurrTfm.Rotation.w * Weight; if (FinalMask & ETransformChannel::Rotation) { // Blend with shortest arc, based on a 4D dot product sign if (Q.x * FinalTfm.Rotation.x + Q.y * FinalTfm.Rotation.y + Q.z * FinalTfm.Rotation.z + Q.w * FinalTfm.Rotation.w < 0.f) FinalTfm.Rotation -= Q; else FinalTfm.Rotation += Q; } else { FinalTfm.Rotation = Q; } FinalMask |= ETransformChannel::Rotation; RotationWeights += Weight; } if ((ChannelMask & ETransformChannel::Translation) && TranslationWeights < 1.f) { const float Weight = std::min(SourceWeight, 1.f - TranslationWeights); FinalTfm.Translation += CurrTfm.Translation * Weight; FinalMask |= ETransformChannel::Translation; TranslationWeights += Weight; } } // Apply accumulated transform if (FinalMask & ETransformChannel::Scaling) Output.SetScale(Port, FinalTfm.Scale); if (FinalMask & ETransformChannel::Rotation) { if (RotationWeights < 1.f) FinalTfm.Rotation.normalize(); Output.SetRotation(Port, FinalTfm.Rotation); } if (FinalMask & ETransformChannel::Translation) Output.SetTranslation(Port, FinalTfm.Translation); } // Source data is blended into the output, no more channels are ready to be blended std::memset(_ChannelMasks.data(), 0, _ChannelMasks.size()); } //--------------------------------------------------------------------- void CAnimationBlender::SetPriority(U8 Source, U16 Priority) { if (Source < _Sources.size() && _Sources[Source]._Priority != Priority) { _Sources[Source]._Priority = Priority; _PrioritiesChanged = true; } } //--------------------------------------------------------------------- void CAnimationBlender::SetWeight(U8 Source, float Weight) { if (Source < _Sources.size()) _Sources[Source]._Weight = Weight; } //--------------------------------------------------------------------- } <|endoftext|>
<commit_before>#include <Arduino.h> #include "uplink.h" #include "main.h" #include "usonic.h" extern "C" { #include "pb.h" #include "pb_encode.h" #include "pb_decode.h" #include "status.pb.h" #include "sensor.pb.h" #include "odometry.h" #include "battery.h" } uint8_t uplink_send_buffer[BUFFERSIZE]; void uplink_setup(void){ Serial.begin(UPLINK_SPEED); } void uplink_sendStatus(void){ antikeimena_Status status_pb; status_pb.version = 12; status_pb.uptime = 13; status_pb.sensorInError = 14; pb_ostream_t stream = pb_ostream_from_buffer(uplink_send_buffer, sizeof(uplink_send_buffer)); pb_encode(&stream, antikeimena_Status_fields, &status_pb); uint16_t s = antikeimena_Status_size; Serial.write("ANSI"); Serial.write(STATUS_MESSAGE); Serial.write( (s ) & 0xFF); // low Serial.write( (s >> 8) & 0xFF); // high for(uint32_t i = 0; i < antikeimena_Status_size; i++) { Serial.write(uplink_send_buffer[i]); } } void uplink_sendSensor(void){ antikeimena_Sensor sensor_pb = antikeimena_Sensor_init_zero; sensor_pb.odometry_left = odometry_get_left_counter(); sensor_pb.odometry_right = odometry_get_right_counter(); sensor_pb.battery_voltage = battery_voltage; sensor_pb.ultrasonic_01 = ultrasonic_distance[0]; sensor_pb.ultrasonic_02 = ultrasonic_distance[1]; sensor_pb.ultrasonic_03 = ultrasonic_distance[2]; sensor_pb.ultrasonic_04 = ultrasonic_distance[3]; sensor_pb.ultrasonic_05 = ultrasonic_distance[4]; sensor_pb.ultrasonic_06 = ultrasonic_distance[5]; sensor_pb.ultrasonic_07 = ultrasonic_distance[6]; sensor_pb.ultrasonic_08 = ultrasonic_distance[7]; sensor_pb.ultrasonic_09 = ultrasonic_distance[8]; sensor_pb.ultrasonic_10 = ultrasonic_distance[9]; pb_ostream_t stream = pb_ostream_from_buffer(uplink_send_buffer, sizeof(uplink_send_buffer)); pb_encode(&stream, antikeimena_Sensor_fields, &sensor_pb); uint16_t mysize = stream.bytes_written; Serial.write("ANSI"); Serial.flush(); Serial.write(SENSOR_MESSAGE); Serial.flush(); Serial.write( (mysize ) & 0xFF); // low Serial.write( (mysize >> 8) & 0xFF); // high Serial.flush(); for(uint32_t i = 0; i < mysize; i++) { Serial.write(uplink_send_buffer[i]); } Serial.flush(); }<commit_msg>Fixing protobuf error<commit_after>#include <Arduino.h> #include "uplink.h" #include "main.h" #include "usonic.h" extern "C" { #include "pb.h" #include "pb_encode.h" #include "pb_decode.h" #include "status.pb.h" #include "sensor.pb.h" #include "odometry.h" #include "battery.h" } uint8_t uplink_send_buffer[BUFFERSIZE]; void uplink_setup(void){ Serial.begin(UPLINK_SPEED); } void uplink_sendStatus(void){ antikeimena_Status status_pb = antikeimena_Status_init_zero; status_pb.version = 12; status_pb.uptime = 13; status_pb.sensorInError = 14; pb_ostream_t stream = pb_ostream_from_buffer(uplink_send_buffer, sizeof(uplink_send_buffer)); pb_encode(&stream, antikeimena_Status_fields, &status_pb); uint16_t mysize = stream.bytes_written; Serial.write("ANSI"); Serial.flush(); Serial.write(STATUS_MESSAGE); Serial.flush(); Serial.write( (mysize ) & 0xFF); // low Serial.write( (mysize >> 8) & 0xFF); // high Serial.flush(); for(uint32_t i = 0; i < mysize; i++) { Serial.write(uplink_send_buffer[i]); } Serial.flush(); } void uplink_sendSensor(void){ antikeimena_Sensor sensor_pb = antikeimena_Sensor_init_zero; sensor_pb.odometry_left = odometry_get_left_counter(); sensor_pb.odometry_right = odometry_get_right_counter(); sensor_pb.battery_voltage = battery_voltage; sensor_pb.ultrasonic_01 = ultrasonic_distance[0]; sensor_pb.ultrasonic_02 = ultrasonic_distance[1]; sensor_pb.ultrasonic_03 = ultrasonic_distance[2]; sensor_pb.ultrasonic_04 = ultrasonic_distance[3]; sensor_pb.ultrasonic_05 = ultrasonic_distance[4]; sensor_pb.ultrasonic_06 = ultrasonic_distance[5]; sensor_pb.ultrasonic_07 = ultrasonic_distance[6]; sensor_pb.ultrasonic_08 = ultrasonic_distance[7]; sensor_pb.ultrasonic_09 = ultrasonic_distance[8]; sensor_pb.ultrasonic_10 = ultrasonic_distance[9]; pb_ostream_t stream = pb_ostream_from_buffer(uplink_send_buffer, sizeof(uplink_send_buffer)); pb_encode(&stream, antikeimena_Sensor_fields, &sensor_pb); uint16_t mysize = stream.bytes_written; Serial.write("ANSI"); Serial.flush(); Serial.write(SENSOR_MESSAGE); Serial.flush(); Serial.write( (mysize ) & 0xFF); // low Serial.write( (mysize >> 8) & 0xFF); // high Serial.flush(); for(uint32_t i = 0; i < mysize; i++) { Serial.write(uplink_send_buffer[i]); } Serial.flush(); }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: toolboxdocumenthandler.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-07-06 16:55:36 $ * * 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 __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_ #define __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_ #ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ #include <xml/toolboxconfiguration.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef __SGI_STL_HASH_MAP #include <hash_map> #endif #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //***************************************************************************************************************** // Hash code function for using in all hash maps of follow implementation. class OReadToolBoxDocumentHandler : public ::com::sun::star::xml::sax::XDocumentHandler, private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses. public ::cppu::OWeakObject { public: enum ToolBox_XML_Entry { TB_ELEMENT_TOOLBAR, TB_ELEMENT_TOOLBARITEM, TB_ELEMENT_TOOLBARSPACE, TB_ELEMENT_TOOLBARBREAK, TB_ELEMENT_TOOLBARSEPARATOR, TB_ATTRIBUTE_TEXT, TB_ATTRIBUTE_BITMAP, TB_ATTRIBUTE_URL, TB_ATTRIBUTE_ITEMBITS, TB_ATTRIBUTE_VISIBLE, TB_ATTRIBUTE_WIDTH, TB_ATTRIBUTE_USER, TB_ATTRIBUTE_HELPID, TB_ATTRIBUTE_STYLE, TB_ATTRIBUTE_UINAME, TB_XML_ENTRY_COUNT }; enum ToolBox_XML_Namespace { TB_NS_TOOLBAR, TB_NS_XLINK, TB_XML_NAMESPACES_COUNT }; OReadToolBoxDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::container::XIndexContainer >& rItemContainer ); virtual ~OReadToolBoxDocumentHandler(); // XInterface virtual void SAL_CALL acquire() throw() { OWeakObject::acquire(); } virtual void SAL_CALL release() throw() { OWeakObject::release(); } virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException ); // XDocumentHandler virtual void SAL_CALL startDocument(void) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL endDocument(void) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL startElement( const rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL endElement(const rtl::OUString& aName) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL characters(const rtl::OUString& aChars) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget, const rtl::OUString& aData) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); private: ::rtl::OUString getErrorLineString(); class ToolBoxHashMap : public ::std::hash_map< ::rtl::OUString , ToolBox_XML_Entry , OUStringHashCode , ::std::equal_to< ::rtl::OUString > > { public: inline void free() { ToolBoxHashMap().swap( *this ); } }; sal_Bool m_bToolBarStartFound; sal_Bool m_bToolBarEndFound; sal_Bool m_bToolBarItemStartFound; sal_Bool m_bToolBarSpaceStartFound; sal_Bool m_bToolBarBreakStartFound; sal_Bool m_bToolBarSeparatorStartFound; ToolBoxHashMap m_aToolBoxMap; com::sun::star::uno::Reference< com::sun::star::container::XIndexContainer > m_rItemContainer; ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > m_xLocator; sal_Int32 m_nHashCode_Style_Radio; sal_Int32 m_nHashCode_Style_Auto; sal_Int32 m_nHashCode_Style_Left; sal_Int32 m_nHashCode_Style_AutoSize; sal_Int32 m_nHashCode_Style_DropDown; sal_Int32 m_nHashCode_Style_Repeat; }; class OWriteToolBoxDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses. { public: OWriteToolBoxDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rItemAccess, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler >& rDocumentHandler ); virtual ~OWriteToolBoxDocumentHandler(); void WriteToolBoxDocument() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); protected: virtual void WriteToolBoxItem( const rtl::OUString& aCommandURL, const rtl::OUString& aLabel, const rtl::OUString& aHelpURL, sal_Bool bVisible ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void WriteToolBoxSpace() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void WriteToolBoxBreak() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void WriteToolBoxSeparator() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xWriteDocumentHandler; ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > m_xEmptyList; com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > m_rItemAccess; ::rtl::OUString m_aXMLToolbarNS; ::rtl::OUString m_aXMLXlinkNS; ::rtl::OUString m_aAttributeType; ::rtl::OUString m_aAttributeURL; }; } // namespace framework #endif <commit_msg>INTEGRATION: CWS ooo20040704 (1.2.58); FILE MERGED 2004/07/19 05:50:45 svesik 1.2.58.3: RESYNC: (1.2-1.3); FILE MERGED 2004/07/02 10:21:15 cmc 1.2.58.2: #i30891# revert header and namespace change 2004/06/28 12:23:42 cmc 1.2.58.1: #i30801 allow using system stl if possible<commit_after>/************************************************************************* * * $RCSfile: toolboxdocumenthandler.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-09-08 14:10:56 $ * * 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 __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_ #define __FRAMEWORK_XML_TOOLBOXDOCUMENTHANDLER_HXX_ #ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_ #include <xml/toolboxconfiguration.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_ #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #include <hash_map> #ifndef __FRAMEWORK_STDTYPES_H_ #include <stdtypes.h> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ namespace framework{ //***************************************************************************************************************** // Hash code function for using in all hash maps of follow implementation. class OReadToolBoxDocumentHandler : public ::com::sun::star::xml::sax::XDocumentHandler, private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses. public ::cppu::OWeakObject { public: enum ToolBox_XML_Entry { TB_ELEMENT_TOOLBAR, TB_ELEMENT_TOOLBARITEM, TB_ELEMENT_TOOLBARSPACE, TB_ELEMENT_TOOLBARBREAK, TB_ELEMENT_TOOLBARSEPARATOR, TB_ATTRIBUTE_TEXT, TB_ATTRIBUTE_BITMAP, TB_ATTRIBUTE_URL, TB_ATTRIBUTE_ITEMBITS, TB_ATTRIBUTE_VISIBLE, TB_ATTRIBUTE_WIDTH, TB_ATTRIBUTE_USER, TB_ATTRIBUTE_HELPID, TB_ATTRIBUTE_STYLE, TB_ATTRIBUTE_UINAME, TB_XML_ENTRY_COUNT }; enum ToolBox_XML_Namespace { TB_NS_TOOLBAR, TB_NS_XLINK, TB_XML_NAMESPACES_COUNT }; OReadToolBoxDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::container::XIndexContainer >& rItemContainer ); virtual ~OReadToolBoxDocumentHandler(); // XInterface virtual void SAL_CALL acquire() throw() { OWeakObject::acquire(); } virtual void SAL_CALL release() throw() { OWeakObject::release(); } virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException ); // XDocumentHandler virtual void SAL_CALL startDocument(void) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL endDocument(void) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL startElement( const rtl::OUString& aName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL endElement(const rtl::OUString& aName) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL characters(const rtl::OUString& aChars) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget, const rtl::OUString& aData) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator) throw( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); private: ::rtl::OUString getErrorLineString(); class ToolBoxHashMap : public ::std::hash_map< ::rtl::OUString , ToolBox_XML_Entry , OUStringHashCode , ::std::equal_to< ::rtl::OUString > > { public: inline void free() { ToolBoxHashMap().swap( *this ); } }; sal_Bool m_bToolBarStartFound; sal_Bool m_bToolBarEndFound; sal_Bool m_bToolBarItemStartFound; sal_Bool m_bToolBarSpaceStartFound; sal_Bool m_bToolBarBreakStartFound; sal_Bool m_bToolBarSeparatorStartFound; ToolBoxHashMap m_aToolBoxMap; com::sun::star::uno::Reference< com::sun::star::container::XIndexContainer > m_rItemContainer; ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > m_xLocator; sal_Int32 m_nHashCode_Style_Radio; sal_Int32 m_nHashCode_Style_Auto; sal_Int32 m_nHashCode_Style_Left; sal_Int32 m_nHashCode_Style_AutoSize; sal_Int32 m_nHashCode_Style_DropDown; sal_Int32 m_nHashCode_Style_Repeat; }; class OWriteToolBoxDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses. { public: OWriteToolBoxDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rItemAccess, ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler >& rDocumentHandler ); virtual ~OWriteToolBoxDocumentHandler(); void WriteToolBoxDocument() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); protected: virtual void WriteToolBoxItem( const rtl::OUString& aCommandURL, const rtl::OUString& aLabel, const rtl::OUString& aHelpURL, sal_Bool bVisible ) throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void WriteToolBoxSpace() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void WriteToolBoxBreak() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); virtual void WriteToolBoxSeparator() throw ( ::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException ); ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > m_xWriteDocumentHandler; ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > m_xEmptyList; com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > m_rItemAccess; ::rtl::OUString m_aXMLToolbarNS; ::rtl::OUString m_aXMLXlinkNS; ::rtl::OUString m_aAttributeType; ::rtl::OUString m_aAttributeURL; }; } // namespace framework #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #define CONV_FUNCTOR( name, ...) \ struct name { \ template<typename A, typename B, typename C> \ static void apply(A&& a, B&& b, C& c){ \ __VA_ARGS__; \ } \ }; CONV_FUNCTOR( default_conv1_full, c = etl::conv_1d_full(a, b) ) CONV_FUNCTOR( std_conv1_full, etl::impl::standard::conv1_full(a, b, c) ) CONV_FUNCTOR( reduc_conv1_full, etl::impl::reduc::conv1_full(a, b, c) ) //MMUL_FUNCTOR( lazy_mmul, c = etl::lazy_mmul(a, b) ) //MMUL_FUNCTOR( strassen_mmul, c = etl::strassen_mmul(a, b) ) //MMUL_FUNCTOR( eblas_mmul_float, etl::impl::eblas::fast_sgemm(a, b, c) ) //MMUL_FUNCTOR( eblas_mmul_double, etl::impl::eblas::fast_dgemm(a, b, c) ) #define CONV1_FULL_TEST_CASE_SECTION_DEFAULT CONV_TEST_CASE_SECTIONS( default_conv1_full, default_conv1_full ) #define CONV1_FULL_TEST_CASE_SECTION_STD CONV_TEST_CASE_SECTIONS( std_conv1_full, std_conv1_full ) #define CONV1_FULL_TEST_CASE_SECTION_REDUC CONV_TEST_CASE_SECTIONS( reduc_conv1_full, reduc_conv1_full ) //#define MMUL_TEST_CASE_SECTION_LAZY MMUL_TEST_CASE_SECTIONS( lazy_mmul, lazy_mmul ) //#define MMUL_TEST_CASE_SECTION_STRASSEN MMUL_TEST_CASE_SECTIONS( strassen_mmul, strassen_mmul ) //#define MMUL_TEST_CASE_SECTION_EBLAS MMUL_TEST_CASE_SECTIONS( eblas_mmul_float, eblas_mmul_double ) //#ifdef ETL_BLAS_MODE //MMUL_FUNCTOR( blas_mmul_float, etl::impl::blas::sgemm(a, b, c) ) //MMUL_FUNCTOR( blas_mmul_double, etl::impl::blas::dgemm(a, b, c) ) //#define MMUL_TEST_CASE_SECTION_BLAS MMUL_TEST_CASE_SECTIONS( blas_mmul_float, blas_mmul_double ) //#else //#define MMUL_TEST_CASE_SECTION_BLAS //#endif #define CONV_TEST_CASE_DECL( name, description ) \ template<typename T, typename Impl> \ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )(); \ TEST_CASE( name, description ) #define CONV_TEST_CASE_SECTION( Tn, Impln) \ SECTION( #Tn #Impln ) \ { \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )<Tn, Impln>(); \ } #define CONV_TEST_CASE_DEFN \ template<typename T, typename Impl> \ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )() #define CONV_TEST_CASE_SECTIONS( S1, S2 ) \ CONV_TEST_CASE_SECTION( float, S1 ) \ CONV_TEST_CASE_SECTION( double, S2 ) #define CONV1_FULL_TEST_CASE( name, description ) \ CONV_TEST_CASE_DECL( name, description ) \ { \ CONV1_FULL_TEST_CASE_SECTION_DEFAULT \ CONV1_FULL_TEST_CASE_SECTION_STD \ CONV1_FULL_TEST_CASE_SECTION_REDUC \ } \ CONV_TEST_CASE_DEFN <commit_msg>Update for conv2<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #define CONV_FUNCTOR( name, ...) \ struct name { \ template<typename A, typename B, typename C> \ static void apply(A&& a, B&& b, C& c){ \ __VA_ARGS__; \ } \ }; CONV_FUNCTOR( default_conv1_full, c = etl::conv_1d_full(a, b) ) CONV_FUNCTOR( std_conv1_full, etl::impl::standard::conv1_full(a, b, c) ) CONV_FUNCTOR( reduc_conv1_full, etl::impl::reduc::conv1_full(a, b, c) ) CONV_FUNCTOR( default_conv2_full, c = etl::conv_2d_full(a, b) ) CONV_FUNCTOR( std_conv2_full, etl::impl::standard::conv2_full(a, b, c) ) CONV_FUNCTOR( reduc_conv2_full, etl::impl::reduc::conv2_full(a, b, c) ) #define CONV1_FULL_TEST_CASE_SECTION_DEFAULT CONV_TEST_CASE_SECTIONS( default_conv1_full, default_conv1_full ) #define CONV1_FULL_TEST_CASE_SECTION_STD CONV_TEST_CASE_SECTIONS( std_conv1_full, std_conv1_full ) #define CONV1_FULL_TEST_CASE_SECTION_REDUC CONV_TEST_CASE_SECTIONS( reduc_conv1_full, reduc_conv1_full ) #define CONV2_FULL_TEST_CASE_SECTION_DEFAULT CONV_TEST_CASE_SECTIONS( default_conv2_full, default_conv2_full ) #define CONV2_FULL_TEST_CASE_SECTION_STD CONV_TEST_CASE_SECTIONS( std_conv2_full, std_conv2_full ) #define CONV2_FULL_TEST_CASE_SECTION_REDUC CONV_TEST_CASE_SECTIONS( reduc_conv2_full, reduc_conv2_full ) //#ifdef ETL_BLAS_MODE //MMUL_FUNCTOR( blas_mmul_float, etl::impl::blas::sgemm(a, b, c) ) //MMUL_FUNCTOR( blas_mmul_double, etl::impl::blas::dgemm(a, b, c) ) //#define MMUL_TEST_CASE_SECTION_BLAS MMUL_TEST_CASE_SECTIONS( blas_mmul_float, blas_mmul_double ) //#else //#define MMUL_TEST_CASE_SECTION_BLAS //#endif #define CONV_TEST_CASE_DECL( name, description ) \ template<typename T, typename Impl> \ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )(); \ TEST_CASE( name, description ) #define CONV_TEST_CASE_SECTION( Tn, Impln) \ SECTION( #Tn "_" #Impln ) \ { \ INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )<Tn, Impln>(); \ } #define CONV_TEST_CASE_DEFN \ template<typename T, typename Impl> \ static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____ )() #define CONV_TEST_CASE_SECTIONS( S1, S2 ) \ CONV_TEST_CASE_SECTION( float, S1 ) \ CONV_TEST_CASE_SECTION( double, S2 ) #define CONV1_FULL_TEST_CASE( name, description ) \ CONV_TEST_CASE_DECL( name, description ) \ { \ CONV1_FULL_TEST_CASE_SECTION_DEFAULT \ CONV1_FULL_TEST_CASE_SECTION_STD \ CONV1_FULL_TEST_CASE_SECTION_REDUC \ } \ CONV_TEST_CASE_DEFN #define CONV2_FULL_TEST_CASE( name, description ) \ CONV_TEST_CASE_DECL( name, description ) \ { \ CONV2_FULL_TEST_CASE_SECTION_DEFAULT \ CONV2_FULL_TEST_CASE_SECTION_STD \ CONV2_FULL_TEST_CASE_SECTION_REDUC \ } \ CONV_TEST_CASE_DEFN <|endoftext|>
<commit_before>// PythonStuff.cpp #include "stdafx.h" #include <wx/file.h> #include <wx/mimetype.h> #include "PythonStuff.h" #include "ProgramCanvas.h" #include "OutputCanvas.h" #include "Program.h" static bool write_python_file(const wxString& python_file_path) { wxFile ofs(python_file_path.c_str(), wxFile::write); if(!ofs.IsOpened())return false; ofs.Write(theApp.m_program_canvas->m_textCtrl->GetValue()); return true; } bool HeeksPyPostProcess() { try{ theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window // write the python file wxString file_str = theApp.GetDllFolder() + wxString(_T("/post.py")); if(!write_python_file(file_str)) { wxMessageBox(_T("couldn't write post.py!")); } else { ::wxSetWorkingDirectory(theApp.GetDllFolder()); // call the python file #ifdef WIN32 wxString batch_file_str = theApp.GetDllFolder() + wxString(_T("/post.bat")); wxExecute(batch_file_str, wxEXEC_SYNC); #else wxString py_file_str = theApp.GetDllFolder() + wxString(_T("/post.py")); wxExecute(wxString(_T("python ")) + py_file_str, wxEXEC_SYNC); #endif // in Windows, at least, executing the bat file was making HeeksCAD change it's Z order heeksCAD->GetMainFrame()->Raise(); return true; } } catch(...) { wxMessageBox(_T("Error while post-processing the program!")); } return false; } bool HeeksPyBackplot(const wxString &filepath) { try{ theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window ::wxSetWorkingDirectory(theApp.GetDllFolder()); // call the python file #ifdef WIN32 wxString py_file_str = wxString(_T("\"")) + theApp.GetDllFolder() + _T("/nc_read.bat\" iso ") + filepath; wxExecute(py_file_str, wxEXEC_SYNC); #else wxString py_file_str = wxString(_T("\"")) + theApp.GetDllFolder() + wxString(_T("/nc/iso_read.py\" ")) + filepath; wxExecute(wxString(_T("python ")) + py_file_str, wxEXEC_SYNC); #endif // in Windows, at least, executing the bat file was making HeeksCAD change it's Z order heeksCAD->GetMainFrame()->Raise(); // there should now be nccode.xml written #ifdef WIN32 wxString xml_file_str = theApp.GetDllFolder() + wxString(_T("/")) + filepath + wxString(_T(".xml")); #else wxString xml_file_str = theApp.GetDllFolder() + wxString(_T("/")) + filepath + wxString(_T(".nc.xml")); #endif wxFile ofs(xml_file_str.c_str()); if(!ofs.IsOpened()) { wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str); return false; } // read the xml file, just like paste, into the program heeksCAD->OpenXMLFile(xml_file_str, true, theApp.m_program); heeksCAD->Repaint(); return true; } catch(...) { wxMessageBox(_T("Error while backplotting the program!")); } return false; } <commit_msg>changed backplot file from .xml to .nc.xml<commit_after>// PythonStuff.cpp #include "stdafx.h" #include <wx/file.h> #include <wx/mimetype.h> #include "PythonStuff.h" #include "ProgramCanvas.h" #include "OutputCanvas.h" #include "Program.h" static bool write_python_file(const wxString& python_file_path) { wxFile ofs(python_file_path.c_str(), wxFile::write); if(!ofs.IsOpened())return false; ofs.Write(theApp.m_program_canvas->m_textCtrl->GetValue()); return true; } bool HeeksPyPostProcess() { try{ theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window // write the python file wxString file_str = theApp.GetDllFolder() + wxString(_T("/post.py")); if(!write_python_file(file_str)) { wxMessageBox(_T("couldn't write post.py!")); } else { ::wxSetWorkingDirectory(theApp.GetDllFolder()); // call the python file #ifdef WIN32 wxString batch_file_str = theApp.GetDllFolder() + wxString(_T("/post.bat")); wxExecute(batch_file_str, wxEXEC_SYNC); #else wxString py_file_str = theApp.GetDllFolder() + wxString(_T("/post.py")); wxExecute(wxString(_T("python ")) + py_file_str, wxEXEC_SYNC); #endif // in Windows, at least, executing the bat file was making HeeksCAD change it's Z order heeksCAD->GetMainFrame()->Raise(); return true; } } catch(...) { wxMessageBox(_T("Error while post-processing the program!")); } return false; } bool HeeksPyBackplot(const wxString &filepath) { try{ theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window ::wxSetWorkingDirectory(theApp.GetDllFolder()); // call the python file #ifdef WIN32 wxString py_file_str = wxString(_T("\"")) + theApp.GetDllFolder() + _T("/nc_read.bat\" iso ") + filepath; wxExecute(py_file_str, wxEXEC_SYNC); #else wxString py_file_str = wxString(_T("\"")) + theApp.GetDllFolder() + wxString(_T("/nc/iso_read.py\" ")) + filepath; wxExecute(wxString(_T("python ")) + py_file_str, wxEXEC_SYNC); #endif // in Windows, at least, executing the bat file was making HeeksCAD change it's Z order heeksCAD->GetMainFrame()->Raise(); // there should now be a .nc.xml written wxString xml_file_str = theApp.GetDllFolder() + wxString(_T("/")) + filepath + wxString(_T(".nc.xml")); wxFile ofs(xml_file_str.c_str()); if(!ofs.IsOpened()) { wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str); return false; } // read the xml file, just like paste, into the program heeksCAD->OpenXMLFile(xml_file_str, true, theApp.m_program); heeksCAD->Repaint(); return true; } catch(...) { wxMessageBox(_T("Error while backplotting the program!")); } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ConnectionPageSetup.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ $Date: 2007-05-10 10:22: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_CONNECTIONPAGESETUP_HXX #include "ConnectionPageSetup.hxx" #endif #ifndef _DBAUI_AUTOCONTROLS_HRC_ #include "AutoControls.hrc" #endif #ifndef _DBAUI_DBADMINSETUP_HRC_ #include "dbadminsetup.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBU_DLG_HRC_ #include "dbu_dlg.hrc" #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SFXSTRITEM_HXX #include <svtools/stritem.hxx> #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _DBAUI_DATASOURCEITEMS_HXX_ #include "dsitems.hxx" #endif #ifndef _DBA_DBACCESS_HELPID_HRC_ #include "dbaccess_helpid.hrc" #endif #ifndef _DBAUI_LOCALRESACCESS_HXX_ #include "localresaccess.hxx" #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _DBAUI_DBADMIN_HXX_ #include "dbadmin.hxx" #endif #ifndef _DBAUI_DBADMIN_HRC_ #include "dbadmin.hrc" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _VCL_STDTEXT_HXX #include <vcl/stdtext.hxx> #endif #ifndef _DBAUI_SQLMESSAGE_HXX_ #include "sqlmessage.hxx" #endif #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _DBAUI_DSSELECT_HXX_ #include "dsselect.hxx" #endif #ifndef SVTOOLS_FILENOTATION_HXX_ #include <svtools/filenotation.hxx> #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFolderPicker.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif // #106016# ------------------------------------ #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include <com/sun/star/task/XInteractionHandler.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XPROGRESSHANDLER_HPP_ #include <com/sun/star/ucb/XProgressHandler.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UNOTOOLS_UCBHELPER_HXX #include <unotools/ucbhelper.hxx> #endif #ifndef _UCBHELPER_COMMANDENVIRONMENT_HXX #include <ucbhelper/commandenvironment.hxx> #endif #ifndef DBAUI_FILEPICKER_INTERACTION_HXX #include "finteraction.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _SFX_DOCFILT_HACK_HXX #include <sfx2/docfilt.hxx> #endif #ifndef _SV_MNEMONIC_HXX #include <vcl/mnemonic.hxx> #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; using namespace ::com::sun::star::ui::dialogs; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; using namespace ::dbtools; using namespace ::svt; OGenericAdministrationPage* OConnectionTabPageSetup::CreateDbaseTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_DBASE, _rAttrSet, STR_DBASE_HELPTEXT, STR_DBASE_HEADERTEXT, STR_DBASE_PATH_OR_FILE); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateMSAccessTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_MSACCESS, _rAttrSet, STR_MSACCESS_HELPTEXT, STR_MSACCESS_HEADERTEXT, STR_MSACCESS_MDB_FILE); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateAdabasTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADABAS, _rAttrSet, STR_ADABAS_HELPTEXT, STR_ADABAS_HEADERTEXT, STR_ADABAS_DATABASE_NAME); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateADOTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADO, _rAttrSet, STR_ADO_HELPTEXT, STR_ADO_HEADERTEXT, STR_COMMONURL); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateODBCTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ODBC, _rAttrSet, STR_ODBC_HELPTEXT, STR_ODBC_HEADERTEXT, STR_NAME_OF_ODBC_DATASOURCE); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateUserDefinedTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_USERDEFINED, _rAttrSet, USHRT_MAX, USHRT_MAX, STR_COMMONURL); oDBWizardPage->FreeResource(); return oDBWizardPage; } //======================================================================== //= OConnectionTabPageSetup //======================================================================== DBG_NAME(OConnectionTabPageSetup) OConnectionTabPageSetup::OConnectionTabPageSetup(Window* pParent, USHORT _rId, const SfxItemSet& _rCoreAttrs, USHORT _nHelpTextResId, USHORT _nHeaderResId, USHORT _nUrlResId) :OConnectionHelper(pParent, ModuleRes(_rId), _rCoreAttrs) ,m_bUserGrabFocus(sal_True) ,m_aFT_HelpText(this, ModuleRes(FT_AUTOWIZARDHELPTEXT)) { DBG_CTOR(OConnectionTabPageSetup, NULL); if ( USHRT_MAX != _nHelpTextResId ) { String sHelpText = String(ModuleRes(_nHelpTextResId)); m_aFT_HelpText.SetText(sHelpText); } else m_aFT_HelpText.Hide(); if ( USHRT_MAX != _nHeaderResId ) SetHeaderText(FT_AUTOWIZARDHEADER, _nHeaderResId); if ( USHRT_MAX != _nUrlResId ) { String sLabelText = String(ModuleRes(_nUrlResId)); m_aFT_Connection.SetText(sLabelText); if ( USHRT_MAX == _nHelpTextResId ) { Point aPos = m_aFT_HelpText.GetPosPixel(); Point aFTPos = m_aFT_Connection.GetPosPixel(); Point aEDPos = m_aET_Connection.GetPosPixel(); Point aPBPos = m_aPB_Connection.GetPosPixel(); aEDPos.Y() = aPos.Y() + aEDPos.Y() - aFTPos.Y(); aPBPos.Y() = aPos.Y() + aPBPos.Y() - aFTPos.Y(); aFTPos.Y() = aPos.Y(); m_aFT_Connection.SetPosPixel(aFTPos); m_aET_Connection.SetPosPixel(aEDPos); m_aPB_Connection.SetPosPixel(aPBPos); } } else m_aFT_Connection.Hide(); m_aET_Connection.SetModifyHdl(LINK(this, OConnectionTabPageSetup, OnEditModified)); SetRoadmapStateValue(sal_False); } // ----------------------------------------------------------------------- OConnectionTabPageSetup::~OConnectionTabPageSetup() { DBG_DTOR(OConnectionTabPageSetup,NULL); } // ----------------------------------------------------------------------- void OConnectionTabPageSetup::implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { m_eType = m_pAdminDialog->getDatasourceType(_rSet); // special handling for oracle, this can only happen // if the user enters the same url as used for Oracle and we are on the JDBC path if ( DST_ORACLE_JDBC == m_eType ) m_eType = DST_JDBC; OConnectionHelper::implInitControls(_rSet, _bSaveValue); if ( m_eType >= DST_USERDEFINE1 ) { String sDisplayName = m_pCollection->getTypeDisplayName(m_eType); FixedText* ppTextControls[] ={&m_aFT_Connection}; for (size_t i = 0; i < sizeof(ppTextControls)/sizeof(ppTextControls[0]); ++i) { ppTextControls[i]->SetText(sDisplayName); } } callModifiedHdl(); } // ----------------------------------------------------------------------- sal_Bool OConnectionTabPageSetup::commitPage(COMMIT_REASON /*_eReason*/) { return commitURL(); } // ----------------------------------------------------------------------- sal_Bool OConnectionTabPageSetup::FillItemSet(SfxItemSet& _rSet) { sal_Bool bChangedSomething = sal_False; fillString(_rSet,&m_aET_Connection, DSID_CONNECTURL, bChangedSomething); return bChangedSomething; } // ----------------------------------------------------------------------- bool OConnectionTabPageSetup::checkTestConnection() { return !m_aET_Connection.IsVisible() || (m_aET_Connection.GetTextNoPrefix().Len() != 0); } // ----------------------------------------------------------------------- IMPL_LINK(OConnectionTabPageSetup, OnEditModified, Edit*, /*_pEdit*/) { SetRoadmapStateValue(checkTestConnection()); callModifiedHdl(); return 0L; } //......................................................................... } // namespace dbaui //......................................................................... <commit_msg>INTEGRATION: CWS oj14 (1.5.8); FILE MERGED 2007/06/04 18:14:43 oj 1.5.8.6: RESYNC: (1.7-1.9); FILE MERGED 2006/11/07 09:19:11 oj 1.5.8.5: RESYNC: (1.6-1.7); FILE MERGED 2006/07/04 07:53:59 oj 1.5.8.4: RESYNC: (1.5-1.6); FILE MERGED 2006/04/25 13:02:50 oj 1.5.8.3: new include 2006/03/20 07:48:21 oj 1.5.8.2: use of module client helper 2006/01/03 07:49:06 oj 1.5.8.1: changed module client<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ConnectionPageSetup.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-07-06 08:10:32 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBAUI_CONNECTIONPAGESETUP_HXX #include "ConnectionPageSetup.hxx" #endif #ifndef _DBAUI_AUTOCONTROLS_HRC_ #include "AutoControls.hrc" #endif #ifndef _DBAUI_DBADMINSETUP_HRC_ #include "dbadminsetup.hrc" #endif #ifndef _DBU_DLG_HRC_ #include "dbu_dlg.hrc" #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _SFXSTRITEM_HXX #include <svtools/stritem.hxx> #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _DBAUI_DATASOURCEITEMS_HXX_ #include "dsitems.hxx" #endif #ifndef _DBA_DBACCESS_HELPID_HRC_ #include "dbaccess_helpid.hrc" #endif #ifndef _DBAUI_LOCALRESACCESS_HXX_ #include "localresaccess.hxx" #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _DBAUI_DBADMIN_HXX_ #include "dbadmin.hxx" #endif #ifndef _DBAUI_DBADMIN_HRC_ #include "dbadmin.hrc" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif #ifndef _VCL_STDTEXT_HXX #include <vcl/stdtext.hxx> #endif #ifndef _DBAUI_SQLMESSAGE_HXX_ #include "sqlmessage.hxx" #endif #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _DBAUI_DSSELECT_HXX_ #include "dsselect.hxx" #endif #ifndef SVTOOLS_FILENOTATION_HXX_ #include <svtools/filenotation.hxx> #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFolderPicker.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif // #106016# ------------------------------------ #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include <com/sun/star/task/XInteractionHandler.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XPROGRESSHANDLER_HPP_ #include <com/sun/star/ucb/XProgressHandler.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef DBAUI_TOOLS_HXX #include "UITools.hxx" #endif #ifndef _UNOTOOLS_LOCALFILEHELPER_HXX #include <unotools/localfilehelper.hxx> #endif #ifndef _UNOTOOLS_UCBHELPER_HXX #include <unotools/ucbhelper.hxx> #endif #ifndef _UCBHELPER_COMMANDENVIRONMENT_HXX #include <ucbhelper/commandenvironment.hxx> #endif #ifndef DBAUI_FILEPICKER_INTERACTION_HXX #include "finteraction.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include <connectivity/CommonTools.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _SFX_DOCFILT_HACK_HXX #include <sfx2/docfilt.hxx> #endif #ifndef _SV_MNEMONIC_HXX #include <vcl/mnemonic.hxx> #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ucb; using namespace ::com::sun::star::ui::dialogs; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; using namespace ::dbtools; using namespace ::svt; OGenericAdministrationPage* OConnectionTabPageSetup::CreateDbaseTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_DBASE, _rAttrSet, STR_DBASE_HELPTEXT, STR_DBASE_HEADERTEXT, STR_DBASE_PATH_OR_FILE); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateMSAccessTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_MSACCESS, _rAttrSet, STR_MSACCESS_HELPTEXT, STR_MSACCESS_HEADERTEXT, STR_MSACCESS_MDB_FILE); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateAdabasTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADABAS, _rAttrSet, STR_ADABAS_HELPTEXT, STR_ADABAS_HEADERTEXT, STR_ADABAS_DATABASE_NAME); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateADOTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ADO, _rAttrSet, STR_ADO_HELPTEXT, STR_ADO_HEADERTEXT, STR_COMMONURL); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateODBCTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_ODBC, _rAttrSet, STR_ODBC_HELPTEXT, STR_ODBC_HEADERTEXT, STR_NAME_OF_ODBC_DATASOURCE); oDBWizardPage->FreeResource(); return oDBWizardPage; } OGenericAdministrationPage* OConnectionTabPageSetup::CreateUserDefinedTabPage( Window* pParent, const SfxItemSet& _rAttrSet ) { OConnectionTabPageSetup* oDBWizardPage = new OConnectionTabPageSetup( pParent, PAGE_DBWIZARD_USERDEFINED, _rAttrSet, USHRT_MAX, USHRT_MAX, STR_COMMONURL); oDBWizardPage->FreeResource(); return oDBWizardPage; } //======================================================================== //= OConnectionTabPageSetup //======================================================================== DBG_NAME(OConnectionTabPageSetup) OConnectionTabPageSetup::OConnectionTabPageSetup(Window* pParent, USHORT _rId, const SfxItemSet& _rCoreAttrs, USHORT _nHelpTextResId, USHORT _nHeaderResId, USHORT _nUrlResId) :OConnectionHelper(pParent, ModuleRes(_rId), _rCoreAttrs) ,m_bUserGrabFocus(sal_True) ,m_aFT_HelpText(this, ModuleRes(FT_AUTOWIZARDHELPTEXT)) { DBG_CTOR(OConnectionTabPageSetup, NULL); if ( USHRT_MAX != _nHelpTextResId ) { String sHelpText = String(ModuleRes(_nHelpTextResId)); m_aFT_HelpText.SetText(sHelpText); } else m_aFT_HelpText.Hide(); if ( USHRT_MAX != _nHeaderResId ) SetHeaderText(FT_AUTOWIZARDHEADER, _nHeaderResId); if ( USHRT_MAX != _nUrlResId ) { String sLabelText = String(ModuleRes(_nUrlResId)); m_aFT_Connection.SetText(sLabelText); if ( USHRT_MAX == _nHelpTextResId ) { Point aPos = m_aFT_HelpText.GetPosPixel(); Point aFTPos = m_aFT_Connection.GetPosPixel(); Point aEDPos = m_aET_Connection.GetPosPixel(); Point aPBPos = m_aPB_Connection.GetPosPixel(); aEDPos.Y() = aPos.Y() + aEDPos.Y() - aFTPos.Y(); aPBPos.Y() = aPos.Y() + aPBPos.Y() - aFTPos.Y(); aFTPos.Y() = aPos.Y(); m_aFT_Connection.SetPosPixel(aFTPos); m_aET_Connection.SetPosPixel(aEDPos); m_aPB_Connection.SetPosPixel(aPBPos); } } else m_aFT_Connection.Hide(); m_aET_Connection.SetModifyHdl(LINK(this, OConnectionTabPageSetup, OnEditModified)); SetRoadmapStateValue(sal_False); } // ----------------------------------------------------------------------- OConnectionTabPageSetup::~OConnectionTabPageSetup() { DBG_DTOR(OConnectionTabPageSetup,NULL); } // ----------------------------------------------------------------------- void OConnectionTabPageSetup::implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { m_eType = m_pAdminDialog->getDatasourceType(_rSet); // special handling for oracle, this can only happen // if the user enters the same url as used for Oracle and we are on the JDBC path if ( DST_ORACLE_JDBC == m_eType ) m_eType = DST_JDBC; OConnectionHelper::implInitControls(_rSet, _bSaveValue); if ( m_eType >= DST_USERDEFINE1 ) { String sDisplayName = m_pCollection->getTypeDisplayName(m_eType); FixedText* ppTextControls[] ={&m_aFT_Connection}; for (size_t i = 0; i < sizeof(ppTextControls)/sizeof(ppTextControls[0]); ++i) { ppTextControls[i]->SetText(sDisplayName); } } callModifiedHdl(); } // ----------------------------------------------------------------------- sal_Bool OConnectionTabPageSetup::commitPage(COMMIT_REASON /*_eReason*/) { return commitURL(); } // ----------------------------------------------------------------------- sal_Bool OConnectionTabPageSetup::FillItemSet(SfxItemSet& _rSet) { sal_Bool bChangedSomething = sal_False; fillString(_rSet,&m_aET_Connection, DSID_CONNECTURL, bChangedSomething); return bChangedSomething; } // ----------------------------------------------------------------------- bool OConnectionTabPageSetup::checkTestConnection() { return !m_aET_Connection.IsVisible() || (m_aET_Connection.GetTextNoPrefix().Len() != 0); } // ----------------------------------------------------------------------- IMPL_LINK(OConnectionTabPageSetup, OnEditModified, Edit*, /*_pEdit*/) { SetRoadmapStateValue(checkTestConnection()); callModifiedHdl(); return 0L; } //......................................................................... } // namespace dbaui //......................................................................... <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: documentcontroller.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2007-04-16 16:28:39 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBACCESS_SOURCE_UI_INC_DOCUMENTCONTROLLER_HXX #include "documentcontroller.hxx" #endif /** === begin UNO includes === **/ /** === end UNO includes === **/ #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif //........................................................................ namespace dbaui { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; //==================================================================== //= ModelControllerConnector //==================================================================== DBG_NAME( ModelControllerConnector ) //-------------------------------------------------------------------- ModelControllerConnector::ModelControllerConnector() { DBG_CTOR( ModelControllerConnector, NULL ); } //-------------------------------------------------------------------- ModelControllerConnector::ModelControllerConnector( const Reference< XModel >& _rxModel, const Reference< XController >& _rxController ) :m_xModel( _rxModel ) ,m_xController( _rxController ) { DBG_CTOR( ModelControllerConnector, NULL ); DBG_ASSERT( _rxModel.is() && m_xController.is(), "ModelControllerConnector::ModelControllerConnector: invalid model or controller!" ); impl_connect(); } //-------------------------------------------------------------------- ModelControllerConnector::ModelControllerConnector( const ModelControllerConnector& _rSource ) { DBG_CTOR( ModelControllerConnector, NULL ); impl_copyFrom( _rSource ); } //-------------------------------------------------------------------- ModelControllerConnector& ModelControllerConnector::operator=( const ModelControllerConnector& _rSource ) { if ( this != &_rSource ) impl_copyFrom( _rSource ); return *this; } //-------------------------------------------------------------------- void ModelControllerConnector::swap( ModelControllerConnector& _rSource ) { ModelControllerConnector aTemp( _rSource ); _rSource.impl_copyFrom( *this ); impl_copyFrom( aTemp ); } //-------------------------------------------------------------------- void ModelControllerConnector::impl_copyFrom( const ModelControllerConnector& _rSource ) { Model aNewModel( _rSource.m_xModel ); Controller aNewController( _rSource.m_xController ); impl_disconnect(); m_xModel = aNewModel; m_xController = aNewController; impl_connect(); } //-------------------------------------------------------------------- ModelControllerConnector::~ModelControllerConnector() { impl_disconnect(); DBG_DTOR( ModelControllerConnector, NULL ); } //-------------------------------------------------------------------- void ModelControllerConnector::impl_connect() { try { Reference< XModel > xModel = m_xModel; if ( xModel.is() && m_xController.is() ) xModel->connectController( m_xController ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "ModelControllerConnector::impl_connect: caught an exception!" ); } } //-------------------------------------------------------------------- void ModelControllerConnector::impl_disconnect() { try { Reference< XModel > xModel = m_xModel; if ( xModel.is() && m_xController.is() ) xModel->disconnectController( m_xController ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "ModelControllerConnector::impl_disconnect: caught an exception!" ); } } //........................................................................ } // namespace dbaui //........................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.5.182); FILE MERGED 2008/03/31 13:27:54 rt 1.5.182.1: #i87441# Change license header to LPGL v3.<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: documentcontroller.cxx,v $ * $Revision: 1.6 $ * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBACCESS_SOURCE_UI_INC_DOCUMENTCONTROLLER_HXX #include "documentcontroller.hxx" #endif /** === begin UNO includes === **/ /** === end UNO includes === **/ #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif //........................................................................ namespace dbaui { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; //==================================================================== //= ModelControllerConnector //==================================================================== DBG_NAME( ModelControllerConnector ) //-------------------------------------------------------------------- ModelControllerConnector::ModelControllerConnector() { DBG_CTOR( ModelControllerConnector, NULL ); } //-------------------------------------------------------------------- ModelControllerConnector::ModelControllerConnector( const Reference< XModel >& _rxModel, const Reference< XController >& _rxController ) :m_xModel( _rxModel ) ,m_xController( _rxController ) { DBG_CTOR( ModelControllerConnector, NULL ); DBG_ASSERT( _rxModel.is() && m_xController.is(), "ModelControllerConnector::ModelControllerConnector: invalid model or controller!" ); impl_connect(); } //-------------------------------------------------------------------- ModelControllerConnector::ModelControllerConnector( const ModelControllerConnector& _rSource ) { DBG_CTOR( ModelControllerConnector, NULL ); impl_copyFrom( _rSource ); } //-------------------------------------------------------------------- ModelControllerConnector& ModelControllerConnector::operator=( const ModelControllerConnector& _rSource ) { if ( this != &_rSource ) impl_copyFrom( _rSource ); return *this; } //-------------------------------------------------------------------- void ModelControllerConnector::swap( ModelControllerConnector& _rSource ) { ModelControllerConnector aTemp( _rSource ); _rSource.impl_copyFrom( *this ); impl_copyFrom( aTemp ); } //-------------------------------------------------------------------- void ModelControllerConnector::impl_copyFrom( const ModelControllerConnector& _rSource ) { Model aNewModel( _rSource.m_xModel ); Controller aNewController( _rSource.m_xController ); impl_disconnect(); m_xModel = aNewModel; m_xController = aNewController; impl_connect(); } //-------------------------------------------------------------------- ModelControllerConnector::~ModelControllerConnector() { impl_disconnect(); DBG_DTOR( ModelControllerConnector, NULL ); } //-------------------------------------------------------------------- void ModelControllerConnector::impl_connect() { try { Reference< XModel > xModel = m_xModel; if ( xModel.is() && m_xController.is() ) xModel->connectController( m_xController ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "ModelControllerConnector::impl_connect: caught an exception!" ); } } //-------------------------------------------------------------------- void ModelControllerConnector::impl_disconnect() { try { Reference< XModel > xModel = m_xModel; if ( xModel.is() && m_xController.is() ) xModel->disconnectController( m_xController ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "ModelControllerConnector::impl_disconnect: caught an exception!" ); } } //........................................................................ } // namespace dbaui //........................................................................ <|endoftext|>
<commit_before>#include <cstddef> #include <glog/logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <dcel/dcel.hh> #include <dcel/Vertex.hh> #include <voronoi/geometry.hh> using voronoi::Point; using voronoi::FaceInfo; typedef dcel::DCEL<Point*, Point*, FaceInfo*> MyDCEL; static MyDCEL::Vertex* createVertex(MyDCEL& d, double x, double y) { MyDCEL::Vertex *v = d.createGetVertex(); v->getData() = new voronoi::Point(x, y); EXPECT_TRUE(v != NULL) << "Erro ao criar vértice"; return v; } static void createEdge(MyDCEL& d, MyDCEL::Vertex* origin, MyDCEL::Face* face, MyDCEL::Vertex* twinOrigin, MyDCEL::Face* twinFace, MyDCEL::HalfEdge** outHalfEdge, MyDCEL::HalfEdge** outTwinHalfEdge) { unsigned int i = d.createEdge(origin, face, twinOrigin, twinFace); *outHalfEdge = d.getHalfEdge(i); EXPECT_TRUE(*outHalfEdge != NULL) << "Erro ao criar meia aresta"; *outTwinHalfEdge = d.getHalfEdge(i + 1); origin->setIncidentEdge(*outHalfEdge); twinOrigin->setIncidentEdge(*outTwinHalfEdge); } TEST(DCELCheckTest, UnitTestingFrameworkWorks) { LOG(INFO) << "Starting DCEL check test."; const size_t VERTICES = 4; const size_t EDGES = 10; const size_t FACES = 2; MyDCEL d(VERTICES, EDGES, FACES); EXPECT_TRUE(d.getVertices().capacity() == VERTICES) << "Memória não alocada para os vértices."; EXPECT_TRUE(d.getHalfEdges().capacity() == EDGES * 2) << "Memória não alocada para as meia arestas."; EXPECT_TRUE(d.getFaces().capacity() == FACES) << "Memória não alocada para as faces."; MyDCEL::Vertex* v1 = createVertex(d, 0, 4); MyDCEL::Vertex* v2 = createVertex(d, 2, 4); MyDCEL::Vertex* v3 = createVertex(d, 2, 2); MyDCEL::Vertex* v4 = createVertex(d, 1, 1); MyDCEL::Face* f1 = d.createGetFace(NULL); MyDCEL::Face* f2 = d.createGetFace(NULL); f1->getData() = new FaceInfo(1); f2->getData() = new FaceInfo(2); EXPECT_TRUE(f1 != NULL) << "Face 1 não criada"; EXPECT_TRUE(f2 != NULL) << "Face 2 não criada"; MyDCEL::HalfEdge *e11, *e12, *e21, *e22, *e31, *e32, *e41, *e42; e11 = e12 = e21 = e22 = e31 = e32 = e41 = e42 = NULL; /* Src Face TwinSrc TwinFace HalfEdge TwinHalfEdge */ createEdge(d, v1, f1, v2, f2, &e11, &e12); createEdge(d, v3, f1, v4, f1, &e21, &e22); createEdge(d, v3, f1, v1, f2, &e31, &e32); createEdge(d, v3, f2, v2, f1, &e41, &e42); e11->setNext(e42); e12->setNext(e32); e21->setNext(e22); e22->setNext(e31); e31->setNext(e11); e32->setNext(e41); e41->setNext(e12); e42->setNext(e21); f1->setBoundary(e22); f2->setBoundary(e32); d.checkAllFaces(); delete f1->getData(); delete f2->getData(); delete v1->getData(); delete v2->getData(); delete v3->getData(); delete v4->getData(); d.clear(); //d.getFace(0)->getData() = 0; LOG(INFO) << "Finishing DCEL check test."; } <commit_msg>Teste de unidade para a DCEL<commit_after>#include <cstddef> #include <glog/logging.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <dcel/dcel.hh> #include <dcel/Vertex.hh> #include <voronoi/geometry.hh> using voronoi::Point; using voronoi::FaceInfo; typedef dcel::DCEL<Point*, Point*, FaceInfo*> MyDCEL; static MyDCEL::Vertex* createVertex(MyDCEL& d, double x, double y) { MyDCEL::Vertex *v = d.createGetVertex(); v->getData() = new voronoi::Point(x, y); EXPECT_TRUE(v != NULL) << "Erro ao criar vértice"; return v; } static void createEdge(MyDCEL& d, MyDCEL::Vertex* origin, MyDCEL::Face* face, MyDCEL::Vertex* twinOrigin, MyDCEL::Face* twinFace, MyDCEL::HalfEdge** outHalfEdge, MyDCEL::HalfEdge** outTwinHalfEdge) { unsigned int i = d.createEdge(origin, face, twinOrigin, twinFace); *outHalfEdge = d.getHalfEdge(i); EXPECT_TRUE(*outHalfEdge != NULL) << "Erro ao criar meia aresta"; *outTwinHalfEdge = d.getHalfEdge(i + 1); origin->setIncidentEdge(*outHalfEdge); twinOrigin->setIncidentEdge(*outTwinHalfEdge); } static MyDCEL::Face* createFace(MyDCEL& d, int id) { MyDCEL::Face* face = d.createGetFace(NULL); EXPECT_TRUE(face != NULL) << "Face não alocada."; face->getData() = new FaceInfo(id); return face; } TEST(DCELCheckTest, UnitTestingFrameworkWorks) { LOG(INFO) << "Starting DCEL check test."; const size_t VERTICES = 4; const size_t EDGES = 4; const size_t FACES = 2; /* Criar DCEL alocando espaço o necessário */ MyDCEL d(VERTICES, EDGES, FACES); EXPECT_TRUE(d.getVertices().capacity() == VERTICES) << "Memória não alocada para os vértices."; EXPECT_TRUE(d.getHalfEdges().capacity() == EDGES * 2) << "Memória não alocada para as meia arestas."; EXPECT_TRUE(d.getFaces().capacity() == FACES) << "Memória não alocada para as faces."; /* Criar os vértices */ MyDCEL::Vertex* v1 = createVertex(d, 0, 4); MyDCEL::Vertex* v2 = createVertex(d, 2, 4); MyDCEL::Vertex* v3 = createVertex(d, 2, 2); MyDCEL::Vertex* v4 = createVertex(d, 1, 1); /* Criar as faces */ MyDCEL::Face* f1 = createFace(d, 1); MyDCEL::Face* f2 = createFace(d, 2); /* Criar as meias arestas */ MyDCEL::HalfEdge *e11, *e12, *e21, *e22, *e31, *e32, *e41, *e42; e11 = e12 = e21 = e22 = e31 = e32 = e41 = e42 = NULL; /* Src Face TwinSrc TwinFace HalfEdge TwinHalfEdge */ createEdge(d, v1, f1, v2, f2, &e11, &e12); createEdge(d, v3, f1, v4, f1, &e21, &e22); createEdge(d, v3, f1, v1, f2, &e31, &e32); createEdge(d, v3, f2, v2, f1, &e41, &e42); e11->setNext(e42); e12->setNext(e32); e21->setNext(e22); e22->setNext(e31); e31->setNext(e11); e32->setNext(e41); e41->setNext(e12); e42->setNext(e21); f1->setBoundary(e22); f2->setBoundary(e32); d.checkAllFaces(); /* Limpar a DCEL */ delete f1->getData(); delete f2->getData(); delete v1->getData(); delete v2->getData(); delete v3->getData(); delete v4->getData(); d.clear(); LOG(INFO) << "Finishing DCEL check test."; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/plat/mem/prdfMemTdCtlr_rt.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** @file prdfMemTdCtlr_rt.C * @brief A state machine for memory Targeted Diagnostics (runtime only). */ #include <prdfMemTdCtlr.H> // Platform includes #include <prdfMemEccAnalysis.H> #include <prdfMemScrubUtils.H> #include <prdfMemTps.H> #include <prdfMemUtils.H> #include <prdfMemVcm.H> #include <prdfP9McaDataBundle.H> #include <prdfP9McaExtraSig.H> #include <prdfPlatServices.H> using namespace TARGETING; namespace PRDF { using namespace PlatServices; //------------------------------------------------------------------------------ template <TARGETING::TYPE T> uint32_t MemTdCtlr<T>::handleTdEvent( STEP_CODE_DATA_STRUCT & io_sc, TdEntry * i_entry ) { #define PRDF_FUNC "[MemTdCtlr::handleTdEvent] " uint32_t o_rc = SUCCESS; do { // Make sure the TD controller is initialized. o_rc = initialize(); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "initialize() failed on 0x%08x", iv_chip->getHuid() ); break; } // Add this entry to the queue. iv_queue.push( i_entry ); // Don't interrupt a TD procedure if one is already in progress. if ( nullptr != iv_curProcedure ) break; // Stop background scrubbing. o_rc = stopBgScrub<T>( iv_chip ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "stopBgScrub<T>(0x%08x) failed", iv_chip->getHuid() ); break; } // Since we had to manually stop the maintenance command, refresh all // relevant registers that may have changed since the initial capture. // TODO: RTC 166837 // It is possible that background scrub could have found an ECC error // before we had a chance to stop the command. Therefore, we need to // call analyzeCmdComplete() first so that any ECC errors found can be // handled. Also, analyzeCmdComplete() will initialize the variables // needed so we know where to restart background scrubbing. bool junk = false; o_rc = analyzeCmdComplete( junk, io_sc ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "analyzeCmdComplete(0x%08x) failed", iv_chip->getHuid() ); break; } // Move onto the next step in the state machine. o_rc = nextStep( io_sc ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "nextStep() failed on 0x%08x", iv_chip->getHuid() ); break; } } while (0); return o_rc; #undef PRDF_FUNC } //------------------------------------------------------------------------------ template <TARGETING::TYPE T> uint32_t MemTdCtlr<T>::initialize() { #define PRDF_FUNC "[MemTdCtlr::initialize] " uint32_t o_rc = SUCCESS; do { if ( iv_initialized ) break; // nothing to do // Add any unverified chip marks to the TD queue // TODO: RTC 171866 // At this point, the TD controller is initialized. iv_initialized = true; } while (0); return o_rc; #undef PRDF_FUNC } //------------------------------------------------------------------------------ template <TARGETING::TYPE T> uint32_t MemTdCtlr<T>::defaultStep( STEP_CODE_DATA_STRUCT & io_sc ) { #define PRDF_FUNC "[MemTdCtlr::defaultStep] " uint32_t o_rc = SUCCESS; if ( iv_resumeBgScrub ) { // Background scrubbing paused for FFDC collection only. Resume the // current command. iv_resumeBgScrub = false; PRDF_TRAC( PRDF_FUNC "Calling resumeBgScrub<T>(0x%08x)", iv_chip->getHuid() ); o_rc = resumeBgScrub<T>( iv_chip ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "resumeBgScrub<T>(0x%08x) failed", iv_chip->getHuid() ); } } else { // A TD procedure has completed. Restart background scrubbing on the // next rank. TdRankListEntry nextRank = iv_rankList.getNext( iv_stoppedRank ); PRDF_TRAC( PRDF_FUNC "Calling startBgScrub<T>(0x%08x, m%ds%d)", nextRank.getChip()->getHuid(), nextRank.getRank().getMaster(), nextRank.getRank().getSlave() ); o_rc = startBgScrub<T>( nextRank.getChip(), nextRank.getRank() ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "startBgScrub<T>(0x%08x,m%ds%d) failed", nextRank.getChip()->getHuid(), nextRank.getRank().getMaster(), nextRank.getRank().getSlave() ); } } return o_rc; #undef PRDF_FUNC } //------------------------------------------------------------------------------ template <TARGETING::TYPE T, typename D> uint32_t __checkEcc( ExtensibleChip * i_chip, TdQueue & io_queue, const MemAddr & i_addr, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ) { #define PRDF_FUNC "[__checkEcc] " PRDF_ASSERT( nullptr != i_chip ); PRDF_ASSERT( T == i_chip->getType() ); uint32_t o_rc = SUCCESS; o_errorsFound = false; TargetHandle_t trgt = i_chip->getTrgt(); HUID huid = i_chip->getHuid(); MemRank rank = i_addr.getRank(); do { // Check for ECC errors. uint32_t eccAttns = 0; o_rc = checkEccFirs<T>( i_chip, eccAttns ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "checkEccFirs<T>(0x%08x) failed", huid ); break; } if ( 0 != (eccAttns & MAINT_INT_NCE_ETE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintINTER_CTE); // Can't do any more isolation at this time. So add the rank to the // callout list. MemoryMru mm { trgt, rank, MemoryMruData::CALLOUT_RANK }; io_sc.service_data->SetCallout( mm ); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); } if ( 0 != (eccAttns & MAINT_SOFT_NCE_ETE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintSOFT_CTE ); // Can't do any more isolation at this time. So add the rank to the // callout list. MemoryMru mm { trgt, rank, MemoryMruData::CALLOUT_RANK }; io_sc.service_data->SetCallout( mm ); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); } if ( 0 != (eccAttns & MAINT_HARD_NCE_ETE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintHARD_CTE ); // Query the per-symbol counters for the hard CE symbol. MemUtils::MaintSymbols symData; MemSymbol junk; o_rc = MemUtils::collectCeStats<T>( i_chip, rank, symData, junk ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "MemUtils::collectCeStats(0x%08x,m%ds%d) " "failed", huid, rank.getMaster(), rank.getSlave() ); break; } // The command will have stopped on the first occurrence. So there // should only be one symbol in the list. PRDF_ASSERT( 1 == symData.size() ); // Add the symbol to the callout list. MemoryMru mm { trgt, rank, symData[0].symbol }; io_sc.service_data->SetCallout( mm ); // Any hard CEs in MNFG should be immediately reported. if ( mfgMode() ) io_sc.service_data->setServiceCall(); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); /* TODO RTC 136129 // Dynamically deallocation the page. o_rc = MemDealloc::page<T>( i_chip, i_addr ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "MemDealloc::page(0x%08x) failed", huid ); break; } */ } if ( 0 != (eccAttns & MAINT_MPE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintMPE ); // Add entry to UE table. D db = static_cast<D>(i_chip->getDataBundle()); db->iv_ueTable.addEntry( UE_TABLE::SCRUB_MPE, i_addr ); // Read the chip mark from markstore. MemMark chipMark; o_rc = MarkStore::readChipMark<T>( i_chip, rank, chipMark ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "readChipMark<T>(0x%08x,%d) failed", huid, rank.getMaster() ); break; } // If the chip mark is not valid, then somehow the chip mark was // placed on a rank other than the rank in which the command // stopped. This would most likely be a code bug. PRDF_ASSERT( chipMark.isValid() ); // Add the mark to the callout list. MemoryMru mm { trgt, rank, chipMark.getSymbol() }; io_sc.service_data->SetCallout( mm ); // Add a VCM procedure to the queue. TdEntry * e = new VcmEvent<T>{ i_chip, rank, chipMark }; io_queue.push( e ); } if ( 0 != (eccAttns & MAINT_RCE_ETE) ) { o_errorsFound = true; // TODO: RTC 171867 } if ( 0 != (eccAttns & MAINT_UE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintUE ); // Since this will be a predictive callout, change the primary // signature as well. io_sc.service_data->setSignature( huid, PRDFSIG_MaintUE ); // Add entry to UE table. D db = static_cast<D>(i_chip->getDataBundle()); db->iv_ueTable.addEntry( UE_TABLE::SCRUB_UE, i_addr ); // Add the rank to the callout list. MemEcc::calloutMemUe<T>( i_chip, rank, io_sc ); // Make the error log predictive. io_sc.service_data->setServiceCall(); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); /* TODO RTC 136129 // Dynamically deallocation the rank. o_rc = MemDealloc::rank<T>( i_chip, rank ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "MemDealloc::rank(0x%08x, m%ds%d) failed", huid, rank.getMaster(), rank.getSlave() ); break; } */ } } while (0); return o_rc; #undef PRDF_FUNC } template uint32_t __checkEcc<TYPE_MCA, McaDataBundle *>( ExtensibleChip * i_chip, TdQueue & io_queue, const MemAddr & i_addr, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ); /* TODO RTC 157888 template uint32_t __checkEcc<TYPE_MBA>( ExtensibleChip * i_chip, TdQueue & io_queue, const MemAddr & i_addr, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ); */ //------------------------------------------------------------------------------ template <TARGETING::TYPE T> void MemTdCtlr<T>::collectStateCaptureData( STEP_CODE_DATA_STRUCT & io_sc, const char * i_startEnd ) { #define PRDF_FUNC "[MemTdCtlr<T>::collectStateCaptureData] " // TODO RTC 167827 #undef PRDF_FUNC } //------------------------------------------------------------------------------ // Avoid linker errors with the template. template class MemTdCtlr<TYPE_MCBIST>; template class MemTdCtlr<TYPE_MBA>; //------------------------------------------------------------------------------ } // end namespace PRDF <commit_msg>PRD: runtime IUE handling in MNFG mode<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/plat/mem/prdfMemTdCtlr_rt.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /** @file prdfMemTdCtlr_rt.C * @brief A state machine for memory Targeted Diagnostics (runtime only). */ #include <prdfMemTdCtlr.H> // Platform includes #include <prdfMemEccAnalysis.H> #include <prdfMemScrubUtils.H> #include <prdfMemTps.H> #include <prdfMemUtils.H> #include <prdfMemVcm.H> #include <prdfP9McaDataBundle.H> #include <prdfP9McaExtraSig.H> #include <prdfPlatServices.H> using namespace TARGETING; namespace PRDF { using namespace PlatServices; //------------------------------------------------------------------------------ template <TARGETING::TYPE T> uint32_t MemTdCtlr<T>::handleTdEvent( STEP_CODE_DATA_STRUCT & io_sc, TdEntry * i_entry ) { #define PRDF_FUNC "[MemTdCtlr::handleTdEvent] " uint32_t o_rc = SUCCESS; do { // Make sure the TD controller is initialized. o_rc = initialize(); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "initialize() failed on 0x%08x", iv_chip->getHuid() ); break; } // Add this entry to the queue. iv_queue.push( i_entry ); // Don't interrupt a TD procedure if one is already in progress. if ( nullptr != iv_curProcedure ) break; // Stop background scrubbing. o_rc = stopBgScrub<T>( iv_chip ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "stopBgScrub<T>(0x%08x) failed", iv_chip->getHuid() ); break; } // Since we had to manually stop the maintenance command, refresh all // relevant registers that may have changed since the initial capture. // TODO: RTC 166837 // It is possible that background scrub could have found an ECC error // before we had a chance to stop the command. Therefore, we need to // call analyzeCmdComplete() first so that any ECC errors found can be // handled. Also, analyzeCmdComplete() will initialize the variables // needed so we know where to restart background scrubbing. bool junk = false; o_rc = analyzeCmdComplete( junk, io_sc ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "analyzeCmdComplete(0x%08x) failed", iv_chip->getHuid() ); break; } // Move onto the next step in the state machine. o_rc = nextStep( io_sc ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "nextStep() failed on 0x%08x", iv_chip->getHuid() ); break; } } while (0); return o_rc; #undef PRDF_FUNC } //------------------------------------------------------------------------------ template <TARGETING::TYPE T> uint32_t MemTdCtlr<T>::initialize() { #define PRDF_FUNC "[MemTdCtlr::initialize] " uint32_t o_rc = SUCCESS; do { if ( iv_initialized ) break; // nothing to do // Add any unverified chip marks to the TD queue // TODO: RTC 171866 // At this point, the TD controller is initialized. iv_initialized = true; } while (0); return o_rc; #undef PRDF_FUNC } //------------------------------------------------------------------------------ template <TARGETING::TYPE T> uint32_t MemTdCtlr<T>::defaultStep( STEP_CODE_DATA_STRUCT & io_sc ) { #define PRDF_FUNC "[MemTdCtlr::defaultStep] " uint32_t o_rc = SUCCESS; if ( iv_resumeBgScrub ) { // Background scrubbing paused for FFDC collection only. Resume the // current command. iv_resumeBgScrub = false; PRDF_TRAC( PRDF_FUNC "Calling resumeBgScrub<T>(0x%08x)", iv_chip->getHuid() ); o_rc = resumeBgScrub<T>( iv_chip ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "resumeBgScrub<T>(0x%08x) failed", iv_chip->getHuid() ); } } else { // A TD procedure has completed. Restart background scrubbing on the // next rank. TdRankListEntry nextRank = iv_rankList.getNext( iv_stoppedRank ); PRDF_TRAC( PRDF_FUNC "Calling startBgScrub<T>(0x%08x, m%ds%d)", nextRank.getChip()->getHuid(), nextRank.getRank().getMaster(), nextRank.getRank().getSlave() ); o_rc = startBgScrub<T>( nextRank.getChip(), nextRank.getRank() ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "startBgScrub<T>(0x%08x,m%ds%d) failed", nextRank.getChip()->getHuid(), nextRank.getRank().getMaster(), nextRank.getRank().getSlave() ); } } return o_rc; #undef PRDF_FUNC } //------------------------------------------------------------------------------ template<TARGETING::TYPE T> uint32_t __handleRceEte( ExtensibleChip * i_chip, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ); template<> uint32_t __handleRceEte<TYPE_MCA>( ExtensibleChip * i_chip, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ) { #define PRDF_FUNC "[__handleRceEte] " uint32_t o_rc = SUCCESS; // Should only get this attention in MNFG mode. PRDF_ASSERT( mfgMode() ); do { // The RCE ETE attention could be from IUE, IMPE, or IRCD. Need to check // MCAECCFIR[37] to determine if there was at least one IUE. SCAN_COMM_REGISTER_CLASS * fir = i_chip->getRegister( "MCAECCFIR" ); o_rc = fir->Read(); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "Read() failed on MCAECCFIR: i_chip=0x%08x", i_chip->getHuid() ); break; } if ( !fir->IsBitSet(37) ) break; // nothing else to do // Handle the IUE. o_errorsFound = true; io_sc.service_data->AddSignatureList( i_chip->getTrgt(), PRDFSIG_MaintIUE ); o_rc = MemEcc::analyzeMaintIue<TYPE_MCA,McaDataBundle *>(i_chip, io_sc); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "analyzeMaintIue(0x%08x) failed", i_chip->getHuid() ); break; } } while (0); return o_rc; #undef PRDF_FUNC } /* TODO RTC 157888 template<> uint32_t __handleRceEte<TYPE_MBA>( ExtensibleChip * i_chip, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ) { #define PRDF_FUNC "[__handleRceEte] " uint32_t o_rc = SUCCESS; do { } while (0); return o_rc; #undef PRDF_FUNC } */ //------------------------------------------------------------------------------ template <TARGETING::TYPE T, typename D> uint32_t __checkEcc( ExtensibleChip * i_chip, TdQueue & io_queue, const MemAddr & i_addr, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ) { #define PRDF_FUNC "[__checkEcc] " PRDF_ASSERT( nullptr != i_chip ); PRDF_ASSERT( T == i_chip->getType() ); uint32_t o_rc = SUCCESS; o_errorsFound = false; TargetHandle_t trgt = i_chip->getTrgt(); HUID huid = i_chip->getHuid(); MemRank rank = i_addr.getRank(); do { // Check for ECC errors. uint32_t eccAttns = 0; o_rc = checkEccFirs<T>( i_chip, eccAttns ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "checkEccFirs<T>(0x%08x) failed", huid ); break; } if ( 0 != (eccAttns & MAINT_INT_NCE_ETE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintINTER_CTE); // Can't do any more isolation at this time. So add the rank to the // callout list. MemoryMru mm { trgt, rank, MemoryMruData::CALLOUT_RANK }; io_sc.service_data->SetCallout( mm ); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); } if ( 0 != (eccAttns & MAINT_SOFT_NCE_ETE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintSOFT_CTE ); // Can't do any more isolation at this time. So add the rank to the // callout list. MemoryMru mm { trgt, rank, MemoryMruData::CALLOUT_RANK }; io_sc.service_data->SetCallout( mm ); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); } if ( 0 != (eccAttns & MAINT_HARD_NCE_ETE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintHARD_CTE ); // Query the per-symbol counters for the hard CE symbol. MemUtils::MaintSymbols symData; MemSymbol junk; o_rc = MemUtils::collectCeStats<T>( i_chip, rank, symData, junk ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "MemUtils::collectCeStats(0x%08x,m%ds%d) " "failed", huid, rank.getMaster(), rank.getSlave() ); break; } // The command will have stopped on the first occurrence. So there // should only be one symbol in the list. PRDF_ASSERT( 1 == symData.size() ); // Add the symbol to the callout list. MemoryMru mm { trgt, rank, symData[0].symbol }; io_sc.service_data->SetCallout( mm ); // Any hard CEs in MNFG should be immediately reported. if ( mfgMode() ) io_sc.service_data->setServiceCall(); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); /* TODO RTC 136129 // Dynamically deallocation the page. o_rc = MemDealloc::page<T>( i_chip, i_addr ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "MemDealloc::page(0x%08x) failed", huid ); break; } */ } if ( 0 != (eccAttns & MAINT_MPE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintMPE ); // Add entry to UE table. D db = static_cast<D>(i_chip->getDataBundle()); db->iv_ueTable.addEntry( UE_TABLE::SCRUB_MPE, i_addr ); // Read the chip mark from markstore. MemMark chipMark; o_rc = MarkStore::readChipMark<T>( i_chip, rank, chipMark ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "readChipMark<T>(0x%08x,%d) failed", huid, rank.getMaster() ); break; } // If the chip mark is not valid, then somehow the chip mark was // placed on a rank other than the rank in which the command // stopped. This would most likely be a code bug. PRDF_ASSERT( chipMark.isValid() ); // Add the mark to the callout list. MemoryMru mm { trgt, rank, chipMark.getSymbol() }; io_sc.service_data->SetCallout( mm ); // Add a VCM procedure to the queue. TdEntry * e = new VcmEvent<T>{ i_chip, rank, chipMark }; io_queue.push( e ); } if ( 0 != (eccAttns & MAINT_RCE_ETE) ) { o_rc = __handleRceEte<T>( i_chip, o_errorsFound, io_sc ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "__handleRceEte<T>(0x%08x) failed", huid ); break; } } if ( 0 != (eccAttns & MAINT_UE) ) { o_errorsFound = true; io_sc.service_data->AddSignatureList( trgt, PRDFSIG_MaintUE ); // Since this will be a predictive callout, change the primary // signature as well. io_sc.service_data->setSignature( huid, PRDFSIG_MaintUE ); // Add entry to UE table. D db = static_cast<D>(i_chip->getDataBundle()); db->iv_ueTable.addEntry( UE_TABLE::SCRUB_UE, i_addr ); // Add the rank to the callout list. MemEcc::calloutMemUe<T>( i_chip, rank, io_sc ); // Make the error log predictive. io_sc.service_data->setServiceCall(); // Add a TPS procedure to the queue. TdEntry * e = new TpsEvent<T>{ i_chip, rank }; io_queue.push( e ); /* TODO RTC 136129 // Dynamically deallocation the rank. o_rc = MemDealloc::rank<T>( i_chip, rank ); if ( SUCCESS != o_rc ) { PRDF_ERR( PRDF_FUNC "MemDealloc::rank(0x%08x, m%ds%d) failed", huid, rank.getMaster(), rank.getSlave() ); break; } */ } } while (0); return o_rc; #undef PRDF_FUNC } template uint32_t __checkEcc<TYPE_MCA, McaDataBundle *>( ExtensibleChip * i_chip, TdQueue & io_queue, const MemAddr & i_addr, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ); /* TODO RTC 157888 template uint32_t __checkEcc<TYPE_MBA>( ExtensibleChip * i_chip, TdQueue & io_queue, const MemAddr & i_addr, bool & o_errorsFound, STEP_CODE_DATA_STRUCT & io_sc ); */ //------------------------------------------------------------------------------ template <TARGETING::TYPE T> void MemTdCtlr<T>::collectStateCaptureData( STEP_CODE_DATA_STRUCT & io_sc, const char * i_startEnd ) { #define PRDF_FUNC "[MemTdCtlr<T>::collectStateCaptureData] " // TODO RTC 167827 #undef PRDF_FUNC } //------------------------------------------------------------------------------ // Avoid linker errors with the template. template class MemTdCtlr<TYPE_MCBIST>; template class MemTdCtlr<TYPE_MBA>; //------------------------------------------------------------------------------ } // end namespace PRDF <|endoftext|>
<commit_before>/***************************************************************************** bamAncillary.cpp (c) 2009 - Aaron Quinlan Hall Laboratory Department of Biochemistry and Molecular Genetics University of Virginia aaronquinlan@gmail.com Licensed under the GNU General Public License 2.0 license. ******************************************************************************/ #include "BamAncillary.h" using namespace std; // 10 15 20 25 30 4000 // acccctttggacct---ataggga.................aaaa // acccc---ggaccttttataggga.................aaaa // 5M 3D 6M 2I 7M 20N 4M namespace BamTools { void getBamBlocks(const BamAlignment &bam, const RefVector &refs, vector<BED> &blocks, bool breakOnDeletionOps) { CHRPOS currPosition = bam.Position; CHRPOS blockStart = bam.Position; string chrom = refs.at(bam.RefID).RefName; string name = bam.Name; string strand = "+"; string score = ToString(bam.MapQuality); char prevOp = '\0'; if (bam.IsReverseStrand()) strand = "-"; bool blocksFound = false; vector<CigarOp>::const_iterator cigItr = bam.CigarData.begin(); vector<CigarOp>::const_iterator cigEnd = bam.CigarData.end(); for ( ; cigItr != cigEnd; ++cigItr ) { if (cigItr->Type == 'M') { currPosition += cigItr->Length; // we only want to create a new block if the current M op // was preceded by an N op or a D op (and we are breaking on D ops) if ((prevOp == 'D' && breakOnDeletionOps == true) || (prevOp == 'N')) { blocks.push_back( BED(chrom, blockStart, currPosition, name, score, strand) ); blockStart = currPosition; } } else if (cigItr->Type == 'D') { if (breakOnDeletionOps == false) currPosition += cigItr->Length; else { blocksFound = true; currPosition += cigItr->Length; blockStart = currPosition; } } else if (cigItr->Type == 'N') { blocks.push_back( BED(chrom, blockStart, currPosition, name, score, strand) ); blocksFound = true; currPosition += cigItr->Length; blockStart = currPosition; } else if (cigItr->Type == 'S' || cigItr->Type == 'H' || cigItr->Type == 'P' || cigItr->Type == 'I') { // do nothing } else { cerr << "Input error: invalid CIGAR type (" << cigItr->Type << ") for: " << bam.Name << endl; exit(1); } prevOp = cigItr->Type; } // if there were no splits, we just create a block representing the contiguous alignment. if (blocksFound == false) { blocks.push_back( BED(chrom, bam.Position, currPosition, name, score, strand) ); } } void MakeBedFromBam(const BamAlignment &bam, const string &chrom, const bedVector &blocks, BED &bed) { bed.chrom = chrom; bed.start = bam.Position; bed.end = bam.GetEndPosition(false, false); // build the name field from the BAM alignment. bed.name = bam.Name; if (bam.IsFirstMate()) bed.name += "/1"; else if (bam.IsSecondMate()) bed.name += "/2"; bed.score = ToString(bam.MapQuality); bed.strand = "+"; if (bam.IsReverseStrand()) bed.strand = "-"; bed.fields.push_back(bed.chrom); bed.fields.push_back(ToString(bed.start)); bed.fields.push_back(ToString(bed.end)); bed.fields.push_back(bed.name); bed.fields.push_back(bed.score); bed.fields.push_back(bed.strand); bed.fields.push_back(ToString(bam.Position)); bed.fields.push_back(ToString(bed.end)); bed.fields.push_back("0,0,0"); bed.fields.push_back(ToString(blocks.size())); ostringstream block_lengths, block_starts; for (size_t i = 0; i < blocks.size(); ++i) { block_lengths << blocks[i].end - blocks[i].start << ","; block_starts << blocks[i].start - bam.Position << ","; } bed.fields.push_back(block_lengths.str()); bed.fields.push_back(block_starts.str()); // identify which indices relate to the "other" // (i,e. non-BED6) fields for (size_t i = 5; i <= 11; ++i) bed.other_idxs.push_back(i); } } <commit_msg>remove additional strand from intersect -bed -abam<commit_after>/***************************************************************************** bamAncillary.cpp (c) 2009 - Aaron Quinlan Hall Laboratory Department of Biochemistry and Molecular Genetics University of Virginia aaronquinlan@gmail.com Licensed under the GNU General Public License 2.0 license. ******************************************************************************/ #include "BamAncillary.h" using namespace std; // 10 15 20 25 30 4000 // acccctttggacct---ataggga.................aaaa // acccc---ggaccttttataggga.................aaaa // 5M 3D 6M 2I 7M 20N 4M namespace BamTools { void getBamBlocks(const BamAlignment &bam, const RefVector &refs, vector<BED> &blocks, bool breakOnDeletionOps) { CHRPOS currPosition = bam.Position; CHRPOS blockStart = bam.Position; string chrom = refs.at(bam.RefID).RefName; string name = bam.Name; string strand = "+"; string score = ToString(bam.MapQuality); char prevOp = '\0'; if (bam.IsReverseStrand()) strand = "-"; bool blocksFound = false; vector<CigarOp>::const_iterator cigItr = bam.CigarData.begin(); vector<CigarOp>::const_iterator cigEnd = bam.CigarData.end(); for ( ; cigItr != cigEnd; ++cigItr ) { if (cigItr->Type == 'M') { currPosition += cigItr->Length; // we only want to create a new block if the current M op // was preceded by an N op or a D op (and we are breaking on D ops) if ((prevOp == 'D' && breakOnDeletionOps == true) || (prevOp == 'N')) { blocks.push_back( BED(chrom, blockStart, currPosition, name, score, strand) ); blockStart = currPosition; } } else if (cigItr->Type == 'D') { if (breakOnDeletionOps == false) currPosition += cigItr->Length; else { blocksFound = true; currPosition += cigItr->Length; blockStart = currPosition; } } else if (cigItr->Type == 'N') { blocks.push_back( BED(chrom, blockStart, currPosition, name, score, strand) ); blocksFound = true; currPosition += cigItr->Length; blockStart = currPosition; } else if (cigItr->Type == 'S' || cigItr->Type == 'H' || cigItr->Type == 'P' || cigItr->Type == 'I') { // do nothing } else { cerr << "Input error: invalid CIGAR type (" << cigItr->Type << ") for: " << bam.Name << endl; exit(1); } prevOp = cigItr->Type; } // if there were no splits, we just create a block representing the contiguous alignment. if (blocksFound == false) { blocks.push_back( BED(chrom, bam.Position, currPosition, name, score, strand) ); } } void MakeBedFromBam(const BamAlignment &bam, const string &chrom, const bedVector &blocks, BED &bed) { bed.chrom = chrom; bed.start = bam.Position; bed.end = bam.GetEndPosition(false, false); // build the name field from the BAM alignment. bed.name = bam.Name; if (bam.IsFirstMate()) bed.name += "/1"; else if (bam.IsSecondMate()) bed.name += "/2"; bed.score = ToString(bam.MapQuality); bed.strand = "+"; if (bam.IsReverseStrand()) bed.strand = "-"; bed.fields.push_back(bed.chrom); bed.fields.push_back(ToString(bed.start)); bed.fields.push_back(ToString(bed.end)); bed.fields.push_back(bed.name); bed.fields.push_back(bed.score); bed.fields.push_back(bed.strand); bed.fields.push_back(ToString(bam.Position)); bed.fields.push_back(ToString(bed.end)); bed.fields.push_back("0,0,0"); bed.fields.push_back(ToString(blocks.size())); ostringstream block_lengths, block_starts; for (size_t i = 0; i < blocks.size(); ++i) { block_lengths << blocks[i].end - blocks[i].start << ","; block_starts << blocks[i].start - bam.Position << ","; } bed.fields.push_back(block_lengths.str()); bed.fields.push_back(block_starts.str()); // identify which indices relate to the "other" // (i,e. non-BED6) fields for (size_t i = 6; i <= 11; ++i) bed.other_idxs.push_back(i); } } <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "sysapi.h" /* ** Try to determine the swap space available on our own machine. The answer ** is in kilobytes. */ /* If for some reason, the call fails, then -1 is returned */ #if defined(WIN32) int sysapi_swap_space_raw() { MEMORYSTATUS status; sysapi_internal_reconfig(); GlobalMemoryStatus(&status); return (int) (status.dwAvailPageFile/1024L); } #elif defined(LINUX) int sysapi_swap_space_raw() { struct sysinfo si; double free_swap; sysapi_internal_reconfig(); if (sysinfo(&si) == -1) { dprintf(D_ALWAYS, "sysapi_swap_space_raw(): error: sysinfo(2) failed: %d(%s)", errno, strerror(errno)); return -1; } /* On Linux before 2.3.23, mem_unit was not present and the pad region of space in this structure appears to have been occupying was set to 0; units are bytes */ if (si.mem_unit == 0) { si.mem_unit = 1; } /* in B */ free_swap = (double)si.freeswap * (double)si.mem_unit + (double)si.totalram * (double)si.mem_unit; /* in KB */ free_swap /= 1024.0; if ((int)free_swap > INT_MAX) { return INT_MAX; } return (int)free_swap; } #elif defined(HPUX) /* here's the deal: Using any number in pst_getdynamic seems to be *way* to small for our purposes. Those silly writers of HPUX return 'free memory paging space' (a small region of physical system memory that can be used for paging if all other swap areas are full (aka "psuedo-swap")) in the pst_vm field returned in pstat_getdynamic. This number is wrong. What we *really* want is the sum of the free space in 'dev' (the swap device) and 'localfs' (any file system swapping set up). So.... I can use pstat_getswap for this. It returns a number of structures, one for each "swap pool". These structures will either be "Block Device Fields" or "File System Fields" (dev or localfs). I'll sum up their 'pss_nfpgs' fields, multiply by pagesize, and return. On the cae HPs, two swap spaces are returned, one of each type. The localfs 'nfpgs' field is 0 on cae machines. Grrr. Hopefully, it might work somewhere else. Who knows... For more information, see /usr/include/sys/pstat.h and the pstat and swapinfo manual pages. -Mike Yoder 9-28-98 */ #include <sys/pstat.h> int sysapi_swap_space_raw () { int pagesize; /* in kB */ double virt_mem_size = 0; /* the so-called virtual memory size we seek */ struct pst_static s; struct pst_swapinfo pss[10]; int count, i; int idx = 0; /* index within the context */ sysapi_internal_reconfig(); if (pstat_getstatic(&s, sizeof(s), (size_t)1, 0) != -1) { pagesize = s.page_size / 1024; /* it's right here.... */ } else { dprintf ( D_ALWAYS, "sysapi_swap_space_raw(): Error getting pagesize. Errno = %d\n",errno); return -1; } /* loop until count == 0, will occur when we've got 'em all */ while ((count = pstat_getswap(pss, sizeof(pss[0]), 10, idx)) > 0) { /* got 'count' entries. process them. */ for ( i = 0 ; i < count ; i++ ) { /* first ensure that it's enabled */ if ( (pss[i].pss_flags & 1) == 1 ) { /* now make sure it's a SW_BLOCK or FS_BLOCK*/ /* FS_BLOCK has always returned a 0 for pss_nfpgs on cae hpuxs. Grrr. It's here in case it works somewhere else. */ if (((pss[i].pss_flags & 2) == 2) || ((pss[i].pss_flags & 4) == 4)) { /* add free pages to total */ virt_mem_size += (double)pss[i].pss_nfpgs * (double)pagesize; } } } idx = pss[count-1].pss_idx+1; } if (count == -1) dprintf ( D_ALWAYS, "sysapi_swap_space_raw(): Error in pstat_getswap(). Errno = %d\n", errno ); /* under HP-UX, it is considered an error if virt_mem_size == 0 */ if ( virt_mem_size != 0 ) { if (virt_mem_size > INT_MAX) { return INT_MAX; } return (int)virt_mem_size; } else { /* Print an error */ dprintf ( D_ALWAYS, "sysapi_swapspace_raw(): Error virt_mem_size == 0.\n"); return -1; } } #elif defined(Solaris) #include <sys/types.h> #include <sys/stat.h> #include <sys/swap.h> /* ** Try to determine the swap space available on our own machine. The answer ** is in kilobytes. */ int sysapi_swap_space_raw() { struct anoninfo ai; double avail; int factor; sysapi_internal_reconfig(); factor = sysconf(_SC_PAGESIZE) >> 10; memset( &ai, 0, sizeof(ai) ); if( swapctl(SC_AINFO, &ai) >= 0 ) { avail = (double)(ai.ani_max - ai.ani_resv) * (double)factor; if (avail > INT_MAX) { return INT_MAX; } return (int)avail; } else { dprintf( D_FULLDEBUG, "swapctl call failed, errno = %d\n", errno ); return -1; } } #elif defined(Darwin) || defined(CONDOR_FREEBSD) #include <sys/sysctl.h> int sysapi_swap_space_raw() { int mib[2]; unsigned int usermem; size_t len; mib[0] = CTL_HW; mib[1] = HW_USERMEM; len = sizeof(usermem); sysctl(mib, 2, &usermem, &len, NULL, 0); return usermem / 1024; } #elif defined(AIX) int sysapi_swap_space_raw() { struct pginfo p; int ret; CLASS_SYMBOL cuat; struct CuAt paging_ent; struct CuAt *pret = NULL; unsigned long free_swap_space = 0; char buf[1024]; char *path = NULL; if (odm_initialize() < 0) { /* This is quite terrible if it happens */ dprintf(D_ALWAYS, "sysapi_swap_space_raw(): Could not initialize the ODM database: " "%d\n", odmerrno); return -1; } /* remember to free this memory just before I leave this function */ path = odm_set_path("/etc/objrepos"); if (path == (char*)-1) /* eewww */ { dprintf(D_ALWAYS, "sysapi_swap_space_raw(): Could not set class path! " "%d\n", odmerrno); return -1; } /* open up a predefined class symbol found in libcfg.a */ cuat = odm_open_class(CuAt_CLASS); if (cuat == NULL) { dprintf(D_ALWAYS, "sysapi_swap_space_raw(): Could not open CuAt! %d\n", odmerrno); if (odm_terminate() < 0) { dprintf(D_ALWAYS, "Could not terminate using the ODM database: " "%d\n", odmerrno); free(path); return -1; } free(path); return -1; } /* odm_get_list() is scary cause I can't tell if it is going to actually remove the entries from the ODM when it returns them to me or not. So I'm traversing the list in the safe way that I know how */ /* get me the objects that are paging devices */ pret = (struct CuAt *)odm_get_obj(cuat, "value='paging'", &paging_ent, ODM_FIRST); while(pret != NULL && (int)pret != -1) { memset(buf, 0, 1024); snprintf(buf, 1024, "%s/%s", "/dev", paging_ent.name); ret = swapqry(buf, &p); if (ret == -1) { /* XXX when non root, some swap partitions cannot be inspected, so skip them. */ pret = (struct CuAt *)odm_get_obj(cuat, NULL, &paging_ent, ODM_NEXT); continue; } free_swap_space += p.free; pret = (struct CuAt *)odm_get_obj(cuat, NULL, &paging_ent, ODM_NEXT); } if (odm_close_class(cuat) < 0) { dprintf(D_ALWAYS, "Could not close CuAt in the ODM database: %d\n", odmerrno); free(path); return -1; } if (odm_terminate() < 0) { dprintf(D_ALWAYS, "Could not terminate using the ODM database: %d\n", odmerrno); free(path); return -1; } free(path); /* the free_swap_space unit is in PAGESIZE blocks */ /* so convert it into bytes, and then convert it into KB units */ return (free_swap_space * PAGESIZE) / 1024; } #else #error "Please define: sysapi_swap_space_raw()" #endif /* !defined(WIN32) */ /* the cooked version of the function */ int sysapi_swap_space(void) { sysapi_internal_reconfig(); return sysapi_swap_space_raw(); } <commit_msg>Remove useless cast<commit_after>/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_debug.h" #include "sysapi.h" /* ** Try to determine the swap space available on our own machine. The answer ** is in kilobytes. */ /* If for some reason, the call fails, then -1 is returned */ #if defined(WIN32) int sysapi_swap_space_raw() { MEMORYSTATUS status; sysapi_internal_reconfig(); GlobalMemoryStatus(&status); return (int) (status.dwAvailPageFile/1024L); } #elif defined(LINUX) int sysapi_swap_space_raw() { struct sysinfo si; double free_swap; sysapi_internal_reconfig(); if (sysinfo(&si) == -1) { dprintf(D_ALWAYS, "sysapi_swap_space_raw(): error: sysinfo(2) failed: %d(%s)", errno, strerror(errno)); return -1; } /* On Linux before 2.3.23, mem_unit was not present and the pad region of space in this structure appears to have been occupying was set to 0; units are bytes */ if (si.mem_unit == 0) { si.mem_unit = 1; } /* in B */ free_swap = (double)si.freeswap * (double)si.mem_unit + (double)si.totalram * (double)si.mem_unit; /* in KB */ free_swap /= 1024.0; if (free_swap > INT_MAX) { return INT_MAX; } return (int)free_swap; } #elif defined(HPUX) /* here's the deal: Using any number in pst_getdynamic seems to be *way* to small for our purposes. Those silly writers of HPUX return 'free memory paging space' (a small region of physical system memory that can be used for paging if all other swap areas are full (aka "psuedo-swap")) in the pst_vm field returned in pstat_getdynamic. This number is wrong. What we *really* want is the sum of the free space in 'dev' (the swap device) and 'localfs' (any file system swapping set up). So.... I can use pstat_getswap for this. It returns a number of structures, one for each "swap pool". These structures will either be "Block Device Fields" or "File System Fields" (dev or localfs). I'll sum up their 'pss_nfpgs' fields, multiply by pagesize, and return. On the cae HPs, two swap spaces are returned, one of each type. The localfs 'nfpgs' field is 0 on cae machines. Grrr. Hopefully, it might work somewhere else. Who knows... For more information, see /usr/include/sys/pstat.h and the pstat and swapinfo manual pages. -Mike Yoder 9-28-98 */ #include <sys/pstat.h> int sysapi_swap_space_raw () { int pagesize; /* in kB */ double virt_mem_size = 0; /* the so-called virtual memory size we seek */ struct pst_static s; struct pst_swapinfo pss[10]; int count, i; int idx = 0; /* index within the context */ sysapi_internal_reconfig(); if (pstat_getstatic(&s, sizeof(s), (size_t)1, 0) != -1) { pagesize = s.page_size / 1024; /* it's right here.... */ } else { dprintf ( D_ALWAYS, "sysapi_swap_space_raw(): Error getting pagesize. Errno = %d\n",errno); return -1; } /* loop until count == 0, will occur when we've got 'em all */ while ((count = pstat_getswap(pss, sizeof(pss[0]), 10, idx)) > 0) { /* got 'count' entries. process them. */ for ( i = 0 ; i < count ; i++ ) { /* first ensure that it's enabled */ if ( (pss[i].pss_flags & 1) == 1 ) { /* now make sure it's a SW_BLOCK or FS_BLOCK*/ /* FS_BLOCK has always returned a 0 for pss_nfpgs on cae hpuxs. Grrr. It's here in case it works somewhere else. */ if (((pss[i].pss_flags & 2) == 2) || ((pss[i].pss_flags & 4) == 4)) { /* add free pages to total */ virt_mem_size += (double)pss[i].pss_nfpgs * (double)pagesize; } } } idx = pss[count-1].pss_idx+1; } if (count == -1) dprintf ( D_ALWAYS, "sysapi_swap_space_raw(): Error in pstat_getswap(). Errno = %d\n", errno ); /* under HP-UX, it is considered an error if virt_mem_size == 0 */ if ( virt_mem_size != 0 ) { if (virt_mem_size > INT_MAX) { return INT_MAX; } return (int)virt_mem_size; } else { /* Print an error */ dprintf ( D_ALWAYS, "sysapi_swapspace_raw(): Error virt_mem_size == 0.\n"); return -1; } } #elif defined(Solaris) #include <sys/types.h> #include <sys/stat.h> #include <sys/swap.h> /* ** Try to determine the swap space available on our own machine. The answer ** is in kilobytes. */ int sysapi_swap_space_raw() { struct anoninfo ai; double avail; int factor; sysapi_internal_reconfig(); factor = sysconf(_SC_PAGESIZE) >> 10; memset( &ai, 0, sizeof(ai) ); if( swapctl(SC_AINFO, &ai) >= 0 ) { avail = (double)(ai.ani_max - ai.ani_resv) * (double)factor; if (avail > INT_MAX) { return INT_MAX; } return (int)avail; } else { dprintf( D_FULLDEBUG, "swapctl call failed, errno = %d\n", errno ); return -1; } } #elif defined(Darwin) || defined(CONDOR_FREEBSD) #include <sys/sysctl.h> int sysapi_swap_space_raw() { int mib[2]; unsigned int usermem; size_t len; mib[0] = CTL_HW; mib[1] = HW_USERMEM; len = sizeof(usermem); sysctl(mib, 2, &usermem, &len, NULL, 0); return usermem / 1024; } #elif defined(AIX) int sysapi_swap_space_raw() { struct pginfo p; int ret; CLASS_SYMBOL cuat; struct CuAt paging_ent; struct CuAt *pret = NULL; unsigned long free_swap_space = 0; char buf[1024]; char *path = NULL; if (odm_initialize() < 0) { /* This is quite terrible if it happens */ dprintf(D_ALWAYS, "sysapi_swap_space_raw(): Could not initialize the ODM database: " "%d\n", odmerrno); return -1; } /* remember to free this memory just before I leave this function */ path = odm_set_path("/etc/objrepos"); if (path == (char*)-1) /* eewww */ { dprintf(D_ALWAYS, "sysapi_swap_space_raw(): Could not set class path! " "%d\n", odmerrno); return -1; } /* open up a predefined class symbol found in libcfg.a */ cuat = odm_open_class(CuAt_CLASS); if (cuat == NULL) { dprintf(D_ALWAYS, "sysapi_swap_space_raw(): Could not open CuAt! %d\n", odmerrno); if (odm_terminate() < 0) { dprintf(D_ALWAYS, "Could not terminate using the ODM database: " "%d\n", odmerrno); free(path); return -1; } free(path); return -1; } /* odm_get_list() is scary cause I can't tell if it is going to actually remove the entries from the ODM when it returns them to me or not. So I'm traversing the list in the safe way that I know how */ /* get me the objects that are paging devices */ pret = (struct CuAt *)odm_get_obj(cuat, "value='paging'", &paging_ent, ODM_FIRST); while(pret != NULL && (int)pret != -1) { memset(buf, 0, 1024); snprintf(buf, 1024, "%s/%s", "/dev", paging_ent.name); ret = swapqry(buf, &p); if (ret == -1) { /* XXX when non root, some swap partitions cannot be inspected, so skip them. */ pret = (struct CuAt *)odm_get_obj(cuat, NULL, &paging_ent, ODM_NEXT); continue; } free_swap_space += p.free; pret = (struct CuAt *)odm_get_obj(cuat, NULL, &paging_ent, ODM_NEXT); } if (odm_close_class(cuat) < 0) { dprintf(D_ALWAYS, "Could not close CuAt in the ODM database: %d\n", odmerrno); free(path); return -1; } if (odm_terminate() < 0) { dprintf(D_ALWAYS, "Could not terminate using the ODM database: %d\n", odmerrno); free(path); return -1; } free(path); /* the free_swap_space unit is in PAGESIZE blocks */ /* so convert it into bytes, and then convert it into KB units */ return (free_swap_space * PAGESIZE) / 1024; } #else #error "Please define: sysapi_swap_space_raw()" #endif /* !defined(WIN32) */ /* the cooked version of the function */ int sysapi_swap_space(void) { sysapi_internal_reconfig(); return sysapi_swap_space_raw(); } <|endoftext|>
<commit_before>#pragma once #include <metaSMT/frontend/Logic.hpp> using namespace metaSMT; using namespace metaSMT::solver; using namespace metaSMT::logic; namespace metaSMT { template<typename Context, typename Boolean> typename Context::result_type one_hot(Context &ctx, std::vector<Boolean> const &ps) { assert(ps.size() > 0 && "One hot encoding requires at least one input variable"); if (ps.size() == 1) { return evaluate(ctx, equal(ps[0], True)); } typename Context::result_type zero_rail = evaluate(ctx, ps[0]); typename Context::result_type one_rail = evaluate(ctx, Not(ps[0])); for (unsigned u = 1; u < ps.size() - 1; ++u) { zero_rail = evaluate(ctx, Ite(ps[u], one_rail, zero_rail)); one_rail = evaluate(ctx, Ite(ps[u], False, one_rail)); } return evaluate(ctx, Ite(ps[ps.size()-1], one_rail, zero_rail)); } template <typename Context, typename Boolean> typename Context::result_type cardinality_geq(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Greater equal cardinality constraint requires at least one input variable"); if (ps.size() < cardinality) { return evaluate(ctx, False); } if (ps.size() == cardinality) { typename Context::result_type res = evaluate(ctx, True); for (unsigned u = 0; u < ps.size(); ++u) res = evaluate(ctx, And(res, ps[u])); return res; } if (cardinality == 0) { return evaluate(ctx, True); } // Now: 0 <= cardinality < ps.size() unsigned const rail_size = cardinality; std::vector<typename Context::result_type> rails[2]; rails[0].resize(rail_size); rails[1].resize(rail_size); // Tableau algorithm - Iteratively calculate all elements for (unsigned v = 0; v < ps.size() - cardinality + 1; ++v) { for (unsigned u = 0; u < cardinality; ++u) { if (u == 0 && v == 0) { rails[0][0] = evaluate(ctx, ps[0]); } else if (u == 0) { rails[v%2][0] = evaluate(ctx, Ite(evaluate(ctx, ps[v]), True, rails[(v-1)%2][0])); } else if (v == 0) { rails[0][u] = evaluate(ctx, Ite(evaluate(ctx, ps[u]), rails[0][u-1], False)); } else { rails[v%2][u] = evaluate(ctx, Ite(ps[u+v], rails[v%2][u-1], rails[(v-1)%2][u])); } } } return rails[(ps.size() - cardinality) % 2][cardinality - 1]; } template <typename Context, typename Boolean> typename Context::result_type cardinality_lt(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Lower than cardinality constraint requires at least one input variable"); return evaluate(ctx, Not(cardinality_geq(ctx, ps, cardinality))); } template <typename Context, typename Boolean> typename Context::result_type cardinality_leq(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Lower equal cardinality constraint requires at least one input variable"); return evaluate(ctx, Not(cardinality_geq(ctx, ps, cardinality+1))); } template <typename Context, typename Boolean> typename Context::result_type cardinality_gt(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Greater than cardinality constraint requires at least one input variable"); return evaluate(ctx, Not(cardinality_leq(ctx, ps, cardinality))); } template <typename Context, typename Boolean> typename Context::result_type cardinality_eq(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Equality cardinality constraint requires at least one input variable"); return evaluate(ctx, And(cardinality_geq(ctx, ps, cardinality), cardinality_lt(ctx, ps, cardinality+1))); } } // metaSMT <commit_msg>generalized cardinality constraint: cardinality_any<commit_after>#pragma once #include <metaSMT/frontend/Logic.hpp> using namespace metaSMT; using namespace metaSMT::solver; using namespace metaSMT::logic; namespace metaSMT { template<typename Context, typename Boolean> typename Context::result_type one_hot(Context &ctx, std::vector<Boolean> const &ps) { assert(ps.size() > 0 && "One hot encoding requires at least one input variable"); if (ps.size() == 1) { return evaluate(ctx, equal(ps[0], True)); } typename Context::result_type zero_rail = evaluate(ctx, ps[0]); typename Context::result_type one_rail = evaluate(ctx, Not(ps[0])); for (unsigned u = 1; u < ps.size() - 1; ++u) { zero_rail = evaluate(ctx, Ite(ps[u], one_rail, zero_rail)); one_rail = evaluate(ctx, Ite(ps[u], False, one_rail)); } return evaluate(ctx, Ite(ps[ps.size()-1], one_rail, zero_rail)); } /** * Generalized cardinality constraint based on a construction using * Binary Decision Diagrams (BDD) by E'{e}n and S\"orensson [1] and * Bailleux et al. [2]. * * [1] N. E'{e}n and N. S\"orensson. Translating pseudo-boolean * constraints into SAT. In Journal on Satisfiability, Boolean * Modeling and Computation, volume 2, pages 1-26, 2006. * * [2] O. Bailleux, Y. Boufkhad, and O. Roussel, A Translation of * Pseudo-Boolean Constraints to SAT, Journal on Satisfiability, * Boolean Modeling and Computation, volume 2, pages 191-200, 2006. * * The tableau algorithm keeps only two rows of the tableau in * memory which we call ``rails''. * * The construction applies to all operator types (<, <=, =, >=, >). * An operator is selected by assigning values to the arguments lt, * eq, gt, e.g., the less equal operator corresponds to lt = True, * eq = True, gt = False. * * For instance, the constraint * * ps[0] + ps[1] + ps[2] + ps[3] <=> 3 with <=> in {<, >, =, <=, >=} * * corresponds to the following tableau * RAILS | 0 1 2 3 * | lt lt lt * ---------|------------------------ * 0 | eq ps[0] ps[1] ps[2] * 1 gt | ps[0] ps[1] ps[2] ps[3] * * From the bottom right node of the tableau a logic formula is * constructed using the ITE-operator where the left neighbor node * and the top neighbor node serve as the then and else part, * respectively. * * Moreover, notice that cells with entries lt and gt are not * explicitly saved in rails but are directly encoded when the * formula is created. * * Precondition: ps.size > 0 && cardinality > 0 && ps.size() > cardinality */ template <typename Context, typename Boolean, typename LT_Expr, typename EQ_Expr, typename GT_Expr> typename Context::result_type cardinality_any(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality, LT_Expr lt, EQ_Expr eq, GT_Expr gt) { assert(ps.size() > 0 && "Cardinality constraint requires at least one input variable"); assert(cardinality > 0 && "Unsatisfied precondition for tableau construction"); assert( ps.size() > cardinality ); unsigned const rail_size = cardinality+1; std::vector<typename Context::result_type> rails[2]; rails[0].resize(rail_size); rails[1].resize(rail_size); // Tableau algorithm - Iteratively calculate all elements for (unsigned v = 0; v < ps.size() - cardinality + 1; ++v) { for (unsigned u = 0; u < cardinality + 1; ++u) { if (u == 0 && v == 0) { rails[0][0] = evaluate(ctx, eq); } else if (u == 0) { rails[v%2][0] = evaluate(ctx, Ite(evaluate(ctx, ps[v-1]), gt, rails[(v-1)%2][0])); } else if (v == 0) { rails[0][u] = evaluate(ctx, Ite(evaluate(ctx, ps[u-1]), rails[0][u-1], lt)); } else { rails[v%2][u] = evaluate(ctx, Ite(ps[u+v-1], rails[v%2][u-1], rails[(v-1)%2][u])); } } } return rails[(ps.size() - cardinality)%2][cardinality]; } template <typename Context, typename Boolean> typename Context::result_type cardinality_eq(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Equality cardinality constraint requires at least one input variable"); if (cardinality == 0) { typename Context::result_type res = evaluate(ctx, True); for (unsigned u = 0; u < ps.size(); ++u) res = evaluate(ctx, And(res, Not(ps[u]))); return res; } if (ps.size() == cardinality) { typename Context::result_type res = evaluate(ctx, True); for (unsigned u = 0; u < ps.size(); ++u) res = evaluate(ctx, And(res, ps[u])); return res; } return cardinality_any(ctx, ps, cardinality, False, True, False); } template <typename Context, typename Boolean> typename Context::result_type cardinality_geq(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Greater equal cardinality constraint requires at least one input variable"); if (ps.size() < cardinality) { return evaluate(ctx, False); } if (cardinality == 0) { return evaluate(ctx, True); } if (ps.size() == cardinality) { typename Context::result_type res = evaluate(ctx, True); for (unsigned u = 0; u < ps.size(); ++u) res = evaluate(ctx, And(res, ps[u])); return res; } return cardinality_any(ctx, ps, cardinality, False, True, True); } template <typename Context, typename Boolean> typename Context::result_type cardinality_leq(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Lower equal cardinality constraint requires at least one input variable"); if (ps.size() < cardinality) { return evaluate(ctx, True); } if (ps.size() == cardinality) { return evaluate(ctx, True); } if (cardinality == 0) { typename Context::result_type res = evaluate(ctx, True); for (unsigned u = 0; u < ps.size(); ++u) res = evaluate(ctx, And(res, Not(ps[u]))); return res; } return cardinality_any(ctx, ps, cardinality, True, True, False); } template <typename Context, typename Boolean> typename Context::result_type cardinality_gt(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Greater than cardinality constraint requires at least one input variable"); return evaluate(ctx, Not(cardinality_leq(ctx, ps, cardinality))); } template <typename Context, typename Boolean> typename Context::result_type cardinality_lt(Context &ctx, std::vector<Boolean> const &ps, unsigned cardinality) { assert(ps.size() > 0 && "Lower than cardinality constraint requires at least one input variable"); return evaluate(ctx, Not(cardinality_geq(ctx, ps, cardinality))); } } // metaSMT <|endoftext|>
<commit_before>#include "TocFunction.h" TocFunction::TocFunction(CodeBlock* body) : Function("toc", NULL, body, NULL) { } TocFunction::~TocFunction() { } TreeNode::ClassType TocFunction::classType() const { return TreeNode::TOC_FUNCTION; } llvm::Value* TocFunction::generateCode() { llvm::BasicBlock *mainBB = llvm::BasicBlock::Create(IR::Context, "toc", IR::MainFunction); IR::Builder.SetInsertPoint(mainBB); return mainBB; } <commit_msg>Geração de código de toc() corrigida.<commit_after>#include "TocFunction.h" TocFunction::TocFunction(CodeBlock* body) : Function("toc", NULL, body, NULL) { } TocFunction::~TocFunction() { } TreeNode::ClassType TocFunction::classType() const { return TreeNode::TOC_FUNCTION; } llvm::Value* TocFunction::generateCode() { llvm::BasicBlock *mainBB = llvm::BasicBlock::Create(IR::Context, "toc", IR::MainFunction); IR::Builder.SetInsertPoint(mainBB); this->body->generateCode(); return mainBB; } <|endoftext|>
<commit_before> #include "nucleus/Config.h" #include "nucleus/Files/FilePath.h" #if OS(POSIX) #include <unistd.h> #endif namespace nu { #if OS(POSIX) FilePath getCurrentWorkingDirectory(Allocator* allocator) { char buf[PATH_MAX] = {0}; const char* result = ::getcwd(buf, PATH_MAX); return FilePath{String{result, String::npos, allocator}, allocator}; } #endif } // namespace nu <commit_msg>Add GetCurrentWorkingDirectory for Windows platform<commit_after> #include "nucleus/Config.h" #include "nucleus/Files/FilePath.h" #if OS(POSIX) #include <unistd.h> #elif OS(WIN) #include "nucleus/Win/WindowsMixin.h" #endif namespace nu { FilePath getCurrentWorkingDirectory(Allocator* allocator) { #if OS(POSIX) char buf[PATH_MAX] = {0}; const char* result = ::getcwd(buf, PATH_MAX); return FilePath{String{result, String::npos, allocator}, allocator}; #elif OS(WIN) char buf[MAX_PATH] = {0}; DWORD result = ::GetCurrentDirectoryA(MAX_PATH, buf); return FilePath{String{buf, static_cast<I32>(result), allocator}, allocator}; #endif } } // namespace nu <|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Request.h" #include "SkPictureRecorder.h" #include "SkPixelSerializer.h" #include "SkPM4fPriv.h" #include "picture_utils.h" using namespace sk_gpu_test; static int kDefaultWidth = 1920; static int kDefaultHeight = 1080; Request::Request(SkString rootUrl) : fUploadContext(nullptr) , fUrlDataManager(rootUrl) , fGPUEnabled(false) , fColorMode(0) { // create surface #if SK_SUPPORT_GPU GrContextOptions grContextOpts; fContextFactory = new GrContextFactory(grContextOpts); #else fContextFactory = nullptr; #endif } Request::~Request() { #if SK_SUPPORT_GPU if (fContextFactory) { delete fContextFactory; } #endif } SkBitmap* Request::getBitmapFromCanvas(SkCanvas* canvas) { SkBitmap* bmp = new SkBitmap(); bmp->setInfo(canvas->imageInfo()); if (!canvas->readPixels(bmp, 0, 0)) { fprintf(stderr, "Can't read pixels\n"); return nullptr; } return bmp; } SkData* Request::writeCanvasToPng(SkCanvas* canvas) { // capture pixels SkAutoTDelete<SkBitmap> bmp(this->getBitmapFromCanvas(canvas)); SkASSERT(bmp); // Convert to format suitable for PNG output sk_sp<SkData> encodedBitmap = sk_tools::encode_bitmap_for_png(*bmp); SkASSERT(encodedBitmap.get()); // write to png SkDynamicMemoryWStream buffer; SkDrawCommand::WritePNG((const png_bytep) encodedBitmap->writable_data(), bmp->width(), bmp->height(), buffer); return buffer.copyToData(); } SkCanvas* Request::getCanvas() { #if SK_SUPPORT_GPU GrContextFactory* factory = fContextFactory; GLTestContext* gl = factory->getContextInfo(GrContextFactory::kNativeGL_ContextType, GrContextFactory::kNone_ContextOptions).glContext(); gl->makeCurrent(); #endif SkASSERT(fDebugCanvas); // create the appropriate surface if necessary if (!fSurface) { this->enableGPU(fGPUEnabled); } SkCanvas* target = fSurface->getCanvas(); return target; } void Request::drawToCanvas(int n, int m) { SkCanvas* target = this->getCanvas(); fDebugCanvas->drawTo(target, n, m); } SkData* Request::drawToPng(int n, int m) { this->drawToCanvas(n, m); return writeCanvasToPng(this->getCanvas()); } SkData* Request::writeOutSkp() { // Playback into picture recorder SkIRect bounds = this->getBounds(); SkPictureRecorder recorder; SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(bounds.width()), SkIntToScalar(bounds.height())); fDebugCanvas->draw(canvas); sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture()); SkDynamicMemoryWStream outStream; SkAutoTUnref<SkPixelSerializer> serializer(SkImageEncoder::CreatePixelSerializer()); picture->serialize(&outStream, serializer); return outStream.copyToData(); } GrContext* Request::getContext() { #if SK_SUPPORT_GPU return fContextFactory->get(GrContextFactory::kNativeGL_ContextType, GrContextFactory::kNone_ContextOptions); #else return nullptr; #endif } SkIRect Request::getBounds() { SkIRect bounds; if (fPicture) { bounds = fPicture->cullRect().roundOut(); if (fGPUEnabled) { #if SK_SUPPORT_GPU int maxRTSize = this->getContext()->caps()->maxRenderTargetSize(); bounds = SkIRect::MakeWH(SkTMin(bounds.width(), maxRTSize), SkTMin(bounds.height(), maxRTSize)); #endif } } else { bounds = SkIRect::MakeWH(kDefaultWidth, kDefaultHeight); } // We clip to kDefaultWidth / kDefaultHeight for performance reasons // TODO make this configurable bounds = SkIRect::MakeWH(SkTMin(bounds.width(), kDefaultWidth), SkTMin(bounds.height(), kDefaultHeight)); return bounds; } namespace { struct ColorAndProfile { SkColorType fColorType; SkColorProfileType fProfileType; bool fGammaCorrect; }; ColorAndProfile ColorModes[] = { { kN32_SkColorType, kLinear_SkColorProfileType, false }, { kN32_SkColorType, kSRGB_SkColorProfileType, true }, { kRGBA_F16_SkColorType, kLinear_SkColorProfileType, true }, }; } SkSurface* Request::createCPUSurface() { SkIRect bounds = this->getBounds(); ColorAndProfile cap = ColorModes[fColorMode]; SkImageInfo info = SkImageInfo::Make(bounds.width(), bounds.height(), cap.fColorType, kPremul_SkAlphaType, cap.fProfileType); uint32_t flags = cap.fGammaCorrect ? SkSurfaceProps::kGammaCorrect_Flag : 0; SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType); return SkSurface::MakeRaster(info, &props).release(); } SkSurface* Request::createGPUSurface() { GrContext* context = this->getContext(); SkIRect bounds = this->getBounds(); ColorAndProfile cap = ColorModes[fColorMode]; SkImageInfo info = SkImageInfo::Make(bounds.width(), bounds.height(), cap.fColorType, kPremul_SkAlphaType, cap.fProfileType); uint32_t flags = cap.fGammaCorrect ? SkSurfaceProps::kGammaCorrect_Flag : 0; SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType); SkSurface* surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, 0, &props).release(); return surface; } bool Request::setColorMode(int mode) { fColorMode = mode; return enableGPU(fGPUEnabled); } bool Request::setSRGBMode(bool enable) { gTreatSkColorAsSRGB = enable; return true; } bool Request::enableGPU(bool enable) { if (enable) { SkSurface* surface = this->createGPUSurface(); if (surface) { fSurface.reset(surface); fGPUEnabled = true; // When we switch to GPU, there seems to be some mystery draws in the canvas. So we // draw once to flush the pipe // TODO understand what is actually happening here if (fDebugCanvas) { fDebugCanvas->drawTo(this->getCanvas(), this->getLastOp()); this->getCanvas()->flush(); } return true; } return false; } fSurface.reset(this->createCPUSurface()); fGPUEnabled = false; return true; } bool Request::initPictureFromStream(SkStream* stream) { // parse picture from stream fPicture = SkPicture::MakeFromStream(stream); if (!fPicture) { fprintf(stderr, "Could not create picture from stream.\n"); return false; } // reinitialize canvas with the new picture dimensions this->enableGPU(fGPUEnabled); // pour picture into debug canvas SkIRect bounds = this->getBounds(); fDebugCanvas.reset(new SkDebugCanvas(bounds.width(), bounds.height())); fDebugCanvas->drawPicture(fPicture); // for some reason we need to 'flush' the debug canvas by drawing all of the ops fDebugCanvas->drawTo(this->getCanvas(), this->getLastOp()); this->getCanvas()->flush(); return true; } SkData* Request::getJsonOps(int n) { SkCanvas* canvas = this->getCanvas(); Json::Value root = fDebugCanvas->toJSON(fUrlDataManager, n, canvas); root["mode"] = Json::Value(fGPUEnabled ? "gpu" : "cpu"); root["drawGpuBatchBounds"] = Json::Value(fDebugCanvas->getDrawGpuBatchBounds()); root["colorMode"] = Json::Value(fColorMode); root["srgbMode"] = Json::Value(gTreatSkColorAsSRGB); SkDynamicMemoryWStream stream; stream.writeText(Json::FastWriter().write(root).c_str()); return stream.copyToData(); } SkData* Request::getJsonBatchList(int n) { SkCanvas* canvas = this->getCanvas(); SkASSERT(fGPUEnabled); Json::Value result = fDebugCanvas->toJSONBatchList(n, canvas); SkDynamicMemoryWStream stream; stream.writeText(Json::FastWriter().write(result).c_str()); return stream.copyToData(); } SkData* Request::getJsonInfo(int n) { // drawTo SkAutoTUnref<SkSurface> surface(this->createCPUSurface()); SkCanvas* canvas = surface->getCanvas(); // TODO this is really slow and we should cache the matrix and clip fDebugCanvas->drawTo(canvas, n); // make some json SkMatrix vm = fDebugCanvas->getCurrentMatrix(); SkIRect clip = fDebugCanvas->getCurrentClip(); Json::Value info(Json::objectValue); info["ViewMatrix"] = SkDrawCommand::MakeJsonMatrix(vm); info["ClipRect"] = SkDrawCommand::MakeJsonIRect(clip); std::string json = Json::FastWriter().write(info); // We don't want the null terminator so strlen is correct return SkData::NewWithCopy(json.c_str(), strlen(json.c_str())); } SkColor Request::getPixel(int x, int y) { SkCanvas* canvas = this->getCanvas(); canvas->flush(); SkAutoTDelete<SkBitmap> bitmap(this->getBitmapFromCanvas(canvas)); SkASSERT(bitmap); // Convert to format suitable for inspection sk_sp<SkData> encodedBitmap = sk_tools::encode_bitmap_for_png(*bitmap); SkASSERT(encodedBitmap.get()); const uint8_t* start = encodedBitmap->bytes() + ((y * bitmap->width() + x) * 4); SkColor result = SkColorSetARGB(start[3], start[0], start[1], start[2]); return result; } <commit_msg>skiaserve no longer crashes when no X server is present GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2059263002<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Request.h" #include "SkPictureRecorder.h" #include "SkPixelSerializer.h" #include "SkPM4fPriv.h" #include "picture_utils.h" using namespace sk_gpu_test; static int kDefaultWidth = 1920; static int kDefaultHeight = 1080; Request::Request(SkString rootUrl) : fUploadContext(nullptr) , fUrlDataManager(rootUrl) , fGPUEnabled(false) , fColorMode(0) { // create surface #if SK_SUPPORT_GPU GrContextOptions grContextOpts; fContextFactory = new GrContextFactory(grContextOpts); #else fContextFactory = nullptr; #endif } Request::~Request() { #if SK_SUPPORT_GPU if (fContextFactory) { delete fContextFactory; } #endif } SkBitmap* Request::getBitmapFromCanvas(SkCanvas* canvas) { SkBitmap* bmp = new SkBitmap(); bmp->setInfo(canvas->imageInfo()); if (!canvas->readPixels(bmp, 0, 0)) { fprintf(stderr, "Can't read pixels\n"); return nullptr; } return bmp; } SkData* Request::writeCanvasToPng(SkCanvas* canvas) { // capture pixels SkAutoTDelete<SkBitmap> bmp(this->getBitmapFromCanvas(canvas)); SkASSERT(bmp); // Convert to format suitable for PNG output sk_sp<SkData> encodedBitmap = sk_tools::encode_bitmap_for_png(*bmp); SkASSERT(encodedBitmap.get()); // write to png SkDynamicMemoryWStream buffer; SkDrawCommand::WritePNG((const png_bytep) encodedBitmap->writable_data(), bmp->width(), bmp->height(), buffer); return buffer.copyToData(); } SkCanvas* Request::getCanvas() { #if SK_SUPPORT_GPU GrContextFactory* factory = fContextFactory; GLTestContext* gl = factory->getContextInfo(GrContextFactory::kNativeGL_ContextType, GrContextFactory::kNone_ContextOptions).glContext(); if (!gl) { gl = factory->getContextInfo(GrContextFactory::kMESA_ContextType, GrContextFactory::kNone_ContextOptions).glContext(); } if (gl) { gl->makeCurrent(); } #endif SkASSERT(fDebugCanvas); // create the appropriate surface if necessary if (!fSurface) { this->enableGPU(fGPUEnabled); } SkCanvas* target = fSurface->getCanvas(); return target; } void Request::drawToCanvas(int n, int m) { SkCanvas* target = this->getCanvas(); fDebugCanvas->drawTo(target, n, m); } SkData* Request::drawToPng(int n, int m) { this->drawToCanvas(n, m); return writeCanvasToPng(this->getCanvas()); } SkData* Request::writeOutSkp() { // Playback into picture recorder SkIRect bounds = this->getBounds(); SkPictureRecorder recorder; SkCanvas* canvas = recorder.beginRecording(SkIntToScalar(bounds.width()), SkIntToScalar(bounds.height())); fDebugCanvas->draw(canvas); sk_sp<SkPicture> picture(recorder.finishRecordingAsPicture()); SkDynamicMemoryWStream outStream; SkAutoTUnref<SkPixelSerializer> serializer(SkImageEncoder::CreatePixelSerializer()); picture->serialize(&outStream, serializer); return outStream.copyToData(); } GrContext* Request::getContext() { #if SK_SUPPORT_GPU GrContext* result = fContextFactory->get(GrContextFactory::kNativeGL_ContextType, GrContextFactory::kNone_ContextOptions); if (!result) { result = fContextFactory->get(GrContextFactory::kMESA_ContextType, GrContextFactory::kNone_ContextOptions); } return result; #else return nullptr; #endif } SkIRect Request::getBounds() { SkIRect bounds; if (fPicture) { bounds = fPicture->cullRect().roundOut(); if (fGPUEnabled) { #if SK_SUPPORT_GPU int maxRTSize = this->getContext()->caps()->maxRenderTargetSize(); bounds = SkIRect::MakeWH(SkTMin(bounds.width(), maxRTSize), SkTMin(bounds.height(), maxRTSize)); #endif } } else { bounds = SkIRect::MakeWH(kDefaultWidth, kDefaultHeight); } // We clip to kDefaultWidth / kDefaultHeight for performance reasons // TODO make this configurable bounds = SkIRect::MakeWH(SkTMin(bounds.width(), kDefaultWidth), SkTMin(bounds.height(), kDefaultHeight)); return bounds; } namespace { struct ColorAndProfile { SkColorType fColorType; SkColorProfileType fProfileType; bool fGammaCorrect; }; ColorAndProfile ColorModes[] = { { kN32_SkColorType, kLinear_SkColorProfileType, false }, { kN32_SkColorType, kSRGB_SkColorProfileType, true }, { kRGBA_F16_SkColorType, kLinear_SkColorProfileType, true }, }; } SkSurface* Request::createCPUSurface() { SkIRect bounds = this->getBounds(); ColorAndProfile cap = ColorModes[fColorMode]; SkImageInfo info = SkImageInfo::Make(bounds.width(), bounds.height(), cap.fColorType, kPremul_SkAlphaType, cap.fProfileType); uint32_t flags = cap.fGammaCorrect ? SkSurfaceProps::kGammaCorrect_Flag : 0; SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType); return SkSurface::MakeRaster(info, &props).release(); } SkSurface* Request::createGPUSurface() { GrContext* context = this->getContext(); SkIRect bounds = this->getBounds(); ColorAndProfile cap = ColorModes[fColorMode]; SkImageInfo info = SkImageInfo::Make(bounds.width(), bounds.height(), cap.fColorType, kPremul_SkAlphaType, cap.fProfileType); uint32_t flags = cap.fGammaCorrect ? SkSurfaceProps::kGammaCorrect_Flag : 0; SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType); SkSurface* surface = SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, 0, &props).release(); return surface; } bool Request::setColorMode(int mode) { fColorMode = mode; return enableGPU(fGPUEnabled); } bool Request::setSRGBMode(bool enable) { gTreatSkColorAsSRGB = enable; return true; } bool Request::enableGPU(bool enable) { if (enable) { SkSurface* surface = this->createGPUSurface(); if (surface) { fSurface.reset(surface); fGPUEnabled = true; // When we switch to GPU, there seems to be some mystery draws in the canvas. So we // draw once to flush the pipe // TODO understand what is actually happening here if (fDebugCanvas) { fDebugCanvas->drawTo(this->getCanvas(), this->getLastOp()); this->getCanvas()->flush(); } return true; } return false; } fSurface.reset(this->createCPUSurface()); fGPUEnabled = false; return true; } bool Request::initPictureFromStream(SkStream* stream) { // parse picture from stream fPicture = SkPicture::MakeFromStream(stream); if (!fPicture) { fprintf(stderr, "Could not create picture from stream.\n"); return false; } // reinitialize canvas with the new picture dimensions this->enableGPU(fGPUEnabled); // pour picture into debug canvas SkIRect bounds = this->getBounds(); fDebugCanvas.reset(new SkDebugCanvas(bounds.width(), bounds.height())); fDebugCanvas->drawPicture(fPicture); // for some reason we need to 'flush' the debug canvas by drawing all of the ops fDebugCanvas->drawTo(this->getCanvas(), this->getLastOp()); this->getCanvas()->flush(); return true; } SkData* Request::getJsonOps(int n) { SkCanvas* canvas = this->getCanvas(); Json::Value root = fDebugCanvas->toJSON(fUrlDataManager, n, canvas); root["mode"] = Json::Value(fGPUEnabled ? "gpu" : "cpu"); root["drawGpuBatchBounds"] = Json::Value(fDebugCanvas->getDrawGpuBatchBounds()); root["colorMode"] = Json::Value(fColorMode); root["srgbMode"] = Json::Value(gTreatSkColorAsSRGB); SkDynamicMemoryWStream stream; stream.writeText(Json::FastWriter().write(root).c_str()); return stream.copyToData(); } SkData* Request::getJsonBatchList(int n) { SkCanvas* canvas = this->getCanvas(); SkASSERT(fGPUEnabled); Json::Value result = fDebugCanvas->toJSONBatchList(n, canvas); SkDynamicMemoryWStream stream; stream.writeText(Json::FastWriter().write(result).c_str()); return stream.copyToData(); } SkData* Request::getJsonInfo(int n) { // drawTo SkAutoTUnref<SkSurface> surface(this->createCPUSurface()); SkCanvas* canvas = surface->getCanvas(); // TODO this is really slow and we should cache the matrix and clip fDebugCanvas->drawTo(canvas, n); // make some json SkMatrix vm = fDebugCanvas->getCurrentMatrix(); SkIRect clip = fDebugCanvas->getCurrentClip(); Json::Value info(Json::objectValue); info["ViewMatrix"] = SkDrawCommand::MakeJsonMatrix(vm); info["ClipRect"] = SkDrawCommand::MakeJsonIRect(clip); std::string json = Json::FastWriter().write(info); // We don't want the null terminator so strlen is correct return SkData::NewWithCopy(json.c_str(), strlen(json.c_str())); } SkColor Request::getPixel(int x, int y) { SkCanvas* canvas = this->getCanvas(); canvas->flush(); SkAutoTDelete<SkBitmap> bitmap(this->getBitmapFromCanvas(canvas)); SkASSERT(bitmap); // Convert to format suitable for inspection sk_sp<SkData> encodedBitmap = sk_tools::encode_bitmap_for_png(*bitmap); SkASSERT(encodedBitmap.get()); const uint8_t* start = encodedBitmap->bytes() + ((y * bitmap->width() + x) * 4); SkColor result = SkColorSetARGB(start[3], start[0], start[1], start[2]); return result; } <|endoftext|>
<commit_before>#ifndef _H_XML_NODE #define _H_XML_NODE #include <iostream> #include <list> #include <string> namespace Xml { class Element; /** * Defines the abstract class of a node for interface purpose */ class Node { public: /* * Gets all children nodes * * @return A list of all children nodes (obviously...) */ virtual std::list<Node *> childrenNodes() = 0; virtual std::list<Node const *> const childrenNodes() const = 0; /* * Implements standart stream operator */ virtual std::ostream & operator >> (std::ostream & stream) const = 0; /* * Destructor */ virtual ~Node() { } }; /* * Defines a sexier standart stream operator */ inline std::ostream & operator << (std::ostream & stream, Node const & node) { node >> stream; return stream; } } #endif //_H_XML_NODE <commit_msg>Removes forward declaration of Xml::Element in src/Xml/XmlNode.hpp<commit_after>#ifndef _H_XML_NODE #define _H_XML_NODE #include <iostream> #include <list> #include <string> namespace Xml { /** * Defines the abstract class of a node for interface purpose */ class Node { public: /* * Gets all children nodes * * @return A list of all children nodes (obviously...) */ virtual std::list<Node *> childrenNodes() = 0; virtual std::list<Node const *> const childrenNodes() const = 0; /* * Implements standart stream operator */ virtual std::ostream & operator >> (std::ostream & stream) const = 0; /* * Destructor */ virtual ~Node() { } }; /* * Defines a sexier standart stream operator */ inline std::ostream & operator << (std::ostream & stream, Node const & node) { node >> stream; return stream; } } #endif //_H_XML_NODE <|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "log.h" #include <string.h> #include <iostream> #include <iomanip> #include <string> #include <unordered_map> #include <vector> #ifdef MULTITHREAD #include <mutex> #endif // MULTITHREAD namespace Log { namespace Detail { int verbosity = 0; int maximumLogLevel = 0; // The time at which logging was initialized; used so that log messages can have // relative rather than absolute timestamps. static uint64_t initTime = 0; // The first level cache for fileLogLevel() - the most recent result returned. static const char* mostRecentFile = nullptr; static int mostRecentLevel = -1; // The second level cache for fileLogLevel(), mapping filenames to log levels. static std::unordered_map<const void*, int> logLevelCache; // All log levels manually specified by the user. static std::vector<std::string> debugSpecs; std::ostream& operator<<(std::ostream& out, const Log::Detail::OutputLogPrefix& pfx) { #ifdef CLOCK_MONOTONIC if (LOGGING(2)) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); uint64_t t = ts.tv_sec*1000000000UL + ts.tv_nsec - Log::Detail::initTime; t /= 1000000UL; // millisec out << t/1000 << '.' << std::setw(3) << std::setfill('0') << t%1000 << ':' << std::setfill(' '); } #endif if (LOGGING(1)) { const char *s = strrchr(pfx.fn, '/'); const char *e = strrchr(pfx.fn, '.'); s = s ? s + 1 : pfx.fn; if (e && e > s) out.write(s, e-s); else out << s; out << ':' << pfx.level << ':'; } return out; } static bool match(const char *pattern, const char *name) { const char *pend = pattern + strcspn(pattern, ",:"); const char *pbackup = 0; while (1) { while (pattern < pend && *pattern == *name) { pattern++; name++; } if (pattern == pend) { if (!strcmp(name, ".cpp")) return true; return *name == 0; } if (*pattern++ != '*') return false; if (pattern == pend) return true; while (*name && *name != *pattern) { if (pbackup && *name == *pbackup) { pattern = pbackup; break; } name++; } pbackup = pattern; } } int uncachedFileLogLevel(const char* file) { if (auto* startOfFilename = strrchr(file, '/')) file = startOfFilename + 1; for (auto& spec : debugSpecs) for (auto* pattern = spec.c_str(); pattern; pattern = strchr(pattern, ',')) { while (*pattern == ',') pattern++; if (match(pattern, file)) if (auto* level = strchr(pattern, ':')) return atoi(level + 1); } // If there's no matching spec, compute a default from the global verbosity level. return verbosity > 0 ? verbosity - 1 : 0; } int fileLogLevel(const char* file) { #ifdef MULTITHREAD static std::mutex lock; std::lock_guard<std::mutex> acquire(lock); #endif // There are two layers of caching here. First, we cache the most recent // result we returned, to minimize expensive lookups in tight loops. if (mostRecentFile == file) return mostRecentLevel; mostRecentFile = file; // Second, we look up @file in a hash table mapping from pointers to log // levels. We expect to hit in this cache virtually all the time. auto logLevelCacheIter = logLevelCache.find(file); if (logLevelCacheIter != logLevelCache.end()) return mostRecentLevel = logLevelCacheIter->second; // This is the slow path. We have to walk @debugSpecs to see if there are any // specs that match @file. mostRecentLevel = uncachedFileLogLevel(file); logLevelCache[file] = mostRecentLevel; return mostRecentLevel; } void invalidateCaches(int possibleNewMaxLogLevel) { mostRecentFile = nullptr; mostRecentLevel = 0; logLevelCache.clear(); maximumLogLevel = std::max(maximumLogLevel, possibleNewMaxLogLevel); } } // namespace Detail void addDebugSpec(const char* spec) { #ifdef CLOCK_MONOTONIC if (!Detail::initTime) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); Detail::initTime = ts.tv_sec*1000000000UL + ts.tv_nsec; } #endif // Validate @spec. bool ok = false; long maxLogLevelInSpec = 0; for (auto* pattern = strchr(spec, ':'); pattern; pattern = strchr(pattern, ':')) { ok = true; long level = strtol(pattern + 1, const_cast<char**>(&pattern), 10); if (*pattern && *pattern != ',') { ok = false; break; } maxLogLevelInSpec = std::max(maxLogLevelInSpec, level); } if (!ok) { std::cerr << "Invalid debug trace spec '" << spec << "'" << std::endl; return; } #ifdef MULTITHREAD static std::mutex lock; std::lock_guard<std::mutex> acquire(lock); #endif Detail::debugSpecs.push_back(spec); Detail::invalidateCaches(maxLogLevelInSpec); } void increaseVerbosity() { #ifdef MULTITHREAD static std::mutex lock; std::lock_guard<std::mutex> acquire(lock); #endif Detail::verbosity++; Detail::invalidateCaches(Detail::verbosity - 1); } } // namespace Log <commit_msg>Clean up and fix log metalogging<commit_after>/* Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "log.h" #include <string.h> #include <iostream> #include <iomanip> #include <string> #include <unordered_map> #include <vector> #ifdef MULTITHREAD #include <mutex> #endif // MULTITHREAD namespace Log { namespace Detail { int verbosity = 0; int maximumLogLevel = 0; // The time at which logging was initialized; used so that log messages can have // relative rather than absolute timestamps. static uint64_t initTime = 0; // The first level cache for fileLogLevel() - the most recent result returned. static const char* mostRecentFile = nullptr; static int mostRecentLevel = -1; // The second level cache for fileLogLevel(), mapping filenames to log levels. static std::unordered_map<const void*, int> logLevelCache; // All log levels manually specified by the user. static std::vector<std::string> debugSpecs; std::ostream& operator<<(std::ostream& out, const Log::Detail::OutputLogPrefix& pfx) { #ifdef CLOCK_MONOTONIC if (LOGGING(2)) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); uint64_t t = ts.tv_sec*1000000000UL + ts.tv_nsec - Log::Detail::initTime; t /= 1000000UL; // millisec out << t/1000 << '.' << std::setw(3) << std::setfill('0') << t%1000 << ':' << std::setfill(' '); } #endif if (LOGGING(1)) { const char *s = strrchr(pfx.fn, '/'); const char *e = strrchr(pfx.fn, '.'); s = s ? s + 1 : pfx.fn; if (e && e > s) out.write(s, e-s); else out << s; out << ':' << pfx.level << ':'; } return out; } static bool match(const char *pattern, const char *name) { const char *pend = pattern + strcspn(pattern, ",:"); const char *pbackup = 0; while (1) { while (pattern < pend && *pattern == *name) { pattern++; name++; } if (pattern == pend) { if (!strcmp(name, ".cpp")) return true; return *name == 0; } if (*pattern++ != '*') return false; if (pattern == pend) return true; while (*name && *name != *pattern) { if (pbackup && *name == *pbackup) { pattern = pbackup; break; } name++; } pbackup = pattern; } } int uncachedFileLogLevel(const char* file) { if (auto* startOfFilename = strrchr(file, '/')) file = startOfFilename + 1; for (auto& spec : debugSpecs) for (auto* pattern = spec.c_str(); pattern; pattern = strchr(pattern, ',')) { while (*pattern == ',') pattern++; if (match(pattern, file)) if (auto* level = strchr(pattern, ':')) return atoi(level + 1); } // If there's no matching spec, compute a default from the global verbosity level, // except for THIS file if (!strcmp(file, "log.cpp")) return 0; return verbosity > 0 ? verbosity - 1 : 0; } int fileLogLevel(const char* file) { #ifdef MULTITHREAD static std::mutex lock; std::lock_guard<std::mutex> acquire(lock); #endif // There are two layers of caching here. First, we cache the most recent // result we returned, to minimize expensive lookups in tight loops. if (mostRecentFile == file) return mostRecentLevel; mostRecentFile = file; // Second, we look up @file in a hash table mapping from pointers to log // levels. We expect to hit in this cache virtually all the time. auto logLevelCacheIter = logLevelCache.find(file); if (logLevelCacheIter != logLevelCache.end()) return mostRecentLevel = logLevelCacheIter->second; // This is the slow path. We have to walk @debugSpecs to see if there are any // specs that match @file. mostRecentLevel = uncachedFileLogLevel(file); logLevelCache[file] = mostRecentLevel; return mostRecentLevel; } void invalidateCaches(int possibleNewMaxLogLevel) { mostRecentFile = nullptr; mostRecentLevel = 0; logLevelCache.clear(); maximumLogLevel = std::max(maximumLogLevel, possibleNewMaxLogLevel); } } // namespace Detail void addDebugSpec(const char* spec) { #ifdef CLOCK_MONOTONIC if (!Detail::initTime) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); Detail::initTime = ts.tv_sec*1000000000UL + ts.tv_nsec; } #endif // Validate @spec. bool ok = false; long maxLogLevelInSpec = 0; for (auto* pattern = strchr(spec, ':'); pattern; pattern = strchr(pattern, ':')) { ok = true; long level = strtol(pattern + 1, const_cast<char**>(&pattern), 10); if (*pattern && *pattern != ',') { ok = false; break; } maxLogLevelInSpec = std::max(maxLogLevelInSpec, level); } if (!ok) { std::cerr << "Invalid debug trace spec '" << spec << "'" << std::endl; return; } #ifdef MULTITHREAD static std::mutex lock; std::lock_guard<std::mutex> acquire(lock); #endif Detail::debugSpecs.push_back(spec); Detail::invalidateCaches(maxLogLevelInSpec); } void increaseVerbosity() { #ifdef MULTITHREAD static std::mutex lock; std::lock_guard<std::mutex> acquire(lock); #endif #ifdef CLOCK_MONOTONIC if (!Detail::initTime) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); Detail::initTime = ts.tv_sec*1000000000UL + ts.tv_nsec; } #endif Detail::verbosity++; Detail::invalidateCaches(Detail::verbosity - 1); } } // namespace Log <|endoftext|>
<commit_before>/* * CliqueConn.cpp * * Created on: Sep 8, 2011 * Author: gkenyon */ #include "CliqueConn.hpp" int pvpatch_update_clique(int nk, float* RESTRICT v, float a, float* RESTRICT w); int pvpatch_update_clique2(int nk, float* RESTRICT v, float a, float* RESTRICT w, float* RESTRICT m); namespace PV { CliqueConn::CliqueConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename, InitWeights *weightInit) { CliqueConn::initialize_base(); CliqueConn::initialize(name, hc, pre, post, channel, filename, weightInit); }; int CliqueConn::initialize_base(){ cliqueSize = 1; KernelConn::initialize_base(); return PV_SUCCESS; } int CliqueConn::initialize(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename, InitWeights *weightInit){ KernelConn::initialize(name, hc, pre, post, channel, filename, weightInit); PVParams * params = parent->parameters(); cliqueSize = params->value(name, "cliqueSize", 1, true); return PV_SUCCESS; } int CliqueConn::updateState(float time, float dt) { int status = KernelConn::updateState(time, dt); assert(status == PV_SUCCESS); return PV_SUCCESS; }; int CliqueConn::update_dW(int arborId) { const PVLayerLoc * preLoc = this->getPre()->getLayerLoc(); const int nfPre = preLoc->nf; //const int nxPre = preLoc->nx; //const int nyPre = preLoc->ny; const int nxPreExt = preLoc->nx + 2 * preLoc->nb; const int nyPreExt = preLoc->ny + 2 * preLoc->nb; int syPostExt = post->getLayerLoc()->nf * (post->getLayerLoc()->nx + 2 * post->getLayerLoc()->nb); // compute just once // if pre and post are the same layers, make a clone of size PVPatch to hold temporary activity values // in order to eliminate generalize self-interactions bool self_flag = this->getPre() == this->getPost(); pvdata_t * a_post_mask = NULL; const int a_post_size = nfp * nxp * nyp; a_post_mask = (pvdata_t *) calloc(a_post_size, sizeof(pvdata_t)); assert(a_post_mask != NULL); // get linear index of cell at center of patch for self_flag == true const int k_post_self = (int) (a_post_size / 2); // if self_flag == true, a_post_size should be odd int delay = getDelay(arborId); // gather active indices in extended layer // hard to pre-compute at HyPerLayer level because of variable delays int numActiveExt = 0; unsigned int * activeExt = (unsigned int *) calloc(this->getPre()->getNumExtended(), sizeof(int)); assert(activeExt != NULL); const pvdata_t * aPre = this->getPre()->getLayerData(delay); for (int kPreExt = 0; kPreExt < this->getPre()->getNumExtended(); kPreExt++) { if (aPre[kPreExt] == 0) continue; activeExt[numActiveExt++] = kPreExt; } // calc dimensions of wPostPatch // TODO: following is copied from calculation of wPostPatches and should be pre-calculated and stored there in HyPerConn::wPostPatches // TODO: following should be implemented as HyPerConn::calcPostPatchSize //const PVLayer * lPre = clayer; const float xScaleDiff = this->getPost()->getXScale() - this->getPre()->getXScale(); const float yScaleDiff = this->getPost()->getYScale() - this->getPre()->getYScale(); const float powXScale = pow(2.0f, (float) xScaleDiff); const float powYScale = pow(2.0f, (float) yScaleDiff); //const int prePad = lPre->loc.nb; const int nxPostPatch = (int) (this->xPatchSize() * powXScale); // TODO: store in HyPerConn::wPostPatches const int nyPostPatch = (int) (this->yPatchSize() * powYScale); // TODO: store in HyPerConn::wPostPatches //const int nfPostPatch = nf; // clique dimensions // a new set of cliques is centered on each pre-synaptic cell with radius nzPostPatch/2 // TODO: precompute clique dimensions during CliqueConn::initialize int nyCliqueRadius = (int) (nyPostPatch / 2); int nxCliqueRadius = (int) (nxPostPatch / 2); int cliquePatchSize = (2 * nxCliqueRadius + 1) * (2 * nyCliqueRadius + 1) * nfPre; //int numKernels = conn->numDataPatches(); // per arbor? int numCliques = pow(cliquePatchSize, cliqueSize - 1); assert(numCliques == this->numberOfAxonalArborLists()); // loop over all products of cliqueSize active presynaptic cells // outer loop is over presynaptic cells, each of which defines the center of a cliquePatch // inner loop is over all combinations of clique cells within cliquePatch boundaries, which may be shrunken // TODO: pre-allocate cliqueActiveIndices as CliqueConn::cliquePatchSize member variable int * cliqueActiveIndices = (int *) calloc(cliquePatchSize, sizeof(int)); assert(cliqueActiveIndices != NULL); for (int kPreActive = 0; kPreActive < numActiveExt; kPreActive++) { int kPreExt = activeExt[kPreActive]; // get indices of active elements in clique radius // watch out for shrunken patches! int numActiveElements = 0; int kxPreExt = kxPos(kPreExt, nxPreExt, nyPreExt, nfPre); int kyPreExt = kyPos(kPreExt, nxPreExt, nyPreExt, nfPre); if (cliqueSize > 1) { for (int kyCliqueExt = ((kyPreExt - nyCliqueRadius) > 0 ? (kyPreExt - nyCliqueRadius) : 0); kyCliqueExt < ((kyPreExt + nyCliqueRadius) <= nyPreExt ? (kyPreExt + nyCliqueRadius) : nyPreExt); kyCliqueExt++) { //if (kyCliqueExt < 0 || kyCliqueExt > nyPreExt) continue; for (int kxCliqueExt = ((kxPreExt - nxCliqueRadius) > 0 ? (kxPreExt - nxCliqueRadius) : 0); kxCliqueExt < ((kxPreExt + nxCliqueRadius) <= nxPreExt ? (kxPreExt + nxCliqueRadius) : nxPreExt); kxCliqueExt++) { //if (kyCliqueExt < 0 || kyCliqueExt > nxPreExt) continue; for (int kfCliqueExt = 0; kfCliqueExt < nfPre; kfCliqueExt++) { int kCliqueExt = kIndex(kxCliqueExt, kyCliqueExt, kfCliqueExt, nxPreExt, nyPreExt, nfPre); if ((aPre[kCliqueExt] == 0) || (kCliqueExt == kPreExt)) continue; cliqueActiveIndices[numActiveElements++] = kCliqueExt; } } } } // cliqueSize > 1 else { cliqueActiveIndices[numActiveElements++] = kPreExt; // each cell is its own clique if cliqueSize == 1 } if (numActiveElements < (cliqueSize-1)) continue; // loop over all active combinations of size=cliqueSize-1 in clique radius int numActiveCliques = pow(numActiveElements, cliqueSize - 1); for (int kClique = 0; kClique < numActiveCliques; kClique++) { //initialize a_post_tmp if (self_flag) { // otherwise, a_post_mask is not modified and thus doesn't have to be updated for (int k_post = 0; k_post < a_post_size; k_post++) { a_post_mask[k_post] = 1; } a_post_mask[k_post_self] = 0; } // decompose kClique to compute product of active clique elements int arborNdx = 0; pvdata_t cliqueProd = aPre[kPreExt]; int kResidue = kClique; int maxIndex = -1; for (int iProd = 0; iProd < cliqueSize - 1; iProd++) { int kPatchActive = (unsigned int) (kResidue / pow(numActiveElements, cliqueSize - 1 - iProd - 1)); // only apply each permutation of clique elements once, no element can contribute more than once if (kPatchActive <= maxIndex) { break; } else { maxIndex = kPatchActive; } int kCliqueExt = cliqueActiveIndices[kPatchActive]; cliqueProd *= aPre[kCliqueExt]; kResidue = kResidue - kPatchActive * pow(numActiveElements, cliqueSize - 1 - iProd - 1); // compute arborIndex for this clique element int kxCliqueExt = kxPos(kCliqueExt, nxPreExt, nyPreExt, nfPre); int kyCliqueExt = kyPos(kCliqueExt, nxPreExt, nyPreExt, nfPre); int kfClique = featureIndex(kCliqueExt, nxPreExt, nyPreExt, nfPre); int kxPatch = kxCliqueExt - kxPreExt + nxCliqueRadius; int kyPatch = kyCliqueExt - kyPreExt + nyCliqueRadius; unsigned int kArbor = kIndex(kxPatch, kyPatch, kfClique, (2 * nxCliqueRadius + 1), (2*nyCliqueRadius + 1), nfPre); arborNdx += kArbor * pow(cliquePatchSize, cliqueSize - 1 - iProd - 1); if ((arborNdx < 0) || (arborNdx >= numCliques)){ assert((arborNdx >= 0) && (arborNdx < numCliques)); } // remove self-interactions if pre == post if (self_flag){ a_post_mask[kArbor] = 0; } } // iProd // receive weights input from clique (mostly copied from superclass method) // PVAxonalArbor * arbor = this->axonalArbor(kPreExt, arborNdx); PVPatch * dWPatch = dwPatches[arborNdx][kPreExt]; // arbor->plasticIncr; size_t postOffset = getAPostOffset(kPreExt, arborNdx); const float * aPost = &post->getLayerData()[postOffset]; const pvdata_t * dWStart = this->getPIncrDataStart(arborNdx); int kernelIndex = this->patchIndexToKernelIndex(kPreExt); const pvdata_t * dW_head = &(dWStart[a_post_size*kernelIndex]); size_t dW_offset = dWPatch->data - dW_head; // WARNING - assumes weight and GSyn patches from task same size // - assumes patch stride sf is 1 int nkPatch = nfp * dWPatch->nx; int nyPatch = dWPatch->ny; int syPatch = syp; // TODO - unroll for (int y = 0; y < nyPatch; y++) { pvpatch_update_clique2( nkPatch, (float *) (dWPatch->data + y * syPatch), cliqueProd, (float *) (aPost + y*syPostExt), (float *) (a_post_mask + dW_offset + y * syPatch)); } } // kClique } // kPreActive free(cliqueActiveIndices); free(activeExt); free(a_post_mask); return PV_BREAK; } ; // calc_dW int CliqueConn::updateWeights(int arborId) { int status = KernelConn::updateWeights(arborId); assert((status == PV_SUCCESS) || (status == PV_BREAK)); return PV_BREAK; } ; // updateWeights /* int CliqueConn::normalizeWeights(PVPatch ** patches, int numPatches, int arborId){ return PV_CONTINUE;}; */ }// namespace PV int pvpatch_update_clique(int nk, float* RESTRICT dW, float aPre, float* RESTRICT aPost) { int k; int err = 0; for (k = 0; k < nk; k++) { dW[k] += aPre * aPost[k]; } return err; } int pvpatch_update_clique2(int nk, float* RESTRICT dW, float aPre, float* RESTRICT aPost, float* RESTRICT a_mask) { int k; int err = 0; for (k = 0; k < nk; k++) { dW[k] += aPre * aPost[k] * a_mask[k]; } return err; } <commit_msg>added code to eliminate generalized self interactions in the rcvSynapticInput method<commit_after>/* * CliqueConn.cpp * * Created on: Sep 8, 2011 * Author: gkenyon */ #include "CliqueConn.hpp" int pvpatch_update_clique(int nk, float* RESTRICT v, float a, float* RESTRICT w); int pvpatch_update_clique2(int nk, float* RESTRICT v, float a, float* RESTRICT w, float* RESTRICT m); namespace PV { CliqueConn::CliqueConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename, InitWeights *weightInit) { CliqueConn::initialize_base(); CliqueConn::initialize(name, hc, pre, post, channel, filename, weightInit); }; int CliqueConn::initialize_base(){ cliqueSize = 1; KernelConn::initialize_base(); return PV_SUCCESS; } int CliqueConn::initialize(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename, InitWeights *weightInit){ KernelConn::initialize(name, hc, pre, post, channel, filename, weightInit); PVParams * params = parent->parameters(); cliqueSize = params->value(name, "cliqueSize", 1, true); return PV_SUCCESS; } int CliqueConn::updateState(float time, float dt) { int status = KernelConn::updateState(time, dt); assert(status == PV_SUCCESS); return PV_SUCCESS; }; int CliqueConn::update_dW(int arborId) { const PVLayerLoc * preLoc = this->getPre()->getLayerLoc(); const int nfPre = preLoc->nf; //const int nxPre = preLoc->nx; //const int nyPre = preLoc->ny; const int nxPreExt = preLoc->nx + 2 * preLoc->nb; const int nyPreExt = preLoc->ny + 2 * preLoc->nb; int syPostExt = post->getLayerLoc()->nf * (post->getLayerLoc()->nx + 2 * post->getLayerLoc()->nb); // compute just once // if pre and post are the same layers, make a clone of size PVPatch to hold temporary activity values // in order to eliminate generalize self-interactions bool self_flag = this->getPre() == this->getPost(); pvdata_t * a_post_mask = NULL; const int a_post_size = nfp * nxp * nyp; a_post_mask = (pvdata_t *) calloc(a_post_size, sizeof(pvdata_t)); assert(a_post_mask != NULL); // get linear index of cell at center of patch for self_flag == true const int k_post_self = (int) (a_post_size / 2); // if self_flag == true, a_post_size should be odd for (int k_post = 0; k_post < a_post_size; k_post++) { a_post_mask[k_post] = 1; } int delay = getDelay(arborId); // gather active indices in extended layer // hard to pre-compute at HyPerLayer level because of variable delays int numActiveExt = 0; unsigned int * activeExt = (unsigned int *) calloc(this->getPre()->getNumExtended(), sizeof(int)); assert(activeExt != NULL); const pvdata_t * aPre = this->getPre()->getLayerData(delay); for (int kPreExt = 0; kPreExt < this->getPre()->getNumExtended(); kPreExt++) { if (aPre[kPreExt] == 0) continue; activeExt[numActiveExt++] = kPreExt; } // calc dimensions of wPostPatch // TODO: following is copied from calculation of wPostPatches and should be pre-calculated and stored there in HyPerConn::wPostPatches // TODO: following should be implemented as HyPerConn::calcPostPatchSize //const PVLayer * lPre = clayer; const float xScaleDiff = this->getPost()->getXScale() - this->getPre()->getXScale(); const float yScaleDiff = this->getPost()->getYScale() - this->getPre()->getYScale(); const float powXScale = pow(2.0f, (float) xScaleDiff); const float powYScale = pow(2.0f, (float) yScaleDiff); //const int prePad = lPre->loc.nb; const int nxPostPatch = (int) (this->xPatchSize() * powXScale); // TODO: store in HyPerConn::wPostPatches const int nyPostPatch = (int) (this->yPatchSize() * powYScale); // TODO: store in HyPerConn::wPostPatches //const int nfPostPatch = nf; // clique dimensions // a new set of cliques is centered on each pre-synaptic cell with radius nzPostPatch/2 // TODO: precompute clique dimensions during CliqueConn::initialize int nyCliqueRadius = (int) (nyPostPatch / 2); int nxCliqueRadius = (int) (nxPostPatch / 2); int cliquePatchSize = (2 * nxCliqueRadius + 1) * (2 * nyCliqueRadius + 1) * nfPre; //int numKernels = conn->numDataPatches(); // per arbor? int numCliques = pow(cliquePatchSize, cliqueSize - 1); assert(numCliques == this->numberOfAxonalArborLists()); // loop over all products of cliqueSize active presynaptic cells // outer loop is over presynaptic cells, each of which defines the center of a cliquePatch // inner loop is over all combinations of clique cells within cliquePatch boundaries, which may be shrunken // TODO: pre-allocate cliqueActiveIndices as CliqueConn::cliquePatchSize member variable int * cliqueActiveIndices = (int *) calloc(cliquePatchSize, sizeof(int)); assert(cliqueActiveIndices != NULL); for (int kPreActive = 0; kPreActive < numActiveExt; kPreActive++) { int kPreExt = activeExt[kPreActive]; // get indices of active elements in clique radius // watch out for shrunken patches! int numActiveElements = 0; int kxPreExt = kxPos(kPreExt, nxPreExt, nyPreExt, nfPre); int kyPreExt = kyPos(kPreExt, nxPreExt, nyPreExt, nfPre); if (cliqueSize > 1) { for (int kyCliqueExt = ((kyPreExt - nyCliqueRadius) > 0 ? (kyPreExt - nyCliqueRadius) : 0); kyCliqueExt < ((kyPreExt + nyCliqueRadius) <= nyPreExt ? (kyPreExt + nyCliqueRadius) : nyPreExt); kyCliqueExt++) { //if (kyCliqueExt < 0 || kyCliqueExt > nyPreExt) continue; for (int kxCliqueExt = ((kxPreExt - nxCliqueRadius) > 0 ? (kxPreExt - nxCliqueRadius) : 0); kxCliqueExt < ((kxPreExt + nxCliqueRadius) <= nxPreExt ? (kxPreExt + nxCliqueRadius) : nxPreExt); kxCliqueExt++) { //if (kyCliqueExt < 0 || kyCliqueExt > nxPreExt) continue; for (int kfCliqueExt = 0; kfCliqueExt < nfPre; kfCliqueExt++) { int kCliqueExt = kIndex(kxCliqueExt, kyCliqueExt, kfCliqueExt, nxPreExt, nyPreExt, nfPre); if ((aPre[kCliqueExt] == 0) || (kCliqueExt == kPreExt)) continue; cliqueActiveIndices[numActiveElements++] = kCliqueExt; } } } } // cliqueSize > 1 else { cliqueActiveIndices[numActiveElements++] = kPreExt; // each cell is its own clique if cliqueSize == 1 } if (numActiveElements < (cliqueSize-1)) continue; // loop over all active combinations of size=cliqueSize-1 in clique radius int numActiveCliques = pow(numActiveElements, cliqueSize - 1); for (int kClique = 0; kClique < numActiveCliques; kClique++) { //initialize a_post_tmp if (self_flag) { // otherwise, a_post_mask is not modified and thus doesn't have to be updated for (int k_post = 0; k_post < a_post_size; k_post++) { a_post_mask[k_post] = 1; } a_post_mask[k_post_self] = 0; } // decompose kClique to compute product of active clique elements int arborNdx = 0; pvdata_t cliqueProd = aPre[kPreExt]; int kResidue = kClique; int maxIndex = -1; for (int iProd = 0; iProd < cliqueSize - 1; iProd++) { int kPatchActive = (unsigned int) (kResidue / pow(numActiveElements, cliqueSize - 1 - iProd - 1)); // only apply each permutation of clique elements once, no element can contribute more than once if (kPatchActive <= maxIndex) { break; } else { maxIndex = kPatchActive; } int kCliqueExt = cliqueActiveIndices[kPatchActive]; cliqueProd *= aPre[kCliqueExt]; kResidue = kResidue - kPatchActive * pow(numActiveElements, cliqueSize - 1 - iProd - 1); // compute arborIndex for this clique element int kxCliqueExt = kxPos(kCliqueExt, nxPreExt, nyPreExt, nfPre); int kyCliqueExt = kyPos(kCliqueExt, nxPreExt, nyPreExt, nfPre); int kfClique = featureIndex(kCliqueExt, nxPreExt, nyPreExt, nfPre); int kxPatch = kxCliqueExt - kxPreExt + nxCliqueRadius; int kyPatch = kyCliqueExt - kyPreExt + nyCliqueRadius; unsigned int kArbor = kIndex(kxPatch, kyPatch, kfClique, (2 * nxCliqueRadius + 1), (2*nyCliqueRadius + 1), nfPre); arborNdx += kArbor * pow(cliquePatchSize, cliqueSize - 1 - iProd - 1); if ((arborNdx < 0) || (arborNdx >= numCliques)){ assert((arborNdx >= 0) && (arborNdx < numCliques)); } // remove self-interactions if pre == post if (self_flag){ a_post_mask[kArbor] = 0; } } // iProd // receive weights input from clique (mostly copied from superclass method) // PVAxonalArbor * arbor = this->axonalArbor(kPreExt, arborNdx); PVPatch * dWPatch = dwPatches[arborNdx][kPreExt]; // arbor->plasticIncr; size_t postOffset = getAPostOffset(kPreExt, arborNdx); const float * aPost = &post->getLayerData()[postOffset]; const pvdata_t * dWStart = this->getPIncrDataStart(arborNdx); int kernelIndex = this->patchIndexToKernelIndex(kPreExt); const pvdata_t * dW_head = &(dWStart[a_post_size*kernelIndex]); size_t dW_offset = dWPatch->data - dW_head; // WARNING - assumes weight and GSyn patches from task same size // - assumes patch stride sf is 1 int nkPatch = nfp * dWPatch->nx; int nyPatch = dWPatch->ny; int syPatch = syp; // TODO - unroll for (int y = 0; y < nyPatch; y++) { pvpatch_update_clique2( nkPatch, (float *) (dWPatch->data + y * syPatch), cliqueProd, (float *) (aPost + y*syPostExt), (float *) (a_post_mask + dW_offset + y * syPatch)); } } // kClique } // kPreActive free(cliqueActiveIndices); free(activeExt); free(a_post_mask); return PV_BREAK; } ; // calc_dW int CliqueConn::updateWeights(int arborId) { int status = KernelConn::updateWeights(arborId); assert((status == PV_SUCCESS) || (status == PV_BREAK)); return PV_BREAK; } ; // updateWeights /* int CliqueConn::normalizeWeights(PVPatch ** patches, int numPatches, int arborId){ return PV_CONTINUE;}; */ }// namespace PV int pvpatch_update_clique(int nk, float* RESTRICT dW, float aPre, float* RESTRICT aPost) { int k; int err = 0; for (k = 0; k < nk; k++) { dW[k] += aPre * aPost[k]; } return err; } int pvpatch_update_clique2(int nk, float* RESTRICT dW, float aPre, float* RESTRICT aPost, float* RESTRICT a_mask) { int k; int err = 0; for (k = 0; k < nk; k++) { dW[k] += aPre * aPost[k] * a_mask[k]; } return err; } <|endoftext|>
<commit_before>#include <arpa/inet.h> // inet_ntoa #include <fstream> #include <iostream> #include <netdb.h> // gethostbyname #include <netinet/in.h> // htonl, htons, inet_ntoa #include <netinet/tcp.h> // SO_REUSEADDR #include <pthread.h> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string> #include <strings.h> // bzero #include <sys/types.h> // socket, bind #include <sys/socket.h> // socket, bind, listen, inet_ntoa #include <sys/uio.h> // writev #include <sys/time.h> #include <unistd.h> // read, write, close using namespace std; struct threadData { int sd; }; #define BUF_SIZE 16384 #define PORT 80 // // IF_FALSE_RETURN // // Macro to convieniently add basic error handling // #define IF_FALSE_RETURN(test, msg) \ if (!(test)) \ { \ printf("%s\n", msg); \ return -1; \ } // ConvertParameterToInt // // several of our parameters are expected to be well formed numbers // since no negative values are expected, return -1 to indicate an error. // int ConvertParameterToInt(char* value) { char* endptr = NULL; long int result = strtol(value, &endptr, 0); if (*value == '\0' || *endptr != '\0') return -1; return (int)result; } void* openAndSendFile(void* whatever) { // If file requested does not exist, return 404 Not Found code with custom File Not Found page // // // // If HTTP request is for SecretFile.html, return 401 Unauthorized // // // // If request is for file that is above the directory structure where web server is running ( for example, "GET ../../../etc/passwd" ), return 403 Forbidden // // // // if server cannot understand request return 400 Bad Request // // // threadData* data = (threadData*)whatever; int sd = data->sd; delete data; // After receiving GET request... char databuf[BUF_SIZE]; stringstream ssrequest; // Repeat reading data from the client into databuf[BUF_SIZE]. // Note that the read system call may return without reading // the entire data if the network is slow. int readed = read(sd, &databuf, BUF_SIZE); while(readed > 0) { ssrequest.write(databuf, readed); readed = read(sd, &databuf, BUF_SIZE); } printf("Printing ssrequest:\n"); cout << ssrequest.str(); // open file requested... /* // and send with HTTP 200 OK code. int written = 0; while (written < sizeof(count)) { int bytesWritten = write(sd, &count, sizeof(count)); if (bytesWritten == -1) { printf("write failed\n"); exit(1); } written += bytesWritten; } if (close(sd) != 0) { printf("close failed\n"); exit(1); }*/ } int main(int argc, char** argv) { //wait for connection and HTTP GET request (you may do this single threaded or multi-threaded) // Declare and initialize sockaddr_in structure sockaddr_in acceptSockAddr; bzero((char*)&acceptSockAddr, sizeof(acceptSockAddr)); acceptSockAddr.sin_family = AF_INET; acceptSockAddr.sin_addr.s_addr = htonl(INADDR_ANY); acceptSockAddr.sin_port = htons(port); // Open a stream-oriented socket with the Internet address family. int serverSd = socket(AF_INET, SOCK_STREAM, 0); IF_FALSE_RETURN(serverSd != -1, "socket failed to create file descriptor"); // Set the SO_REUSEADDR option. // // Note: this option is useful to prompt OS to release the server port // as soon as your server process is terminated. const int on = 1; IF_FALSE_RETURN(setsockopt(serverSd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(int)) != -1, "setsockopt failed"); // Bind this socket to its local address. IF_FALSE_RETURN(bind(serverSd, (sockaddr*)&acceptSockAddr, sizeof(acceptSockAddr)) != -1, "bind failed"); // Instruct the operating system to listen to up to 8 connection requests from clients at a time IF_FALSE_RETURN(listen(serverSd, 8) != -1, "listen failed"); printf("Server: listening on port %d\n", port); // Receive a request from a client by calling accept that will return a new socket specific to this connection request. sockaddr_in newSockAddr; socklen_t newSockAddrSize = sizeof(newSockAddr); int newSd = accept(serverSd, (sockaddr*)&newSockAddr, &newSockAddrSize); printf("Server: accepted connection\n"); while (newSd != -1) { //Create a new thread threadData* data = new threadData(); data->sd = newSd; pthread_t thread; if (pthread_create(&thread, NULL, openAndSendFile, data) != 0) { delete data; printf("pthread_create failed\n"); return -1; } printf("Server: created thread\n"); //After handling request, return to waiting for next request. newSd = accept(serverSd, (sockaddr*)&newSockAddr, &newSockAddrSize); printf("Server: accepted another connection\n"); } IF_FALSE_RETURN(newSd != -1, "accept failed"); return 0; }<commit_msg>Another bugfix! If you haven't guessed yet, I'm compiling and coding on two different machines.<commit_after>#include <arpa/inet.h> // inet_ntoa #include <fstream> #include <iostream> #include <netdb.h> // gethostbyname #include <netinet/in.h> // htonl, htons, inet_ntoa #include <netinet/tcp.h> // SO_REUSEADDR #include <pthread.h> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string> #include <strings.h> // bzero #include <sys/types.h> // socket, bind #include <sys/socket.h> // socket, bind, listen, inet_ntoa #include <sys/uio.h> // writev #include <sys/time.h> #include <unistd.h> // read, write, close using namespace std; struct threadData { int sd; }; #define BUF_SIZE 16384 #define PORT 80 // // IF_FALSE_RETURN // // Macro to convieniently add basic error handling // #define IF_FALSE_RETURN(test, msg) \ if (!(test)) \ { \ printf("%s\n", msg); \ return -1; \ } // ConvertParameterToInt // // several of our parameters are expected to be well formed numbers // since no negative values are expected, return -1 to indicate an error. // int ConvertParameterToInt(char* value) { char* endptr = NULL; long int result = strtol(value, &endptr, 0); if (*value == '\0' || *endptr != '\0') return -1; return (int)result; } void* openAndSendFile(void* whatever) { // If file requested does not exist, return 404 Not Found code with custom File Not Found page // // // // If HTTP request is for SecretFile.html, return 401 Unauthorized // // // // If request is for file that is above the directory structure where web server is running ( for example, "GET ../../../etc/passwd" ), return 403 Forbidden // // // // if server cannot understand request return 400 Bad Request // // // threadData* data = (threadData*)whatever; int sd = data->sd; delete data; // After receiving GET request... char databuf[BUF_SIZE]; stringstream ssrequest; // Repeat reading data from the client into databuf[BUF_SIZE]. // Note that the read system call may return without reading // the entire data if the network is slow. int readed = read(sd, &databuf, BUF_SIZE); while(readed > 0) { ssrequest.write(databuf, readed); readed = read(sd, &databuf, BUF_SIZE); } printf("Printing ssrequest:\n"); cout << ssrequest.str(); // open file requested... /* // and send with HTTP 200 OK code. int written = 0; while (written < sizeof(count)) { int bytesWritten = write(sd, &count, sizeof(count)); if (bytesWritten == -1) { printf("write failed\n"); exit(1); } written += bytesWritten; } if (close(sd) != 0) { printf("close failed\n"); exit(1); }*/ } int main(int argc, char** argv) { //wait for connection and HTTP GET request (you may do this single threaded or multi-threaded) // Declare and initialize sockaddr_in structure sockaddr_in acceptSockAddr; bzero((char*)&acceptSockAddr, sizeof(acceptSockAddr)); acceptSockAddr.sin_family = AF_INET; acceptSockAddr.sin_addr.s_addr = htonl(INADDR_ANY); acceptSockAddr.sin_port = htons(PORT); // Open a stream-oriented socket with the Internet address family. int serverSd = socket(AF_INET, SOCK_STREAM, 0); IF_FALSE_RETURN(serverSd != -1, "socket failed to create file descriptor"); // Set the SO_REUSEADDR option. // // Note: this option is useful to prompt OS to release the server port // as soon as your server process is terminated. const int on = 1; IF_FALSE_RETURN(setsockopt(serverSd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(int)) != -1, "setsockopt failed"); // Bind this socket to its local address. IF_FALSE_RETURN(bind(serverSd, (sockaddr*)&acceptSockAddr, sizeof(acceptSockAddr)) != -1, "bind failed"); // Instruct the operating system to listen to up to 8 connection requests from clients at a time IF_FALSE_RETURN(listen(serverSd, 8) != -1, "listen failed"); printf("Server: listening on port %d\n", port); // Receive a request from a client by calling accept that will return a new socket specific to this connection request. sockaddr_in newSockAddr; socklen_t newSockAddrSize = sizeof(newSockAddr); int newSd = accept(serverSd, (sockaddr*)&newSockAddr, &newSockAddrSize); printf("Server: accepted connection\n"); while (newSd != -1) { //Create a new thread threadData* data = new threadData(); data->sd = newSd; pthread_t thread; if (pthread_create(&thread, NULL, openAndSendFile, data) != 0) { delete data; printf("pthread_create failed\n"); return -1; } printf("Server: created thread\n"); //After handling request, return to waiting for next request. newSd = accept(serverSd, (sockaddr*)&newSockAddr, &newSockAddrSize); printf("Server: accepted another connection\n"); } IF_FALSE_RETURN(newSd != -1, "accept failed"); return 0; }<|endoftext|>
<commit_before>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ /* * Copyright (c) 2008 litl, LLC * * 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 <config.h> #include <glib.h> #include <glib-object.h> #include <gjs/gjs-module.h> #include <util/glib.h> #include <util/crash.h> typedef struct _GjsUnitTestFixture GjsUnitTestFixture; struct _GjsUnitTestFixture { JSContext *context; GjsContext *gjs_context; }; static void test_error_reporter(JSContext *context, const char *message, JSErrorReport *report) { g_printerr("error reported by test: %s\n", message); } static void _gjs_unit_test_fixture_begin (GjsUnitTestFixture *fixture) { fixture->gjs_context = gjs_context_new (); fixture->context = (JSContext *) gjs_context_get_native_context (fixture->gjs_context); JS_BeginRequest(fixture->context); JS_SetErrorReporter(fixture->context, test_error_reporter); } static void _gjs_unit_test_fixture_finish (GjsUnitTestFixture *fixture) { JS_EndRequest(fixture->context); g_object_unref(fixture->gjs_context); } static void gjstest_test_func_gjs_context_construct_destroy(void) { GjsContext *context; /* Construct twice just to possibly a case where global state from * the first leaks. */ context = gjs_context_new (); g_object_unref (context); context = gjs_context_new (); g_object_unref (context); } static void gjstest_test_func_gjs_context_construct_eval(void) { GjsContext *context; int estatus; GError *error = NULL; context = gjs_context_new (); if (!gjs_context_eval (context, "1+1", -1, "<input>", &estatus, &error)) g_error ("%s", error->message); g_object_unref (context); } static void gjstest_test_func_gjs_context_fixture(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } #define N_ELEMS 15 static void gjstest_test_func_gjs_jsapi_util_array(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; GjsRootedArray *array; int i; jsval value; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; array = gjs_rooted_array_new(); global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); for (i = 0; i < N_ELEMS; i++) { value = STRING_TO_JSVAL(JS_NewStringCopyZ(context, "abcdefghijk")); gjs_rooted_array_append(context, array, value); } JS_GC(JS_GetRuntime(context)); for (i = 0; i < N_ELEMS; i++) { char *ascii; value = gjs_rooted_array_get(context, array, i); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &ascii); g_assert(strcmp(ascii, "abcdefghijk") == 0); g_free(ascii); } gjs_rooted_array_free(context, array, TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } #undef N_ELEMS static void gjstest_test_func_gjs_jsapi_util_string_js_string_utf8(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; const char *utf8_string = "\303\211\303\226 foobar \343\203\237"; char *utf8_result; jsval js_string; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); g_assert(gjs_string_from_utf8(context, utf8_string, -1, &js_string) == JS_TRUE); g_assert(JSVAL_IS_STRING(js_string)); g_assert(gjs_string_to_utf8(context, js_string, &utf8_result) == JS_TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); g_assert(g_str_equal(utf8_string, utf8_result)); g_free(utf8_result); } static void gjstest_test_func_gjs_stack_dump(void) { GjsContext *context; /* TODO this test could be better - maybe expose dumpstack as a JS API * so that we have a JS stack to dump? At least here we're getting some * coverage. */ context = gjs_context_new(); gjs_dumpstack(); g_object_unref(context); gjs_dumpstack(); } static void gjstest_test_func_gjs_jsapi_util_error_throw(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; jsval exc, value, previous; char *s = NULL; int strcmp_result; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); /* Test that we can throw */ gjs_throw(context, "This is an exception %d", 42); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); value = JSVAL_VOID; JS_GetProperty(context, JSVAL_TO_OBJECT(exc), "message", &value); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &s); g_assert(s != NULL); strcmp_result = strcmp(s, "This is an exception 42"); free(s); if (strcmp_result != 0) g_error("Exception has wrong message '%s'", s); /* keep this around before we clear it */ previous = exc; JS_AddValueRoot(context, &previous); JS_ClearPendingException(context); g_assert(!JS_IsExceptionPending(context)); /* Check that we don't overwrite a pending exception */ JS_SetPendingException(context, previous); g_assert(JS_IsExceptionPending(context)); gjs_throw(context, "Second different exception %s", "foo"); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); g_assert(JSVAL_TO_OBJECT(exc) == JSVAL_TO_OBJECT(previous)); JS_RemoveValueRoot(context, &previous); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } static void gjstest_test_func_util_glib_strv_concat_null(void) { char **ret; ret = gjs_g_strv_concat(NULL, 0); g_assert(ret != NULL); g_assert(ret[0] == NULL); g_strfreev(ret); } static void gjstest_test_func_util_glib_strv_concat_pointers(void) { char *strv0[2] = {(char*)"foo", NULL}; char *strv1[1] = {NULL}; char **strv2 = NULL; char *strv3[2] = {(char*)"bar", NULL}; char **stuff[4]; char **ret; stuff[0] = strv0; stuff[1] = strv1; stuff[2] = strv2; stuff[3] = strv3; ret = gjs_g_strv_concat(stuff, 4); g_assert(ret != NULL); g_assert_cmpstr(ret[0], ==, strv0[0]); /* same string */ g_assert(ret[0] != strv0[0]); /* different pointer */ g_assert_cmpstr(ret[1], ==, strv3[0]); g_assert(ret[1] != strv3[0]); g_assert(ret[2] == NULL); g_strfreev(ret); } static void gjstest_test_strip_shebang_no_advance_for_no_shebang(void) { const char *script = "foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(script, ==, stripped); g_assert(script_len == script_len_original); g_assert(line_number == 1); } static void gjstest_test_strip_shebang_advance_for_shebang(void) { const char *script = "#!foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(stripped, ==, "bar"); g_assert(script_len == 3); g_assert(line_number == 2); } static void gjstest_test_strip_shebang_return_null_for_just_shebang(void) { const char *script = "#!foo"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert(stripped == NULL); g_assert(script_len == 0); g_assert(line_number == -1); } int main(int argc, char **argv) { gjs_crash_after_timeout(60*7); /* give the unit tests 7 minutes to complete */ g_test_init(&argc, &argv, NULL); g_test_add_func("/gjs/context/construct/destroy", gjstest_test_func_gjs_context_construct_destroy); g_test_add_func("/gjs/context/construct/eval", gjstest_test_func_gjs_context_construct_eval); g_test_add_func("/gjs/context/fixture", gjstest_test_func_gjs_context_fixture); g_test_add_func("/gjs/jsapi/util/array", gjstest_test_func_gjs_jsapi_util_array); g_test_add_func("/gjs/jsapi/util/error/throw", gjstest_test_func_gjs_jsapi_util_error_throw); g_test_add_func("/gjs/jsapi/util/string/js/string/utf8", gjstest_test_func_gjs_jsapi_util_string_js_string_utf8); g_test_add_func("/gjs/jsutil/strip_shebang/no_shebang", gjstest_test_strip_shebang_no_advance_for_no_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/have_shebang", gjstest_test_strip_shebang_advance_for_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/only_shebang", gjstest_test_strip_shebang_return_null_for_just_shebang); g_test_add_func("/gjs/stack/dump", gjstest_test_func_gjs_stack_dump); g_test_add_func("/util/glib/strv/concat/null", gjstest_test_func_util_glib_strv_concat_null); g_test_add_func("/util/glib/strv/concat/pointers", gjstest_test_func_util_glib_strv_concat_pointers); g_test_run(); return 0; } <commit_msg>gjs-tests: Remove fixture test<commit_after>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */ /* * Copyright (c) 2008 litl, LLC * * 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 <config.h> #include <glib.h> #include <glib-object.h> #include <gjs/gjs-module.h> #include <util/glib.h> #include <util/crash.h> typedef struct _GjsUnitTestFixture GjsUnitTestFixture; struct _GjsUnitTestFixture { JSContext *context; GjsContext *gjs_context; }; static void test_error_reporter(JSContext *context, const char *message, JSErrorReport *report) { g_printerr("error reported by test: %s\n", message); } static void _gjs_unit_test_fixture_begin (GjsUnitTestFixture *fixture) { fixture->gjs_context = gjs_context_new (); fixture->context = (JSContext *) gjs_context_get_native_context (fixture->gjs_context); JS_BeginRequest(fixture->context); JS_SetErrorReporter(fixture->context, test_error_reporter); } static void _gjs_unit_test_fixture_finish (GjsUnitTestFixture *fixture) { JS_EndRequest(fixture->context); g_object_unref(fixture->gjs_context); } static void gjstest_test_func_gjs_context_construct_destroy(void) { GjsContext *context; /* Construct twice just to possibly a case where global state from * the first leaks. */ context = gjs_context_new (); g_object_unref (context); context = gjs_context_new (); g_object_unref (context); } static void gjstest_test_func_gjs_context_construct_eval(void) { GjsContext *context; int estatus; GError *error = NULL; context = gjs_context_new (); if (!gjs_context_eval (context, "1+1", -1, "<input>", &estatus, &error)) g_error ("%s", error->message); g_object_unref (context); } #define N_ELEMS 15 static void gjstest_test_func_gjs_jsapi_util_array(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; GjsRootedArray *array; int i; jsval value; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; array = gjs_rooted_array_new(); global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); for (i = 0; i < N_ELEMS; i++) { value = STRING_TO_JSVAL(JS_NewStringCopyZ(context, "abcdefghijk")); gjs_rooted_array_append(context, array, value); } JS_GC(JS_GetRuntime(context)); for (i = 0; i < N_ELEMS; i++) { char *ascii; value = gjs_rooted_array_get(context, array, i); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &ascii); g_assert(strcmp(ascii, "abcdefghijk") == 0); g_free(ascii); } gjs_rooted_array_free(context, array, TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } #undef N_ELEMS static void gjstest_test_func_gjs_jsapi_util_string_js_string_utf8(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; const char *utf8_string = "\303\211\303\226 foobar \343\203\237"; char *utf8_result; jsval js_string; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); g_assert(gjs_string_from_utf8(context, utf8_string, -1, &js_string) == JS_TRUE); g_assert(JSVAL_IS_STRING(js_string)); g_assert(gjs_string_to_utf8(context, js_string, &utf8_result) == JS_TRUE); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); g_assert(g_str_equal(utf8_string, utf8_result)); g_free(utf8_result); } static void gjstest_test_func_gjs_stack_dump(void) { GjsContext *context; /* TODO this test could be better - maybe expose dumpstack as a JS API * so that we have a JS stack to dump? At least here we're getting some * coverage. */ context = gjs_context_new(); gjs_dumpstack(); g_object_unref(context); gjs_dumpstack(); } static void gjstest_test_func_gjs_jsapi_util_error_throw(void) { GjsUnitTestFixture fixture; JSContext *context; JSObject *global; jsval exc, value, previous; char *s = NULL; int strcmp_result; _gjs_unit_test_fixture_begin(&fixture); context = fixture.context; global = JS_GetGlobalObject(context); JSCompartment *oldCompartment = JS_EnterCompartment(context, global); /* Test that we can throw */ gjs_throw(context, "This is an exception %d", 42); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); value = JSVAL_VOID; JS_GetProperty(context, JSVAL_TO_OBJECT(exc), "message", &value); g_assert(JSVAL_IS_STRING(value)); gjs_string_to_utf8(context, value, &s); g_assert(s != NULL); strcmp_result = strcmp(s, "This is an exception 42"); free(s); if (strcmp_result != 0) g_error("Exception has wrong message '%s'", s); /* keep this around before we clear it */ previous = exc; JS_AddValueRoot(context, &previous); JS_ClearPendingException(context); g_assert(!JS_IsExceptionPending(context)); /* Check that we don't overwrite a pending exception */ JS_SetPendingException(context, previous); g_assert(JS_IsExceptionPending(context)); gjs_throw(context, "Second different exception %s", "foo"); g_assert(JS_IsExceptionPending(context)); exc = JSVAL_VOID; JS_GetPendingException(context, &exc); g_assert(!JSVAL_IS_VOID(exc)); g_assert(JSVAL_TO_OBJECT(exc) == JSVAL_TO_OBJECT(previous)); JS_RemoveValueRoot(context, &previous); JS_LeaveCompartment(context, oldCompartment); _gjs_unit_test_fixture_finish(&fixture); } static void gjstest_test_func_util_glib_strv_concat_null(void) { char **ret; ret = gjs_g_strv_concat(NULL, 0); g_assert(ret != NULL); g_assert(ret[0] == NULL); g_strfreev(ret); } static void gjstest_test_func_util_glib_strv_concat_pointers(void) { char *strv0[2] = {(char*)"foo", NULL}; char *strv1[1] = {NULL}; char **strv2 = NULL; char *strv3[2] = {(char*)"bar", NULL}; char **stuff[4]; char **ret; stuff[0] = strv0; stuff[1] = strv1; stuff[2] = strv2; stuff[3] = strv3; ret = gjs_g_strv_concat(stuff, 4); g_assert(ret != NULL); g_assert_cmpstr(ret[0], ==, strv0[0]); /* same string */ g_assert(ret[0] != strv0[0]); /* different pointer */ g_assert_cmpstr(ret[1], ==, strv3[0]); g_assert(ret[1] != strv3[0]); g_assert(ret[2] == NULL); g_strfreev(ret); } static void gjstest_test_strip_shebang_no_advance_for_no_shebang(void) { const char *script = "foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(script, ==, stripped); g_assert(script_len == script_len_original); g_assert(line_number == 1); } static void gjstest_test_strip_shebang_advance_for_shebang(void) { const char *script = "#!foo\nbar"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert_cmpstr(stripped, ==, "bar"); g_assert(script_len == 3); g_assert(line_number == 2); } static void gjstest_test_strip_shebang_return_null_for_just_shebang(void) { const char *script = "#!foo"; gssize script_len_original = strlen(script); gssize script_len = script_len_original; int line_number = 1; const char *stripped = gjs_strip_unix_shebang(script, &script_len, &line_number); g_assert(stripped == NULL); g_assert(script_len == 0); g_assert(line_number == -1); } int main(int argc, char **argv) { gjs_crash_after_timeout(60*7); /* give the unit tests 7 minutes to complete */ g_test_init(&argc, &argv, NULL); g_test_add_func("/gjs/context/construct/destroy", gjstest_test_func_gjs_context_construct_destroy); g_test_add_func("/gjs/context/construct/eval", gjstest_test_func_gjs_context_construct_eval); g_test_add_func("/gjs/jsapi/util/array", gjstest_test_func_gjs_jsapi_util_array); g_test_add_func("/gjs/jsapi/util/error/throw", gjstest_test_func_gjs_jsapi_util_error_throw); g_test_add_func("/gjs/jsapi/util/string/js/string/utf8", gjstest_test_func_gjs_jsapi_util_string_js_string_utf8); g_test_add_func("/gjs/jsutil/strip_shebang/no_shebang", gjstest_test_strip_shebang_no_advance_for_no_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/have_shebang", gjstest_test_strip_shebang_advance_for_shebang); g_test_add_func("/gjs/jsutil/strip_shebang/only_shebang", gjstest_test_strip_shebang_return_null_for_just_shebang); g_test_add_func("/gjs/stack/dump", gjstest_test_func_gjs_stack_dump); g_test_add_func("/util/glib/strv/concat/null", gjstest_test_func_util_glib_strv_concat_null); g_test_add_func("/util/glib/strv/concat/pointers", gjstest_test_func_util_glib_strv_concat_pointers); g_test_run(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: wangtaize@baidu.com #include "agent/cgroup.h" #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <boost/bind.hpp> #include "common/logging.h" #include "common/util.h" #include "agent/downloader_manager.h" namespace galaxy { static int CPU_CFS_PERIOD = 100000; static int MIN_CPU_CFS_QUOTA = 1000; int CGroupCtrl::Create(int64_t task_id, std::map<std::string, std::string>& sub_sys_map) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = mkdir(ss.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status != 0) { if (errno == EEXIST) { // TODO LOG(WARNING, "cgroup already there"); } else { LOG(FATAL, "fail to create subsystem %s ,status is %d", ss.str().c_str(), status); return status; } } sub_sys_map[*it] = ss.str(); LOG(INFO, "create subsystem %s successfully", ss.str().c_str()); } return 0; } //目前不支持递归删除 //删除前应该清空tasks文件 int CGroupCtrl::Destroy(int64_t task_id) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = rmdir(ss.str().c_str()); if(status != 0 ){ LOG(FATAL,"fail to delete subsystem %s status %d",ss.str().c_str(),status); return status; } } return 0; } int AbstractCtrl::AttachTask(pid_t pid) { std::string task_file = _my_cg_root + "/" + "tasks"; int ret = common::util::WriteIntToFile(task_file, pid); if (ret < 0) { LOG(FATAL, "fail to attach pid %d for %s", pid, _my_cg_root.c_str()); return -1; } return 0; } int MemoryCtrl::SetLimit(int64_t limit) { std::string limit_file = _my_cg_root + "/" + "memory.limit_in_bytes"; int ret = common::util::WriteIntToFile(limit_file, limit); if (ret < 0) { LOG(FATAL, "fail to set limt %lld for %s", limit, _my_cg_root.c_str()); return -1; } return 0; } int MemoryCtrl::SetSoftLimit(int64_t soft_limit) { std::string soft_limit_file = _my_cg_root + "/" + "memory.soft_limit_in_bytes"; int ret = common::util::WriteIntToFile(soft_limit_file, soft_limit); if (ret < 0) { LOG(FATAL, "fail to set soft limt %lld for %s", soft_limit, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuShare(int64_t cpu_share) { std::string cpu_share_file = _my_cg_root + "/" + "cpu.shares"; int ret = common::util::WriteIntToFile(cpu_share_file, cpu_share); if (ret < 0) { LOG(FATAL, "fail to set cpu share %lld for %s", cpu_share, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuPeriod(int64_t cpu_period) { std::string cpu_period_file = _my_cg_root + "/" + "cpu.cfs_period_us"; int ret = common::util::WriteIntToFile(cpu_period_file, cpu_period); if (ret < 0) { LOG(FATAL, "fail to set cpu period %lld for %s", cpu_period, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuQuota(int64_t cpu_quota) { std::string cpu_quota_file = _my_cg_root + "/" + "cpu.cfs_quota_us"; int ret = common::util::WriteIntToFile(cpu_quota_file, cpu_quota); if (ret < 0) { LOG(FATAL, "fail to set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return -1; } LOG(INFO, "set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return 0; } int ContainerTaskRunner::Prepare() { LOG(INFO, "prepare container for task %d", m_task_info.task_id()); //TODO std::vector<std::string> support_cg; support_cg.push_back("memory"); support_cg.push_back("cpu"); _cg_ctrl = new CGroupCtrl(_cg_root, support_cg); std::map<std::string, std::string> sub_sys_map; int status = _cg_ctrl->Create(m_task_info.task_id(), sub_sys_map); if (status != 0) { LOG(FATAL, "fail to create subsystem for task %d,status %d", m_task_info.task_id(), status); return status; } _mem_ctrl = new MemoryCtrl(sub_sys_map["memory"]); _cpu_ctrl = new CpuCtrl(sub_sys_map["cpu"]); std::string uri = m_task_info.task_raw(); std::string path = m_workspace->GetPath(); path.append("/"); path.append("tmp.tar.gz"); DownloaderManager* downloader_handler = DownloaderManager::GetInstance(); downloader_handler->DownloadInThread( uri, path, boost::bind(&ContainerTaskRunner::StartAfterDownload, this, _1)); return 0; } void ContainerTaskRunner::StartAfterDownload(int ret) { if (ret == 0) { std::string tar_cmd = "cd " + m_workspace->GetPath() + " && tar -xzf tmp.tar.gz"; int status = system(tar_cmd.c_str()); if (status != 0) { LOG(WARNING, "tar -xf failed"); return; } Start(); } } void ContainerTaskRunner::PutToCGroup(){ int64_t mem_size = m_task_info.required_mem() * (1L << 30); double cpu_core = m_task_info.required_cpu(); LOG(INFO, "resource limit cpu %f, mem %ld", cpu_core, mem_size); if (mem_size <= (1L << 30)) { mem_size = (1L << 30); } /* std::string mem_key = "memory"; std::string cpu_key = "cpu"; for (int i = 0; i< m_task_info.resource_list_size(); i++){ ResourceItem item = m_task_info.resource_list(i); if(mem_key.compare(item.name())==0 && item.value() > 0){ mem_size = item.value(); continue; } if(cpu_key.compare(item.name())==0 && item.value() >0){ cpu_share = item.value() * 512; } }*/ _mem_ctrl->SetLimit(mem_size); //_cpu_ctrl->SetCpuShare(cpu_share); int64_t quota = static_cast<int64_t>(cpu_core * CPU_CFS_PERIOD); if (quota < MIN_CPU_CFS_QUOTA) { quota = MIN_CPU_CFS_QUOTA; } _cpu_ctrl->SetCpuQuota(quota); pid_t my_pid = getpid(); _mem_ctrl->AttachTask(my_pid); _cpu_ctrl->AttachTask(my_pid); } int ContainerTaskRunner::Start() { LOG(INFO, "start a task with id %d", m_task_info.task_id()); if (IsRunning() == 0) { LOG(WARNING, "task with id %d has been runing", m_task_info.task_id()); return -1; } int stdout_fd, stderr_fd; std::vector<int> fds; PrepareStart(fds, &stdout_fd, &stderr_fd); m_child_pid = fork(); if (m_child_pid == 0) { PutToCGroup(); StartTaskAfterFork(fds, stdout_fd, stderr_fd); } else { close(stdout_fd); close(stderr_fd); } return 0; } int ContainerTaskRunner::Stop(){ int status = AbstractTaskRunner::Stop(); LOG(INFO,"stop task %d with status %d",m_task_info.task_id(),status); if(status != 0 ){ return status; } status = _cg_ctrl->Destroy(m_task_info.task_id()); LOG(INFO,"destroy cgroup for task %d with status %s",m_task_info.task_id(),status); return status; } } <commit_msg>remove 1<<30<commit_after>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: wangtaize@baidu.com #include "agent/cgroup.h" #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <errno.h> #include <boost/bind.hpp> #include "common/logging.h" #include "common/util.h" #include "agent/downloader_manager.h" namespace galaxy { static int CPU_CFS_PERIOD = 100000; static int MIN_CPU_CFS_QUOTA = 1000; int CGroupCtrl::Create(int64_t task_id, std::map<std::string, std::string>& sub_sys_map) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = mkdir(ss.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status != 0) { if (errno == EEXIST) { // TODO LOG(WARNING, "cgroup already there"); } else { LOG(FATAL, "fail to create subsystem %s ,status is %d", ss.str().c_str(), status); return status; } } sub_sys_map[*it] = ss.str(); LOG(INFO, "create subsystem %s successfully", ss.str().c_str()); } return 0; } //目前不支持递归删除 //删除前应该清空tasks文件 int CGroupCtrl::Destroy(int64_t task_id) { if (_support_cg.size() <= 0) { LOG(WARNING, "no subsystem is support"); return -1; } std::vector<std::string>::iterator it = _support_cg.begin(); for (; it != _support_cg.end(); ++it) { std::stringstream ss ; ss << _cg_root << "/" << *it << "/" << task_id; int status = rmdir(ss.str().c_str()); if(status != 0 ){ LOG(FATAL,"fail to delete subsystem %s status %d",ss.str().c_str(),status); return status; } } return 0; } int AbstractCtrl::AttachTask(pid_t pid) { std::string task_file = _my_cg_root + "/" + "tasks"; int ret = common::util::WriteIntToFile(task_file, pid); if (ret < 0) { LOG(FATAL, "fail to attach pid %d for %s", pid, _my_cg_root.c_str()); return -1; } return 0; } int MemoryCtrl::SetLimit(int64_t limit) { std::string limit_file = _my_cg_root + "/" + "memory.limit_in_bytes"; int ret = common::util::WriteIntToFile(limit_file, limit); if (ret < 0) { LOG(FATAL, "fail to set limt %lld for %s", limit, _my_cg_root.c_str()); return -1; } return 0; } int MemoryCtrl::SetSoftLimit(int64_t soft_limit) { std::string soft_limit_file = _my_cg_root + "/" + "memory.soft_limit_in_bytes"; int ret = common::util::WriteIntToFile(soft_limit_file, soft_limit); if (ret < 0) { LOG(FATAL, "fail to set soft limt %lld for %s", soft_limit, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuShare(int64_t cpu_share) { std::string cpu_share_file = _my_cg_root + "/" + "cpu.shares"; int ret = common::util::WriteIntToFile(cpu_share_file, cpu_share); if (ret < 0) { LOG(FATAL, "fail to set cpu share %lld for %s", cpu_share, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuPeriod(int64_t cpu_period) { std::string cpu_period_file = _my_cg_root + "/" + "cpu.cfs_period_us"; int ret = common::util::WriteIntToFile(cpu_period_file, cpu_period); if (ret < 0) { LOG(FATAL, "fail to set cpu period %lld for %s", cpu_period, _my_cg_root.c_str()); return -1; } return 0; } int CpuCtrl::SetCpuQuota(int64_t cpu_quota) { std::string cpu_quota_file = _my_cg_root + "/" + "cpu.cfs_quota_us"; int ret = common::util::WriteIntToFile(cpu_quota_file, cpu_quota); if (ret < 0) { LOG(FATAL, "fail to set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return -1; } LOG(INFO, "set cpu quota %ld for %s", cpu_quota, _my_cg_root.c_str()); return 0; } int ContainerTaskRunner::Prepare() { LOG(INFO, "prepare container for task %d", m_task_info.task_id()); //TODO std::vector<std::string> support_cg; support_cg.push_back("memory"); support_cg.push_back("cpu"); _cg_ctrl = new CGroupCtrl(_cg_root, support_cg); std::map<std::string, std::string> sub_sys_map; int status = _cg_ctrl->Create(m_task_info.task_id(), sub_sys_map); if (status != 0) { LOG(FATAL, "fail to create subsystem for task %d,status %d", m_task_info.task_id(), status); return status; } _mem_ctrl = new MemoryCtrl(sub_sys_map["memory"]); _cpu_ctrl = new CpuCtrl(sub_sys_map["cpu"]); std::string uri = m_task_info.task_raw(); std::string path = m_workspace->GetPath(); path.append("/"); path.append("tmp.tar.gz"); DownloaderManager* downloader_handler = DownloaderManager::GetInstance(); downloader_handler->DownloadInThread( uri, path, boost::bind(&ContainerTaskRunner::StartAfterDownload, this, _1)); return 0; } void ContainerTaskRunner::StartAfterDownload(int ret) { if (ret == 0) { std::string tar_cmd = "cd " + m_workspace->GetPath() + " && tar -xzf tmp.tar.gz"; int status = system(tar_cmd.c_str()); if (status != 0) { LOG(WARNING, "tar -xf failed"); return; } Start(); } } void ContainerTaskRunner::PutToCGroup(){ int64_t mem_size = m_task_info.required_mem(); double cpu_core = m_task_info.required_cpu(); LOG(INFO, "resource limit cpu %f, mem %ld", cpu_core, mem_size); /* std::string mem_key = "memory"; std::string cpu_key = "cpu"; for (int i = 0; i< m_task_info.resource_list_size(); i++){ ResourceItem item = m_task_info.resource_list(i); if(mem_key.compare(item.name())==0 && item.value() > 0){ mem_size = item.value(); continue; } if(cpu_key.compare(item.name())==0 && item.value() >0){ cpu_share = item.value() * 512; } }*/ _mem_ctrl->SetLimit(mem_size); //_cpu_ctrl->SetCpuShare(cpu_share); int64_t quota = static_cast<int64_t>(cpu_core * CPU_CFS_PERIOD); if (quota < MIN_CPU_CFS_QUOTA) { quota = MIN_CPU_CFS_QUOTA; } _cpu_ctrl->SetCpuQuota(quota); pid_t my_pid = getpid(); _mem_ctrl->AttachTask(my_pid); _cpu_ctrl->AttachTask(my_pid); } int ContainerTaskRunner::Start() { LOG(INFO, "start a task with id %d", m_task_info.task_id()); if (IsRunning() == 0) { LOG(WARNING, "task with id %d has been runing", m_task_info.task_id()); return -1; } int stdout_fd, stderr_fd; std::vector<int> fds; PrepareStart(fds, &stdout_fd, &stderr_fd); m_child_pid = fork(); if (m_child_pid == 0) { PutToCGroup(); StartTaskAfterFork(fds, stdout_fd, stderr_fd); } else { close(stdout_fd); close(stderr_fd); } return 0; } int ContainerTaskRunner::Stop(){ int status = AbstractTaskRunner::Stop(); LOG(INFO,"stop task %d with status %d",m_task_info.task_id(),status); if(status != 0 ){ return status; } status = _cg_ctrl->Destroy(m_task_info.task_id()); LOG(INFO,"destroy cgroup for task %d with status %s",m_task_info.task_id(),status); return status; } } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/core/kernels/captured_function.h" #include <utility> #include "tensorflow/core/common_runtime/threadpool_device.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/framework/device_attributes.pb.h" #include "tensorflow/core/framework/lookup_interface.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/queue_interface.h" #include "tensorflow/core/framework/reader_interface.h" #include "tensorflow/core/framework/resource_handle.pb_text.h" #include "tensorflow/core/kernels/dataset.h" #include "tensorflow/core/kernels/variable_ops.h" #include "tensorflow/core/platform/notification.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { /* static */ Status CapturedFunction::Create( OpKernelContext* ctx, const NameAttrList* func, int graph_def_version, std::vector<Tensor> captured_inputs, std::unique_ptr<CapturedFunction>* out_function) { // NOTE(mrry): We need to assign a name to the device, and we choose // the same name as the calling context's device so that we do not // need to rewrite resource handles that are found in `captured_inputs`. Device* device = new ThreadPoolDevice(SessionOptions(), ctx->device()->attributes().name(), Bytes(256 << 20), DeviceLocality(), cpu_allocator()); // TODO(mrry): Handle arbitrary resource types, which might require a // redesign (or opening up access to `ResourceMgr::DoLookup()` and // `ResourceMgr::DoCreate()` to this code). #define HANDLE_RESOURCE_TYPE(ResourceType) \ if (input_handle.hash_code() == MakeTypeIndex<ResourceType>().hash_code()) { \ ResourceType* resource; \ Status s = LookupResource(ctx, input_handle, &resource); \ if (errors::IsNotFound(s)) { \ return errors::FailedPrecondition( \ "Failed to capture resource named \"", input_handle.name(), \ "\" in a dataset function. You may need to initialize it " \ "explicitly before initializing an iterator that uses it."); \ } else if (!s.ok()) { \ return s; \ } \ TF_RETURN_IF_ERROR(device->resource_manager()->Create( \ input_handle.container(), input_handle.name(), resource)); \ continue; \ } for (size_t i = 0; i < captured_inputs.size(); ++i) { if (captured_inputs[i].dtype() == DT_RESOURCE) { // Extract the resource from `ctx->resource_manager()` and // insert it into `device->resource_manager()` so that it can be // used when the function executes. ResourceHandle input_handle = captured_inputs[i].scalar<ResourceHandle>()(); HANDLE_RESOURCE_TYPE(lookup::LookupInterface); HANDLE_RESOURCE_TYPE(QueueInterface); HANDLE_RESOURCE_TYPE(Var); return errors::Unimplemented( "Cannot currently capture resource '", ProtoDebugString(input_handle), "' in a dataset function (type not supported)."); } } #undef HANDLE_RESOURCE_TYPE std::unique_ptr<DeviceMgr> device_mgr(new DeviceMgr({device})); std::unique_ptr<FunctionLibraryDefinition> flib_def( new FunctionLibraryDefinition( *ctx->function_library()->GetFunctionLibraryDefinition())); std::unique_ptr<ProcessFunctionLibraryRuntime> pflr( new ProcessFunctionLibraryRuntime( device_mgr.get(), ctx->env(), graph_def_version, flib_def.get(), {} /* TODO(mrry): OptimizerOptions? */)); FunctionLibraryRuntime* lib = pflr->GetFLR(device->name()); FunctionLibraryRuntime::Handle f_handle; TF_RETURN_IF_ERROR( lib->Instantiate(func->name(), AttrSlice(&func->attr()), &f_handle)); out_function->reset(new CapturedFunction( device, std::move(device_mgr), std::move(flib_def), std::move(pflr), lib, f_handle, std::move(captured_inputs))); return Status::OK(); } Status CapturedFunction::Run(FunctionLibraryRuntime::Options f_opts, gtl::ArraySlice<Tensor> args, std::vector<Tensor>* rets, const string& prefix) { port::Tracing::TraceMe activity(strings::StrCat(prefix, "::Run")); Notification n; Status s; auto done_callback = [&n, &s](Status func_status) { s.Update(func_status); n.Notify(); }; // TODO(mrry): Add cancellation manager support to IteratorContext // so that we can cancel running map functions. The local // cancellation manager here is created so that we can run kernels // (such as queue kernels) that depend on the non-nullness // `OpKernelContext::cancellation_manager()`, but additional effort // will be required to plumb it through the `IteratorContext`. CancellationManager c_mgr; f_opts.cancellation_manager = &c_mgr; // TODO(mrry): Implement a synchronous version of // FunctionLibraryRuntime::Run() that avoids a context switch for small // functions. if (captured_inputs_.empty()) { lib_->Run(f_opts, f_handle_, args, rets, done_callback); } else { std::vector<Tensor> args_with_captured; args_with_captured.reserve(args.size() + captured_inputs_.size()); args_with_captured.insert(args_with_captured.end(), args.begin(), args.end()); args_with_captured.insert(args_with_captured.end(), captured_inputs_.begin(), captured_inputs_.end()); lib_->Run(f_opts, f_handle_, args_with_captured, rets, done_callback); } n.WaitForNotification(); return s; } CapturedFunction::CapturedFunction( Device* device, std::unique_ptr<DeviceMgr> device_mgr, std::unique_ptr<FunctionLibraryDefinition> flib_def, std::unique_ptr<ProcessFunctionLibraryRuntime> pflr, FunctionLibraryRuntime* lib, FunctionLibraryRuntime::Handle f_handle, std::vector<Tensor> captured_inputs) : device_(device), device_mgr_(std::move(device_mgr)), flib_def_(std::move(flib_def)), pflr_(std::move(pflr)), lib_(lib), f_handle_(f_handle), captured_inputs_(std::move(captured_inputs)) {} } // namespace tensorflow <commit_msg>Use 2-arg TraceMe constructor to prevent unnecessary StrCat computation when tracing is disabled.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/core/kernels/captured_function.h" #include <utility> #include "tensorflow/core/common_runtime/threadpool_device.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/framework/device_attributes.pb.h" #include "tensorflow/core/framework/lookup_interface.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/queue_interface.h" #include "tensorflow/core/framework/reader_interface.h" #include "tensorflow/core/framework/resource_handle.pb_text.h" #include "tensorflow/core/kernels/dataset.h" #include "tensorflow/core/kernels/variable_ops.h" #include "tensorflow/core/platform/notification.h" #include "tensorflow/core/public/session_options.h" namespace tensorflow { /* static */ Status CapturedFunction::Create( OpKernelContext* ctx, const NameAttrList* func, int graph_def_version, std::vector<Tensor> captured_inputs, std::unique_ptr<CapturedFunction>* out_function) { // NOTE(mrry): We need to assign a name to the device, and we choose // the same name as the calling context's device so that we do not // need to rewrite resource handles that are found in `captured_inputs`. Device* device = new ThreadPoolDevice(SessionOptions(), ctx->device()->attributes().name(), Bytes(256 << 20), DeviceLocality(), cpu_allocator()); // TODO(mrry): Handle arbitrary resource types, which might require a // redesign (or opening up access to `ResourceMgr::DoLookup()` and // `ResourceMgr::DoCreate()` to this code). #define HANDLE_RESOURCE_TYPE(ResourceType) \ if (input_handle.hash_code() == MakeTypeIndex<ResourceType>().hash_code()) { \ ResourceType* resource; \ Status s = LookupResource(ctx, input_handle, &resource); \ if (errors::IsNotFound(s)) { \ return errors::FailedPrecondition( \ "Failed to capture resource named \"", input_handle.name(), \ "\" in a dataset function. You may need to initialize it " \ "explicitly before initializing an iterator that uses it."); \ } else if (!s.ok()) { \ return s; \ } \ TF_RETURN_IF_ERROR(device->resource_manager()->Create( \ input_handle.container(), input_handle.name(), resource)); \ continue; \ } for (size_t i = 0; i < captured_inputs.size(); ++i) { if (captured_inputs[i].dtype() == DT_RESOURCE) { // Extract the resource from `ctx->resource_manager()` and // insert it into `device->resource_manager()` so that it can be // used when the function executes. ResourceHandle input_handle = captured_inputs[i].scalar<ResourceHandle>()(); HANDLE_RESOURCE_TYPE(lookup::LookupInterface); HANDLE_RESOURCE_TYPE(QueueInterface); HANDLE_RESOURCE_TYPE(Var); return errors::Unimplemented( "Cannot currently capture resource '", ProtoDebugString(input_handle), "' in a dataset function (type not supported)."); } } #undef HANDLE_RESOURCE_TYPE std::unique_ptr<DeviceMgr> device_mgr(new DeviceMgr({device})); std::unique_ptr<FunctionLibraryDefinition> flib_def( new FunctionLibraryDefinition( *ctx->function_library()->GetFunctionLibraryDefinition())); std::unique_ptr<ProcessFunctionLibraryRuntime> pflr( new ProcessFunctionLibraryRuntime( device_mgr.get(), ctx->env(), graph_def_version, flib_def.get(), {} /* TODO(mrry): OptimizerOptions? */)); FunctionLibraryRuntime* lib = pflr->GetFLR(device->name()); FunctionLibraryRuntime::Handle f_handle; TF_RETURN_IF_ERROR( lib->Instantiate(func->name(), AttrSlice(&func->attr()), &f_handle)); out_function->reset(new CapturedFunction( device, std::move(device_mgr), std::move(flib_def), std::move(pflr), lib, f_handle, std::move(captured_inputs))); return Status::OK(); } Status CapturedFunction::Run(FunctionLibraryRuntime::Options f_opts, gtl::ArraySlice<Tensor> args, std::vector<Tensor>* rets, const string& prefix) { port::Tracing::TraceMe activity(prefix, "::Run"); Notification n; Status s; auto done_callback = [&n, &s](Status func_status) { s.Update(func_status); n.Notify(); }; // TODO(mrry): Add cancellation manager support to IteratorContext // so that we can cancel running map functions. The local // cancellation manager here is created so that we can run kernels // (such as queue kernels) that depend on the non-nullness // `OpKernelContext::cancellation_manager()`, but additional effort // will be required to plumb it through the `IteratorContext`. CancellationManager c_mgr; f_opts.cancellation_manager = &c_mgr; // TODO(mrry): Implement a synchronous version of // FunctionLibraryRuntime::Run() that avoids a context switch for small // functions. if (captured_inputs_.empty()) { lib_->Run(f_opts, f_handle_, args, rets, done_callback); } else { std::vector<Tensor> args_with_captured; args_with_captured.reserve(args.size() + captured_inputs_.size()); args_with_captured.insert(args_with_captured.end(), args.begin(), args.end()); args_with_captured.insert(args_with_captured.end(), captured_inputs_.begin(), captured_inputs_.end()); lib_->Run(f_opts, f_handle_, args_with_captured, rets, done_callback); } n.WaitForNotification(); return s; } CapturedFunction::CapturedFunction( Device* device, std::unique_ptr<DeviceMgr> device_mgr, std::unique_ptr<FunctionLibraryDefinition> flib_def, std::unique_ptr<ProcessFunctionLibraryRuntime> pflr, FunctionLibraryRuntime* lib, FunctionLibraryRuntime::Handle f_handle, std::vector<Tensor> captured_inputs) : device_(device), device_mgr_(std::move(device_mgr)), flib_def_(std::move(flib_def)), pflr_(std::move(pflr)), lib_(lib), f_handle_(f_handle), captured_inputs_(std::move(captured_inputs)) {} } // namespace tensorflow <|endoftext|>
<commit_before>/** * \file * \brief FifoQueuePriorityTestCase class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-12-14 */ #include "FifoQueuePriorityTestCase.hpp" #include "priorityTestPhases.hpp" #include "SequenceAsserter.hpp" #include "distortos/StaticThread.hpp" #include "distortos/StaticFifoQueue.hpp" #include "distortos/statistics.hpp" namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// size of stack for test thread, bytes constexpr size_t testThreadStackSize {256}; /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// pair of sequence points using SequencePoints = std::pair<unsigned int, unsigned int>; /// type of elements of \a TestFifoQueue using TestType = unsigned int; /// FifoQueue with \a TestType using TestFifoQueue = FifoQueue<TestType>; /// StaticFifoQueue with \a TestType, with storage for \a totalThreads elements using TestStaticFifoQueue = StaticFifoQueue<TestType, totalThreads>; /// type of test thread function using TestThreadFunction = void(SequenceAsserter&, SequencePoints, TestFifoQueue&); /// type of test thread using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, std::declval<TestThreadFunction>(), std::ref(std::declval<SequenceAsserter&>()), std::declval<SequencePoints>(), std::ref(std::declval<TestFifoQueue&>()))); /// function executed to prepare queue for test using Prepare = void(TestFifoQueue&); /// function executed on queue to trigger unblocking of test thread using Trigger = bool(TestFifoQueue&, size_t); /// function with final check of queue's contents after all test threads are terminated using FinalCheck = bool(TestFifoQueue&); /// tuple with functions for one stage, Prepare and FinalCheck may be nullptr using Stage = std::tuple<const TestThreadFunction&, const Prepare* const, const Trigger* const, const FinalCheck* const>; /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Final check for "pop" stage. * * The queue should contain "second" sequence points of test threads in the same order as expected by SequenceAsserter. * * \param [in] fifoQueue is a reference to shared FIFO queue * * \return true if final check check succeeded, false otherwise */ bool popFinalCheck(TestFifoQueue& fifoQueue) { for (size_t i = 0; i < totalThreads; ++i) { TestType testValue {}; const auto ret = fifoQueue.tryPop(testValue); if (ret != 0 || testValue != i + totalThreads) return false; } return true; } /** * \brief Prepares queue for "pop" stage - just fills it completely with increasing values. * * \param [in] fifoQueue is a reference to shared FIFO queue */ void popPrepare(TestFifoQueue& fifoQueue) { for (size_t i = 0; i < totalThreads; ++i) fifoQueue.tryPush(i); } /** * \brief FifoQueue::pop() test thread * * Marks the first sequence point in SequenceAsserter, waits for the last sequence point from FIFO queue and marks it in * SequenceAsserter. * * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object * \param [in] sequencePoints is a pair of sequence points for this instance (second one is ignored) * \param [in] fifoQueue is a reference to shared FIFO queue */ void popThread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints, TestFifoQueue& fifoQueue) { sequenceAsserter.sequencePoint(sequencePoints.first); unsigned int lastSequencePoint {}; fifoQueue.pop(lastSequencePoint); sequenceAsserter.sequencePoint(lastSequencePoint); } /** * \brief Trigger action with FifoQueue::pop(). * * \param [in] fifoQueue is a reference to shared FIFO queue * \param [in] i is the iteration counter * * \return true if trigger check succeeded, false otherwise */ bool popTrigger(TestFifoQueue& fifoQueue, const size_t i) { TestType testValue {}; fifoQueue.pop(testValue); return testValue == i; } /** * \brief FifoQueue::push() test thread * * Marks the first sequence point in SequenceAsserter, waits for free space in FIFO queue and marks last sequence point * in SequenceAsserter. * * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object * \param [in] sequencePoints is a pair of sequence points for this instance * \param [in] fifoQueue is a reference to shared FIFO queue */ void pushThread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints, TestFifoQueue& fifoQueue) { sequenceAsserter.sequencePoint(sequencePoints.first); fifoQueue.push(sequencePoints.second); sequenceAsserter.sequencePoint(sequencePoints.second); } /** * \brief Trigger action with FifoQueue::push(). * * \param [in] fifoQueue is a reference to shared FIFO queue * \param [in] i is the iteration counter * * \return true if trigger check succeeded, false otherwise */ bool pushTrigger(TestFifoQueue& fifoQueue, const size_t i) { fifoQueue.push(i + totalThreads); return true; } /** * \brief Builder of TestThread objects. * * \param [in] testThreadFunction is a reference to test thread function that will be used in TestThread * \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this * thread will be started * \param [in] threadParameters is a reference to ThreadParameters object * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object * \param [in] fifoQueue is a reference to shared FIFO queue * * \return constructed TestThread object */ TestThread makeTestThread(const TestThreadFunction& testThreadFunction, const unsigned int firstSequencePoint, const ThreadParameters& threadParameters, SequenceAsserter& sequenceAsserter, TestFifoQueue& fifoQueue) { return makeStaticThread<testThreadStackSize>(threadParameters.first, testThreadFunction, std::ref(sequenceAsserter), SequencePoints{firstSequencePoint, threadParameters.second + totalThreads}, std::ref(fifoQueue)); } /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// test stages const std::array<Stage, 2> stages {{ Stage{popThread, nullptr, pushTrigger, nullptr}, Stage{pushThread, popPrepare, popTrigger, popFinalCheck}, }}; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool FifoQueuePriorityTestCase::Implementation::run_() const { const auto contextSwitchCount = statistics::getContextSwitchCount(); std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {}; for (const auto& stage : stages) for (const auto& phase : priorityTestPhases) { SequenceAsserter sequenceAsserter; TestStaticFifoQueue fifoQueue; const auto& threadFunction = std::get<0>(stage); std::array<TestThread, totalThreads> threads {{ makeTestThread(threadFunction, 0, phase.first[phase.second[0]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 1, phase.first[phase.second[1]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 2, phase.first[phase.second[2]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 3, phase.first[phase.second[3]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 4, phase.first[phase.second[4]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 5, phase.first[phase.second[5]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 6, phase.first[phase.second[6]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 7, phase.first[phase.second[7]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 8, phase.first[phase.second[8]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 9, phase.first[phase.second[9]], sequenceAsserter, fifoQueue), }}; // execute Prepare if (std::get<1>(stage) != nullptr) std::get<1>(stage)(fifoQueue); bool result {true}; for (auto& thread : threads) { thread.start(); // 2 context switches: "into" the thread and "back" to main thread when test thread blocks on FIFO queue expectedContextSwitchCount += 2; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) result = false; } if (sequenceAsserter.assertSequence(totalThreads) == false) result = false; for (size_t i = 0; i < threads.size(); ++i) { std::get<2>(stage)(fifoQueue, i); // 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates expectedContextSwitchCount += 2; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) result = false; } for (auto& thread : threads) thread.join(); // execute FinalCheck if (std::get<3>(stage) != nullptr && std::get<3>(stage)(fifoQueue) == false) result = false; if (result == false || sequenceAsserter.assertSequence(totalThreads * 2) == false) return false; } if (statistics::getContextSwitchCount() - contextSwitchCount != 2 * 4 * totalThreads * priorityTestPhases.size()) return false; return true; } } // namespace test } // namespace distortos <commit_msg>test: comment fix in FifoQueuePriorityTestCase<commit_after>/** * \file * \brief FifoQueuePriorityTestCase class implementation * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2015-01-02 */ #include "FifoQueuePriorityTestCase.hpp" #include "priorityTestPhases.hpp" #include "SequenceAsserter.hpp" #include "distortos/StaticThread.hpp" #include "distortos/StaticFifoQueue.hpp" #include "distortos/statistics.hpp" namespace distortos { namespace test { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// size of stack for test thread, bytes constexpr size_t testThreadStackSize {256}; /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// pair of sequence points using SequencePoints = std::pair<unsigned int, unsigned int>; /// type of elements of \a TestFifoQueue using TestType = unsigned int; /// FifoQueue with \a TestType using TestFifoQueue = FifoQueue<TestType>; /// StaticFifoQueue with \a TestType, with storage for \a totalThreads elements using TestStaticFifoQueue = StaticFifoQueue<TestType, totalThreads>; /// type of test thread function using TestThreadFunction = void(SequenceAsserter&, SequencePoints, TestFifoQueue&); /// type of test thread using TestThread = decltype(makeStaticThread<testThreadStackSize>({}, std::declval<TestThreadFunction>(), std::ref(std::declval<SequenceAsserter&>()), std::declval<SequencePoints>(), std::ref(std::declval<TestFifoQueue&>()))); /// function executed to prepare queue for test using Prepare = void(TestFifoQueue&); /// function executed on queue to trigger unblocking of test thread using Trigger = bool(TestFifoQueue&, size_t); /// function with final check of queue's contents after all test threads are terminated using FinalCheck = bool(TestFifoQueue&); /// tuple with functions for one stage, Prepare and FinalCheck may be nullptr using Stage = std::tuple<const TestThreadFunction&, const Prepare* const, const Trigger* const, const FinalCheck* const>; /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Final check for "pop" stage. * * The queue should contain "second" sequence points of test threads in the same order as expected by SequenceAsserter. * * \param [in] fifoQueue is a reference to shared FIFO queue * * \return true if final check succeeded, false otherwise */ bool popFinalCheck(TestFifoQueue& fifoQueue) { for (size_t i = 0; i < totalThreads; ++i) { TestType testValue {}; const auto ret = fifoQueue.tryPop(testValue); if (ret != 0 || testValue != i + totalThreads) return false; } return true; } /** * \brief Prepares queue for "pop" stage - just fills it completely with increasing values. * * \param [in] fifoQueue is a reference to shared FIFO queue */ void popPrepare(TestFifoQueue& fifoQueue) { for (size_t i = 0; i < totalThreads; ++i) fifoQueue.tryPush(i); } /** * \brief FifoQueue::pop() test thread * * Marks the first sequence point in SequenceAsserter, waits for the last sequence point from FIFO queue and marks it in * SequenceAsserter. * * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object * \param [in] sequencePoints is a pair of sequence points for this instance (second one is ignored) * \param [in] fifoQueue is a reference to shared FIFO queue */ void popThread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints, TestFifoQueue& fifoQueue) { sequenceAsserter.sequencePoint(sequencePoints.first); unsigned int lastSequencePoint {}; fifoQueue.pop(lastSequencePoint); sequenceAsserter.sequencePoint(lastSequencePoint); } /** * \brief Trigger action with FifoQueue::pop(). * * \param [in] fifoQueue is a reference to shared FIFO queue * \param [in] i is the iteration counter * * \return true if trigger check succeeded, false otherwise */ bool popTrigger(TestFifoQueue& fifoQueue, const size_t i) { TestType testValue {}; fifoQueue.pop(testValue); return testValue == i; } /** * \brief FifoQueue::push() test thread * * Marks the first sequence point in SequenceAsserter, waits for free space in FIFO queue and marks last sequence point * in SequenceAsserter. * * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object * \param [in] sequencePoints is a pair of sequence points for this instance * \param [in] fifoQueue is a reference to shared FIFO queue */ void pushThread(SequenceAsserter& sequenceAsserter, const SequencePoints sequencePoints, TestFifoQueue& fifoQueue) { sequenceAsserter.sequencePoint(sequencePoints.first); fifoQueue.push(sequencePoints.second); sequenceAsserter.sequencePoint(sequencePoints.second); } /** * \brief Trigger action with FifoQueue::push(). * * \param [in] fifoQueue is a reference to shared FIFO queue * \param [in] i is the iteration counter * * \return true if trigger check succeeded, false otherwise */ bool pushTrigger(TestFifoQueue& fifoQueue, const size_t i) { fifoQueue.push(i + totalThreads); return true; } /** * \brief Builder of TestThread objects. * * \param [in] testThreadFunction is a reference to test thread function that will be used in TestThread * \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this * thread will be started * \param [in] threadParameters is a reference to ThreadParameters object * \param [in] sequenceAsserter is a reference to SequenceAsserter shared object * \param [in] fifoQueue is a reference to shared FIFO queue * * \return constructed TestThread object */ TestThread makeTestThread(const TestThreadFunction& testThreadFunction, const unsigned int firstSequencePoint, const ThreadParameters& threadParameters, SequenceAsserter& sequenceAsserter, TestFifoQueue& fifoQueue) { return makeStaticThread<testThreadStackSize>(threadParameters.first, testThreadFunction, std::ref(sequenceAsserter), SequencePoints{firstSequencePoint, threadParameters.second + totalThreads}, std::ref(fifoQueue)); } /*---------------------------------------------------------------------------------------------------------------------+ | local constants +---------------------------------------------------------------------------------------------------------------------*/ /// test stages const std::array<Stage, 2> stages {{ Stage{popThread, nullptr, pushTrigger, nullptr}, Stage{pushThread, popPrepare, popTrigger, popFinalCheck}, }}; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool FifoQueuePriorityTestCase::Implementation::run_() const { const auto contextSwitchCount = statistics::getContextSwitchCount(); std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {}; for (const auto& stage : stages) for (const auto& phase : priorityTestPhases) { SequenceAsserter sequenceAsserter; TestStaticFifoQueue fifoQueue; const auto& threadFunction = std::get<0>(stage); std::array<TestThread, totalThreads> threads {{ makeTestThread(threadFunction, 0, phase.first[phase.second[0]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 1, phase.first[phase.second[1]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 2, phase.first[phase.second[2]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 3, phase.first[phase.second[3]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 4, phase.first[phase.second[4]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 5, phase.first[phase.second[5]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 6, phase.first[phase.second[6]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 7, phase.first[phase.second[7]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 8, phase.first[phase.second[8]], sequenceAsserter, fifoQueue), makeTestThread(threadFunction, 9, phase.first[phase.second[9]], sequenceAsserter, fifoQueue), }}; // execute Prepare if (std::get<1>(stage) != nullptr) std::get<1>(stage)(fifoQueue); bool result {true}; for (auto& thread : threads) { thread.start(); // 2 context switches: "into" the thread and "back" to main thread when test thread blocks on FIFO queue expectedContextSwitchCount += 2; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) result = false; } if (sequenceAsserter.assertSequence(totalThreads) == false) result = false; for (size_t i = 0; i < threads.size(); ++i) { std::get<2>(stage)(fifoQueue, i); // 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates expectedContextSwitchCount += 2; if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount) result = false; } for (auto& thread : threads) thread.join(); // execute FinalCheck if (std::get<3>(stage) != nullptr && std::get<3>(stage)(fifoQueue) == false) result = false; if (result == false || sequenceAsserter.assertSequence(totalThreads * 2) == false) return false; } if (statistics::getContextSwitchCount() - contextSwitchCount != 2 * 4 * totalThreads * priorityTestPhases.size()) return false; return true; } } // namespace test } // namespace distortos <|endoftext|>
<commit_before> <commit_msg>Update Ngen.Content.Path.cpp<commit_after> #include <Ngen.hpp> namespace Ngen { namespace Content { _static tchar Path::PathSeperatorChar() { #if _tkn_Platform == _tknval_Platform_Windows return '/'; #else return '/'; #endif } } } class Path { public: static const string& SystemPathChar() const; static string GetLastNode(const string& node=const_string("/\|")); }; } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Common.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "Common.h" using namespace std; using namespace dev; namespace dev { char const* Version = "0.6.8c"; } <commit_msg>Version bump.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file Common.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 */ #include "Common.h" using namespace std; using namespace dev; namespace dev { char const* Version = "0.6.8d"; } <|endoftext|>
<commit_before> #include "Runtime.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <libevm/VM.h> #include "Type.h" namespace dev { namespace eth { namespace jit { llvm::StructType* RuntimeData::getType() { static llvm::StructType* type = nullptr; if (!type) { llvm::Type* elems[] = { llvm::ArrayType::get(Type::Word, _size), Type::BytePtr, Type::BytePtr, Type::BytePtr }; type = llvm::StructType::create(elems, "Runtime"); } return type; } namespace { llvm::Twine getName(RuntimeData::Index _index) { switch (_index) { default: return "data"; case RuntimeData::Gas: return "gas"; case RuntimeData::Address: return "address"; case RuntimeData::Caller: return "caller"; case RuntimeData::Origin: return "origin"; case RuntimeData::CallValue: return "callvalue"; case RuntimeData::CallDataSize: return "calldatasize"; case RuntimeData::GasPrice: return "gasprice"; case RuntimeData::PrevHash: return "prevhash"; case RuntimeData::CoinBase: return "coinbase"; case RuntimeData::TimeStamp: return "timestamp"; case RuntimeData::Number: return "number"; case RuntimeData::Difficulty: return "difficulty"; case RuntimeData::GasLimit: return "gaslimit"; case RuntimeData::CodeSize: return "codesize"; } } } Runtime::Runtime(u256 _gas, ExtVMFace& _ext, jmp_buf _jmpBuf): m_ext(_ext) { set(RuntimeData::Gas, _gas); set(RuntimeData::Address, fromAddress(_ext.myAddress)); set(RuntimeData::Caller, fromAddress(_ext.caller)); set(RuntimeData::Origin, fromAddress(_ext.origin)); set(RuntimeData::CallValue, _ext.value); set(RuntimeData::CallDataSize, _ext.data.size()); set(RuntimeData::GasPrice, _ext.gasPrice); set(RuntimeData::PrevHash, _ext.previousBlock.hash); set(RuntimeData::CoinBase, fromAddress(_ext.currentBlock.coinbaseAddress)); set(RuntimeData::TimeStamp, _ext.currentBlock.timestamp); set(RuntimeData::Number, _ext.currentBlock.number); set(RuntimeData::Difficulty, _ext.currentBlock.difficulty); set(RuntimeData::GasLimit, _ext.currentBlock.gasLimit); set(RuntimeData::CodeSize, _ext.code.size()); // TODO: Use constant m_data.callData = _ext.data.data(); m_data.code = _ext.code.data(); m_data.jmpBuf = _jmpBuf; } void Runtime::set(RuntimeData::Index _index, u256 _value) { m_data.elems[_index] = eth2llvm(_value); } u256 Runtime::getGas() const { return llvm2eth(m_data.elems[RuntimeData::Gas]); } bytesConstRef Runtime::getReturnData() const { // TODO: Handle large indexes auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset])); auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize])); assert(offset + size <= m_memory.size()); // TODO: Handle invalid data access by returning empty ref return {m_memory.data() + offset, size}; } RuntimeManager::RuntimeManager(llvm::IRBuilder<>& _builder): CompilerHelper(_builder) { m_dataPtr = new llvm::GlobalVariable(*getModule(), Type::RuntimePtr, false, llvm::GlobalVariable::PrivateLinkage, llvm::UndefValue::get(Type::RuntimePtr), "rt"); llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()}; m_longjmp = llvm::Function::Create(llvm::FunctionType::get(Type::Void, args, false), llvm::Function::ExternalLinkage, "longjmp", getModule()); // Export data auto mainFunc = getMainFunction(); llvm::Value* dataPtr = &mainFunc->getArgumentList().back(); m_builder.CreateStore(dataPtr, m_dataPtr); } llvm::Value* RuntimeManager::getRuntimePtr() { if (auto mainFunc = getMainFunction()) return mainFunc->arg_begin()->getNextNode(); // Runtime is the second parameter of main function return m_builder.CreateLoad(m_dataPtr, "rt"); } llvm::Value* RuntimeManager::getPtr(RuntimeData::Index _index) { llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(_index)}; return m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, getName(_index) + "Ptr"); } llvm::Value* RuntimeManager::get(RuntimeData::Index _index) { return m_builder.CreateLoad(getPtr(_index), getName(_index)); } void RuntimeManager::set(RuntimeData::Index _index, llvm::Value* _value) { m_builder.CreateStore(_value, getPtr(_index)); } void RuntimeManager::registerReturnData(llvm::Value* _offset, llvm::Value* _size) { set(RuntimeData::ReturnDataOffset, _offset); set(RuntimeData::ReturnDataSize, _size); } void RuntimeManager::raiseException(ReturnCode _returnCode) { m_builder.CreateCall2(m_longjmp, getJmpBuf(), Constant::get(_returnCode)); } llvm::Value* RuntimeManager::get(Instruction _inst) { switch (_inst) { default: assert(false); return nullptr; case Instruction::GAS: return get(RuntimeData::Gas); case Instruction::ADDRESS: return get(RuntimeData::Address); case Instruction::CALLER: return get(RuntimeData::Caller); case Instruction::ORIGIN: return get(RuntimeData::Origin); case Instruction::CALLVALUE: return get(RuntimeData::CallValue); case Instruction::CALLDATASIZE: return get(RuntimeData::CallDataSize); case Instruction::GASPRICE: return get(RuntimeData::GasPrice); case Instruction::PREVHASH: return get(RuntimeData::PrevHash); case Instruction::COINBASE: return get(RuntimeData::CoinBase); case Instruction::TIMESTAMP: return get(RuntimeData::TimeStamp); case Instruction::NUMBER: return get(RuntimeData::Number); case Instruction::DIFFICULTY: return get(RuntimeData::Difficulty); case Instruction::GASLIMIT: return get(RuntimeData::GasLimit); case Instruction::CODESIZE: return get(RuntimeData::CodeSize); } } llvm::Value* RuntimeManager::getCallData() { auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 1, "calldataPtr"); return getBuilder().CreateLoad(ptr, "calldata"); } llvm::Value* RuntimeManager::getCode() { auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 2, "codePtr"); return getBuilder().CreateLoad(ptr, "code"); } llvm::Value* RuntimeManager::getJmpBuf() { auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 3, "jmpbufPtr"); return getBuilder().CreateLoad(ptr, "jmpbuf"); } llvm::Value* RuntimeManager::getGas() { return get(RuntimeData::Gas); } void RuntimeManager::setGas(llvm::Value* _gas) { llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(RuntimeData::Gas)}; auto ptr = m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, "gasPtr"); m_builder.CreateStore(_gas, ptr); } } } } <commit_msg>Use llvm.longjmp intrinsic for longjmp [Delivers #81792986]<commit_after> #include "Runtime.h" #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Function.h> #include <llvm/IR/IntrinsicInst.h> #include <libevm/VM.h> #include "Type.h" namespace dev { namespace eth { namespace jit { llvm::StructType* RuntimeData::getType() { static llvm::StructType* type = nullptr; if (!type) { llvm::Type* elems[] = { llvm::ArrayType::get(Type::Word, _size), Type::BytePtr, Type::BytePtr, Type::BytePtr }; type = llvm::StructType::create(elems, "Runtime"); } return type; } namespace { llvm::Twine getName(RuntimeData::Index _index) { switch (_index) { default: return "data"; case RuntimeData::Gas: return "gas"; case RuntimeData::Address: return "address"; case RuntimeData::Caller: return "caller"; case RuntimeData::Origin: return "origin"; case RuntimeData::CallValue: return "callvalue"; case RuntimeData::CallDataSize: return "calldatasize"; case RuntimeData::GasPrice: return "gasprice"; case RuntimeData::PrevHash: return "prevhash"; case RuntimeData::CoinBase: return "coinbase"; case RuntimeData::TimeStamp: return "timestamp"; case RuntimeData::Number: return "number"; case RuntimeData::Difficulty: return "difficulty"; case RuntimeData::GasLimit: return "gaslimit"; case RuntimeData::CodeSize: return "codesize"; } } } Runtime::Runtime(u256 _gas, ExtVMFace& _ext, jmp_buf _jmpBuf): m_ext(_ext) { set(RuntimeData::Gas, _gas); set(RuntimeData::Address, fromAddress(_ext.myAddress)); set(RuntimeData::Caller, fromAddress(_ext.caller)); set(RuntimeData::Origin, fromAddress(_ext.origin)); set(RuntimeData::CallValue, _ext.value); set(RuntimeData::CallDataSize, _ext.data.size()); set(RuntimeData::GasPrice, _ext.gasPrice); set(RuntimeData::PrevHash, _ext.previousBlock.hash); set(RuntimeData::CoinBase, fromAddress(_ext.currentBlock.coinbaseAddress)); set(RuntimeData::TimeStamp, _ext.currentBlock.timestamp); set(RuntimeData::Number, _ext.currentBlock.number); set(RuntimeData::Difficulty, _ext.currentBlock.difficulty); set(RuntimeData::GasLimit, _ext.currentBlock.gasLimit); set(RuntimeData::CodeSize, _ext.code.size()); // TODO: Use constant m_data.callData = _ext.data.data(); m_data.code = _ext.code.data(); m_data.jmpBuf = _jmpBuf; } void Runtime::set(RuntimeData::Index _index, u256 _value) { m_data.elems[_index] = eth2llvm(_value); } u256 Runtime::getGas() const { return llvm2eth(m_data.elems[RuntimeData::Gas]); } bytesConstRef Runtime::getReturnData() const { // TODO: Handle large indexes auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset])); auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize])); assert(offset + size <= m_memory.size()); // TODO: Handle invalid data access by returning empty ref return {m_memory.data() + offset, size}; } RuntimeManager::RuntimeManager(llvm::IRBuilder<>& _builder): CompilerHelper(_builder) { m_dataPtr = new llvm::GlobalVariable(*getModule(), Type::RuntimePtr, false, llvm::GlobalVariable::PrivateLinkage, llvm::UndefValue::get(Type::RuntimePtr), "rt"); llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()}; m_longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::longjmp); // Export data auto mainFunc = getMainFunction(); llvm::Value* dataPtr = &mainFunc->getArgumentList().back(); m_builder.CreateStore(dataPtr, m_dataPtr); } llvm::Value* RuntimeManager::getRuntimePtr() { if (auto mainFunc = getMainFunction()) return mainFunc->arg_begin()->getNextNode(); // Runtime is the second parameter of main function return m_builder.CreateLoad(m_dataPtr, "rt"); } llvm::Value* RuntimeManager::getPtr(RuntimeData::Index _index) { llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(_index)}; return m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, getName(_index) + "Ptr"); } llvm::Value* RuntimeManager::get(RuntimeData::Index _index) { return m_builder.CreateLoad(getPtr(_index), getName(_index)); } void RuntimeManager::set(RuntimeData::Index _index, llvm::Value* _value) { m_builder.CreateStore(_value, getPtr(_index)); } void RuntimeManager::registerReturnData(llvm::Value* _offset, llvm::Value* _size) { set(RuntimeData::ReturnDataOffset, _offset); set(RuntimeData::ReturnDataSize, _size); } void RuntimeManager::raiseException(ReturnCode _returnCode) { m_builder.CreateCall2(m_longjmp, getJmpBuf(), Constant::get(_returnCode)); } llvm::Value* RuntimeManager::get(Instruction _inst) { switch (_inst) { default: assert(false); return nullptr; case Instruction::GAS: return get(RuntimeData::Gas); case Instruction::ADDRESS: return get(RuntimeData::Address); case Instruction::CALLER: return get(RuntimeData::Caller); case Instruction::ORIGIN: return get(RuntimeData::Origin); case Instruction::CALLVALUE: return get(RuntimeData::CallValue); case Instruction::CALLDATASIZE: return get(RuntimeData::CallDataSize); case Instruction::GASPRICE: return get(RuntimeData::GasPrice); case Instruction::PREVHASH: return get(RuntimeData::PrevHash); case Instruction::COINBASE: return get(RuntimeData::CoinBase); case Instruction::TIMESTAMP: return get(RuntimeData::TimeStamp); case Instruction::NUMBER: return get(RuntimeData::Number); case Instruction::DIFFICULTY: return get(RuntimeData::Difficulty); case Instruction::GASLIMIT: return get(RuntimeData::GasLimit); case Instruction::CODESIZE: return get(RuntimeData::CodeSize); } } llvm::Value* RuntimeManager::getCallData() { auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 1, "calldataPtr"); return getBuilder().CreateLoad(ptr, "calldata"); } llvm::Value* RuntimeManager::getCode() { auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 2, "codePtr"); return getBuilder().CreateLoad(ptr, "code"); } llvm::Value* RuntimeManager::getJmpBuf() { auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 3, "jmpbufPtr"); return getBuilder().CreateLoad(ptr, "jmpbuf"); } llvm::Value* RuntimeManager::getGas() { return get(RuntimeData::Gas); } void RuntimeManager::setGas(llvm::Value* _gas) { llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(RuntimeData::Gas)}; auto ptr = m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, "gasPtr"); m_builder.CreateStore(_gas, ptr); } } } } <|endoftext|>
<commit_before>#include <silicium/html/tree.hpp> #include <silicium/sink/iterator_sink.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(html_tree) { using namespace Si::html; auto document = tag("html", tag("head", tag("title", text("Title") ) ) + tag("body", text("Hello, ") + raw("<b>world</b>") + dynamic<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::unpaired_element(destination, "br"); })+ tag("input", detail::make_element<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::add_attribute(destination, "key", "value"); }), empty ) ) ); BOOST_CHECK_EQUAL(86u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<html><head><title>Title</title></head><body>Hello, <b>world</b><br/><input key=\"value\"/></body></html>", generated); } BOOST_AUTO_TEST_CASE(html_tree_attributes_of_unpaired_tag) { using namespace Si::html; auto document = tag("input", detail::make_element<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::add_attribute(destination, "key", "value"); }), empty ); BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<input key=\"value\"/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_attributes) { using namespace Si::html; auto document = tag("input", detail::make_element<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::add_attribute(destination, "key", "value"); }), text("content") ); BOOST_CHECK_EQUAL(22u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<input key=\"value\">content</input>", generated); } BOOST_AUTO_TEST_CASE(html_tree_one_attribute) { using namespace Si::html; auto document = tag("i", attribute("key", "value"), empty ); BOOST_CHECK_EQUAL(16u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<i key=\"value\"/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_two_attributes) { using namespace Si::html; auto document = tag("i", attribute("key", "value") + attribute("key2", "value2"), empty ); BOOST_CHECK_EQUAL(30u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<i key=\"value\" key2=\"value2\"/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_trait) { Si::html::Element<>::box const erased = Si::html::Element<>::make_box(Si::html::tag("test", Si::html::text("Hello"))); std::string generated; auto sink = Si::Sink<char, Si::success>::erase(Si::make_container_sink(generated)); erased.generate(sink); BOOST_CHECK_EQUAL("<test>Hello</test>", generated); } BOOST_AUTO_TEST_CASE(html_tree_produces_same_output_as_generator) { bool const build_triggered = true; std::vector<char> old_style_generated; auto html = Si::html::make_generator(Si::make_container_sink(old_style_generated)); html("html", [&] { html("head", [&] { html("title", [&] { html.write("Silicium build tester"); }); }); html("body", [&] { if (build_triggered) { html.write("build was triggered"); } html("form", [&] { html.attribute("action", "/"); html.attribute("method", "POST"); }, [&] { html("input", [&] { html.attribute("type", "submit"); html.attribute("value", "Trigger build"); }, Si::html::empty); }); }); }); using namespace Si::html; auto document = tag("html", tag("head", tag("title", text("Silicium build tester") ) ) + tag("body", dynamic<min_length<0>>([build_triggered](Si::Sink<char, Si::success>::interface &destination) { if (!build_triggered) { return; } text("build was triggered").generate(destination); }) + tag("form", attribute("action", "/") + attribute("method", "POST"), tag("input", attribute("type", "submit") + attribute("value", "Trigger build"), empty ) ) ) ); std::vector<char> new_style_generated = Si::html::generate<std::vector<char>>(document); BOOST_CHECK(old_style_generated == new_style_generated); } <commit_msg>more HTML tree tests<commit_after>#include <silicium/html/tree.hpp> #include <silicium/sink/iterator_sink.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(html_tree) { using namespace Si::html; auto document = tag("html", tag("head", tag("title", text("Title") ) ) + tag("body", text("Hello, ") + raw("<b>world</b>") + dynamic<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::unpaired_element(destination, "br"); })+ tag("input", detail::make_element<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::add_attribute(destination, "key", "value"); }), empty ) ) ); BOOST_CHECK_EQUAL(86u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<html><head><title>Title</title></head><body>Hello, <b>world</b><br/><input key=\"value\"/></body></html>", generated); } #if !SILICIUM_VC2013 BOOST_AUTO_TEST_CASE(html_tree_tag_without_attributes_argument) { using namespace Si::html; auto document = tag("a", empty); BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a/>", generated); } #endif BOOST_AUTO_TEST_CASE(html_tree_unpaired_tag) { using namespace Si::html; auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) { }); auto document = tag("a", no_attributes, empty); BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_paired_empty_tag) { using namespace Si::html; auto document = tag("a", dynamic<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) {})); BOOST_CHECK_EQUAL(7u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a></a>", generated); } BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_0) { using namespace Si::html; auto document = sequence(); BOOST_CHECK_EQUAL(0u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("", generated); } BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_1) { using namespace Si::html; auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) { }); auto document = sequence(tag("a", no_attributes, empty)); BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_2) { using namespace Si::html; auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) { }); auto document = sequence(tag("a", no_attributes, empty), tag("b", no_attributes, empty)); BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a/><b/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_3) { using namespace Si::html; auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) { }); auto document = sequence(tag("a", no_attributes, empty), tag("b", no_attributes, empty), tag("c", no_attributes, empty)); BOOST_CHECK_EQUAL(12u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a/><b/><c/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_tag_sum_of_tags_2) { using namespace Si::html; auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) { }); auto document = tag("a", no_attributes, empty) + tag("b", no_attributes, empty); BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a/><b/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_tag_sum_of_tags_3) { using namespace Si::html; auto no_attributes = detail::make_element<exact_length<0>>([](Si::Sink<char, Si::success>::interface &) { }); auto document = tag("a", no_attributes, empty) + tag("b", no_attributes, empty) + tag("c", no_attributes, empty); BOOST_CHECK_EQUAL(12u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<a/><b/><c/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_attributes_of_unpaired_tag) { using namespace Si::html; auto document = tag("input", detail::make_element<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::add_attribute(destination, "key", "value"); }), empty ); BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<input key=\"value\"/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_attributes) { using namespace Si::html; auto document = tag("input", detail::make_element<min_length<0>>([](Si::Sink<char, Si::success>::interface &destination) { Si::html::add_attribute(destination, "key", "value"); }), text("content") ); BOOST_CHECK_EQUAL(22u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<input key=\"value\">content</input>", generated); } BOOST_AUTO_TEST_CASE(html_tree_one_attribute) { using namespace Si::html; auto document = tag("i", attribute("key", "value"), empty ); BOOST_CHECK_EQUAL(16u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<i key=\"value\"/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_two_attributes) { using namespace Si::html; auto document = tag("i", attribute("key", "value") + attribute("key2", "value2"), empty ); BOOST_CHECK_EQUAL(30u, decltype(document)::length_type::value); std::string generated = generate<std::string>(document); BOOST_CHECK_EQUAL("<i key=\"value\" key2=\"value2\"/>", generated); } BOOST_AUTO_TEST_CASE(html_tree_trait) { Si::html::Element<>::box const erased = Si::html::Element<>::make_box(Si::html::tag("test", Si::html::text("Hello"))); std::string generated; auto sink = Si::Sink<char, Si::success>::erase(Si::make_container_sink(generated)); erased.generate(sink); BOOST_CHECK_EQUAL("<test>Hello</test>", generated); } BOOST_AUTO_TEST_CASE(html_tree_produces_same_output_as_generator) { bool const build_triggered = true; std::vector<char> old_style_generated; auto html = Si::html::make_generator(Si::make_container_sink(old_style_generated)); html("html", [&] { html("head", [&] { html("title", [&] { html.write("Silicium build tester"); }); }); html("body", [&] { if (build_triggered) { html.write("build was triggered"); } html("form", [&] { html.attribute("action", "/"); html.attribute("method", "POST"); }, [&] { html("input", [&] { html.attribute("type", "submit"); html.attribute("value", "Trigger build"); }, Si::html::empty); }); }); }); using namespace Si::html; auto document = tag("html", tag("head", tag("title", text("Silicium build tester") ) ) + tag("body", dynamic<min_length<0>>([build_triggered](Si::Sink<char, Si::success>::interface &destination) { if (!build_triggered) { return; } text("build was triggered").generate(destination); }) + tag("form", attribute("action", "/") + attribute("method", "POST"), tag("input", attribute("type", "submit") + attribute("value", "Trigger build"), empty ) ) ) ); std::vector<char> new_style_generated = Si::html::generate<std::vector<char>>(document); BOOST_CHECK(old_style_generated == new_style_generated); } <|endoftext|>
<commit_before>/* Copyright (c) 2018 ANON authors, see AUTHORS file. 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 "request_dispatcher.h" #include "percent_codec.h" // path "specs" look like this: // // some_host.com/some_partial_path/{thing_one}/some_more_partial_path/{thing_two}/maybe_even_more?queryName1&queryName2 request_helper request_mapping_helper(const std::string &path_spec) { std::string path, query, headers; pcrecpp::RE split_at_q("([^?]*)(.*)"); if (!split_at_q.FullMatch(path_spec, &path, &query)) anon_throw(std::runtime_error, "request_mapping failed, invalid path: " << path_spec); if (query.size() > 0) { if (!split_at_q.FullMatch(query.substr(1), &query, &headers)) anon_throw(std::runtime_error, "request_mapping failed, invalid path: " << path); if (headers.size() > 0) headers = headers.substr(1); } // firgure out how many {foo} statments are in the path pcrecpp::StringPiece input(path); int count = 0; pcrecpp::RE re1("({[^}]*})"); while (re1.FindAndConsume(&input)) ++count; // construct a regular expression for what we will be parsing // out of incomming uri's std::string newre_str = path; pcrecpp::RE("{[^}]*}").GlobalReplace("([^/]*)", &newre_str); request_helper h(newre_str, count); pcrecpp::RE split_at_and("([^&]+)"); if (query.size() > 0) { pcrecpp::StringPiece input(query); std::string val; while (split_at_and.FindAndConsume(&input, &val)) h.query_string_items.push_back(val); } if (headers.size() > 0) { pcrecpp::StringPiece input(headers); std::string val; while (split_at_and.FindAndConsume(&input, &val)) { h.header_items.push_back(val); } } pcrecpp::RE split_at_var("([^?{]*)(.*)"); if (!split_at_var.FullMatch(path_spec, &h.non_var)) anon_throw(std::runtime_error, "request_mapping failed, invalid path"); return h; } std::pair<bool, std::vector<std::string>> extract_params(const request_helper &h, const http_request &request, const std::string &path, const std::string &query, bool is_options) { auto ret = std::make_pair(false, std::vector<std::string>()); std::vector<std::string> p(8); bool match = false; switch (h.num_path_substitutions) { case 0: match = h.path_re.FullMatch(path); break; case 1: match = h.path_re.FullMatch(path, &p[0]); break; case 2: match = h.path_re.FullMatch(path, &p[0], &p[1]); break; case 3: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2]); break; case 4: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3]); break; case 5: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4]); break; case 6: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4], &p[5]); break; case 7: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &p[6]); break; case 8: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &p[6], &p[7]); break; default: break; } if (!match) return ret; for (auto &v : p) { if (v.size() == 0) break; ret.second.push_back(v); } if (ret.second.size() != h.num_path_substitutions) return ret; if (h.query_string_items.size() > 0) { auto quer = percent_decode(query); for (auto &it : h.query_string_items) { size_t pos = 0; auto skip_len = it.size() + 1; // for the "=" while (true) { pos = quer.find(it + "=", pos); if (pos == std::string::npos) break; if (pos == 0 || (quer[pos - 1] == '&')) break; pos = quer.find("&", pos + skip_len); } if (pos == std::string::npos) ret.second.push_back(""); else { auto v = quer.substr(pos + skip_len); ret.second.push_back(v.substr(0, v.find("&", 0))); } } } if (!is_options && h.header_items.size() > 0) { for (auto &it : h.header_items) { auto headers = request.headers; if (!headers.contains_header(it.c_str())) throw_request_error(HTTP_STATUS_BAD_REQUEST, "missing, required header: " << it); ret.second.push_back(headers.get_header(it.c_str()).str()); } } ret.first = true; return ret; } void respond_options(http_server::pipe_t &pipe, const http_request &request) { http_response response; response.add_header("access-control-allow-origin", "*"); std::ostringstream oss; oss << "OPTIONS, " << request.method_str(); response.add_header("access-control-allow-methods", oss.str()); response.add_header("access-control-allow-headers", "*"); response.set_status_code("204 No Content"); pipe.respond(response); } void request_dispatcher::dispatch(http_server::pipe_t &pipe, const http_request &request, bool is_tls) { request_wrap(pipe, [this, &pipe, &request, is_tls] { std::string method = request.method_str(); bool is_options = (_cors_enabled != 0) && (_options == method); auto path = request.get_url_field(UF_PATH); if (is_options) { if (path == "*" || path == "") { std::ostringstream oss; oss << "OPTIONS"; if (_cors_enabled & k_enable_cors_get) oss << ", GET"; if (_cors_enabled & k_enable_cors_head) oss << ", HEAD"; if (_cors_enabled & k_enable_cors_post) oss << ", POST"; if (_cors_enabled & k_enable_cors_put) oss << ", PUT"; if (_cors_enabled & k_enable_cors_delete) oss << ", DELETE"; http_response response; response.add_header("allow", oss.str()); response.set_status_code("204 No Content"); pipe.respond(response); return; } if (!request.headers.contains_header("access-control-request-method")) throw_request_error(HTTP_STATUS_BAD_REQUEST, "OPTIONS request missing required access-control-request-method header"); method = request.headers.get_header("access-control-request-method").str(); bool chk = false; if (method == "GET") chk = _cors_enabled & k_enable_cors_get; else if (method == "HEAD") chk = _cors_enabled & k_enable_cors_head; else if (method == "POST") chk = _cors_enabled & k_enable_cors_post; else if (method == "PUT") chk = _cors_enabled & k_enable_cors_put; else if (method == "DELETE") chk = _cors_enabled & k_enable_cors_put; if (!chk) throw_request_error(HTTP_STATUS_METHOD_NOT_ALLOWED, "method: " << method); } auto m = _map.find(method); if (m == _map.end()) throw_request_error(HTTP_STATUS_METHOD_NOT_ALLOWED, "method: " << method); auto query = request.get_url_field(UF_QUERY); auto e = m->second.upper_bound(path); if (e == m->second.begin()) throw_request_error(HTTP_STATUS_NOT_FOUND, "resource: \"" << path << "\" not found (1)"); --e; for (auto &f : e->second) { if (f(pipe, request, is_tls, path, query, is_options)) return; } throw_request_error(HTTP_STATUS_NOT_FOUND, "resource: \"" << path << "\" not found (2)"); }); }<commit_msg>debugging<commit_after>/* Copyright (c) 2018 ANON authors, see AUTHORS file. 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 "request_dispatcher.h" #include "percent_codec.h" // path "specs" look like this: // // some_host.com/some_partial_path/{thing_one}/some_more_partial_path/{thing_two}/maybe_even_more?queryName1&queryName2 request_helper request_mapping_helper(const std::string &path_spec) { std::string path, query, headers; pcrecpp::RE split_at_q("([^?]*)(.*)"); if (!split_at_q.FullMatch(path_spec, &path, &query)) anon_throw(std::runtime_error, "request_mapping failed, invalid path: " << path_spec); if (query.size() > 0) { if (!split_at_q.FullMatch(query.substr(1), &query, &headers)) anon_throw(std::runtime_error, "request_mapping failed, invalid path: " << path); if (headers.size() > 0) headers = headers.substr(1); } // firgure out how many {foo} statments are in the path pcrecpp::StringPiece input(path); int count = 0; pcrecpp::RE re1("({[^}]*})"); while (re1.FindAndConsume(&input)) ++count; // construct a regular expression for what we will be parsing // out of incomming uri's std::string newre_str = path; pcrecpp::RE("{[^}]*}").GlobalReplace("([^/]*)", &newre_str); request_helper h(newre_str, count); pcrecpp::RE split_at_and("([^&]+)"); if (query.size() > 0) { pcrecpp::StringPiece input(query); std::string val; while (split_at_and.FindAndConsume(&input, &val)) h.query_string_items.push_back(val); } if (headers.size() > 0) { pcrecpp::StringPiece input(headers); std::string val; while (split_at_and.FindAndConsume(&input, &val)) { h.header_items.push_back(val); } } pcrecpp::RE split_at_var("([^?{]*)(.*)"); if (!split_at_var.FullMatch(path_spec, &h.non_var)) anon_throw(std::runtime_error, "request_mapping failed, invalid path"); return h; } std::pair<bool, std::vector<std::string>> extract_params(const request_helper &h, const http_request &request, const std::string &path, const std::string &query, bool is_options) { auto ret = std::make_pair(false, std::vector<std::string>()); std::vector<std::string> p(8); bool match = false; switch (h.num_path_substitutions) { case 0: match = h.path_re.FullMatch(path); break; case 1: match = h.path_re.FullMatch(path, &p[0]); break; case 2: match = h.path_re.FullMatch(path, &p[0], &p[1]); break; case 3: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2]); break; case 4: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3]); break; case 5: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4]); break; case 6: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4], &p[5]); break; case 7: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &p[6]); break; case 8: match = h.path_re.FullMatch(path, &p[0], &p[1], &p[2], &p[3], &p[4], &p[5], &p[6], &p[7]); break; default: break; } if (!match) return ret; for (auto &v : p) { if (v.size() == 0) break; ret.second.push_back(v); } if (ret.second.size() != h.num_path_substitutions) return ret; if (h.query_string_items.size() > 0) { auto quer = percent_decode(query); for (auto &it : h.query_string_items) { size_t pos = 0; auto skip_len = it.size() + 1; // for the "=" while (true) { pos = quer.find(it + "=", pos); if (pos == std::string::npos) break; if (pos == 0 || (quer[pos - 1] == '&')) break; pos = quer.find("&", pos + skip_len); } if (pos == std::string::npos) ret.second.push_back(""); else { auto v = quer.substr(pos + skip_len); ret.second.push_back(v.substr(0, v.find("&", 0))); } } } if (!is_options && h.header_items.size() > 0) { for (auto &it : h.header_items) { auto headers = request.headers; if (!headers.contains_header(it.c_str())) throw_request_error(HTTP_STATUS_BAD_REQUEST, "missing, required header: " << it); ret.second.push_back(headers.get_header(it.c_str()).str()); } } ret.first = true; return ret; } void respond_options(http_server::pipe_t &pipe, const http_request &request) { http_response response; response.add_header("access-control-allow-origin", "*"); std::ostringstream oss; oss << "OPTIONS, " << request.headers.get_header("access-control-request-method").str(); response.add_header("access-control-allow-methods", oss.str()); response.add_header("access-control-allow-headers", "*"); response.set_status_code("204 No Content"); pipe.respond(response); } void request_dispatcher::dispatch(http_server::pipe_t &pipe, const http_request &request, bool is_tls) { request_wrap(pipe, [this, &pipe, &request, is_tls] { std::string method = request.method_str(); bool is_options = (_cors_enabled != 0) && (_options == method); auto path = request.get_url_field(UF_PATH); if (is_options) { if (path == "*" || path == "") { std::ostringstream oss; oss << "OPTIONS"; if (_cors_enabled & k_enable_cors_get) oss << ", GET"; if (_cors_enabled & k_enable_cors_head) oss << ", HEAD"; if (_cors_enabled & k_enable_cors_post) oss << ", POST"; if (_cors_enabled & k_enable_cors_put) oss << ", PUT"; if (_cors_enabled & k_enable_cors_delete) oss << ", DELETE"; http_response response; response.add_header("allow", oss.str()); response.set_status_code("204 No Content"); pipe.respond(response); return; } if (!request.headers.contains_header("access-control-request-method")) throw_request_error(HTTP_STATUS_BAD_REQUEST, "OPTIONS request missing required access-control-request-method header"); method = request.headers.get_header("access-control-request-method").str(); bool chk = false; if (method == "GET") chk = _cors_enabled & k_enable_cors_get; else if (method == "HEAD") chk = _cors_enabled & k_enable_cors_head; else if (method == "POST") chk = _cors_enabled & k_enable_cors_post; else if (method == "PUT") chk = _cors_enabled & k_enable_cors_put; else if (method == "DELETE") chk = _cors_enabled & k_enable_cors_put; if (!chk) throw_request_error(HTTP_STATUS_METHOD_NOT_ALLOWED, "method: " << method); } auto m = _map.find(method); if (m == _map.end()) throw_request_error(HTTP_STATUS_METHOD_NOT_ALLOWED, "method: " << method); auto query = request.get_url_field(UF_QUERY); auto e = m->second.upper_bound(path); if (e == m->second.begin()) throw_request_error(HTTP_STATUS_NOT_FOUND, "resource: \"" << path << "\" not found (1)"); --e; for (auto &f : e->second) { if (f(pipe, request, is_tls, path, query, is_options)) return; } throw_request_error(HTTP_STATUS_NOT_FOUND, "resource: \"" << path << "\" not found (2)"); }); }<|endoftext|>
<commit_before>/* This file is part of libkcal. Copyright (c) 2001,2004 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <klocale.h> #include <kdebug.h> #include <kstandarddirs.h> #include "event.h" #include "todo.h" #include "freebusy.h" #include "icalformat.h" #include "calendar.h" #include "freebusycache.h" #include "scheduler.h" using namespace KCal; ScheduleMessage::ScheduleMessage(IncidenceBase *incidence,int method,ScheduleMessage::Status status) { mIncidence = incidence; mMethod = method; mStatus = status; } QString ScheduleMessage::statusName(ScheduleMessage::Status status) { switch (status) { case PublishUpdate: return i18n("Updated Publish"); case PublishNew: return i18n("Publish"); case Obsolete: return i18n("Obsolete"); case RequestNew: return i18n("New Request"); case RequestUpdate: return i18n("Updated Request"); default: return i18n("Unknown Status: %1").arg(QString::number(status)); } } struct Scheduler::Private { Private() : mFreeBusyCache( 0 ) {} FreeBusyCache *mFreeBusyCache; }; Scheduler::Scheduler(Calendar *calendar) { mCalendar = calendar; mFormat = new ICalFormat(); mFormat->setTimeZone( calendar->timeZoneId(), !calendar->isLocalTime() ); d = new Private; } Scheduler::~Scheduler() { delete d; delete mFormat; } void Scheduler::setFreeBusyCache( FreeBusyCache *c ) { d->mFreeBusyCache = c; } FreeBusyCache *Scheduler::freeBusyCache() const { return d->mFreeBusyCache; } bool Scheduler::acceptTransaction(IncidenceBase *incidence,Method method,ScheduleMessage::Status status) { kdDebug(5800) << "Scheduler::acceptTransaction, method=" << methodName( method ) << endl; switch (method) { case Publish: return acceptPublish(incidence, status, method); case Request: return acceptRequest(incidence, status); case Add: return acceptAdd(incidence, status); case Cancel: return acceptCancel(incidence, status); case Declinecounter: return acceptDeclineCounter(incidence, status); case Reply: return acceptReply(incidence, status, method); case Refresh: return acceptRefresh(incidence, status); case Counter: return acceptCounter(incidence, status); default: break; } deleteTransaction(incidence); return false; } QString Scheduler::methodName(Method method) { switch (method) { case Publish: return QString::fromLatin1("Publish"); case Request: return QString::fromLatin1("Request"); case Refresh: return QString::fromLatin1("Refresh"); case Cancel: return QString::fromLatin1("Cancel"); case Add: return QString::fromLatin1("Add"); case Reply: return QString::fromLatin1("Reply"); case Counter: return QString::fromLatin1("Counter"); case Declinecounter: return QString::fromLatin1("Decline Counter"); default: return QString::fromLatin1("Unknown"); } } QString Scheduler::translatedMethodName(Method method) { switch (method) { case Publish: return i18n("Publish"); case Request: return i18n("Request"); case Refresh: return i18n("Refresh"); case Cancel: return i18n("Cancel"); case Add: return i18n("Add"); case Reply: return i18n("Reply"); case Counter: return i18n("counter proposal","Counter"); case Declinecounter: return i18n("decline counter proposal","Decline Counter"); default: return i18n("Unknown"); } } bool Scheduler::deleteTransaction(IncidenceBase *) { return true; } bool Scheduler::acceptPublish( IncidenceBase *newIncBase, ScheduleMessage::Status status, Method method ) { if( newIncBase->type() == "FreeBusy" ) { return acceptFreeBusy( newIncBase, method ); } bool res = false; kdDebug(5800) << "Scheduler::acceptPublish, status=" << ScheduleMessage::statusName( status ) << endl; Incidence *newInc = static_cast<Incidence *>( newIncBase ); Incidence *calInc = mCalendar->incidence( newIncBase->uid() ); switch ( status ) { case ScheduleMessage::Unknown: case ScheduleMessage::PublishNew: case ScheduleMessage::PublishUpdate: res = true; if ( calInc ) { if ( (newInc->revision() > calInc->revision()) || (newInc->revision() == calInc->revision() && newInc->lastModified() > calInc->lastModified() ) ) { mCalendar->deleteIncidence( calInc ); } else res = false; } if ( res ) mCalendar->addIncidence( newInc ); break; case ScheduleMessage::Obsolete: res = true; break; default: break; } deleteTransaction( newIncBase ); return res; } bool Scheduler::acceptRequest(IncidenceBase *newIncBase, ScheduleMessage::Status /* status */) { if (newIncBase->type()=="FreeBusy") { // reply to this request is handled in korganizer's incomingdialog return true; } Incidence *newInc = dynamic_cast<Incidence *>( newIncBase ); if ( newInc ) { bool res = true; Incidence *exInc = mCalendar->incidenceFromSchedulingID( newIncBase->uid() ); if ( exInc ) { res = false; if ( (newInc->revision() > exInc->revision()) || (newInc->revision() == exInc->revision() && newInc->lastModified()>exInc->lastModified()) ) { mCalendar->deleteIncidence( exInc ); res = true; } } if ( res ) { // Move the uid to be the schedulingID and make a unique UID newInc->setSchedulingID( newInc->uid() ); newInc->setUid( CalFormat::createUniqueId() ); mCalendar->addIncidence(newInc); } deleteTransaction( newIncBase ); return res; } return false; } bool Scheduler::acceptAdd(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { deleteTransaction(incidence); return false; } bool Scheduler::acceptCancel(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { bool ret = false; Incidence *inc = mCalendar->incidence( incidence->uid() ); if ( inc ) { mCalendar->deleteIncidence( inc ); ret = true; } deleteTransaction(incidence); return ret; } bool Scheduler::acceptDeclineCounter(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { deleteTransaction(incidence); return false; } //bool Scheduler::acceptFreeBusy(Incidence *incidence,ScheduleMessage::Status status) //{ // deleteTransaction(incidence); // return false; //} bool Scheduler::acceptReply(IncidenceBase *incidence,ScheduleMessage::Status /* status */, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } bool ret = false; Event *ev = mCalendar->event(incidence->uid()); Todo *to = mCalendar->todo(incidence->uid()); if (ev || to) { //get matching attendee in calendar kdDebug(5800) << "Scheduler::acceptTransaction match found!" << endl; Attendee::List attendeesIn = incidence->attendees(); Attendee::List attendeesEv; if (ev) attendeesEv = ev->attendees(); if (to) attendeesEv = to->attendees(); Attendee::List::ConstIterator inIt; Attendee::List::ConstIterator evIt; for ( inIt = attendeesIn.begin(); inIt != attendeesIn.end(); ++inIt ) { Attendee *attIn = *inIt; for ( evIt = attendeesEv.begin(); evIt != attendeesEv.end(); ++evIt ) { Attendee *attEv = *evIt; if (attIn->email().lower()==attEv->email().lower()) { //update attendee-info kdDebug(5800) << "Scheduler::acceptTransaction update attendee" << endl; attEv->setStatus(attIn->status()); ret = true; } } } if ( ret ) { // We set at least one of the attendees, so the incidence changed // Note: This should not result in a sequence number bump if ( ev ) ev->updated(); else if ( to ) to->updated(); } } else kdError(5800) << "No incidence for scheduling\n"; if (ret) deleteTransaction(incidence); return ret; } bool Scheduler::acceptRefresh(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { // handled in korganizer's IncomingDialog deleteTransaction(incidence); return false; } bool Scheduler::acceptCounter(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { deleteTransaction(incidence); return false; } bool Scheduler::acceptFreeBusy(IncidenceBase *incidence, Method method) { if ( !d->mFreeBusyCache ) { kdError() << "KCal::Scheduler: no FreeBusyCache." << endl; return false; } FreeBusy *freebusy = static_cast<FreeBusy *>(incidence); kdDebug(5800) << "acceptFreeBusy:: freeBusyDirName: " << freeBusyDir() << endl; Person from; if(method == Scheduler::Publish) { from = freebusy->organizer(); } if((method == Scheduler::Reply) && (freebusy->attendeeCount() == 1)) { Attendee *attendee = freebusy->attendees().first(); from = attendee->email(); } if ( !d->mFreeBusyCache->saveFreeBusy( freebusy, from ) ) return false; deleteTransaction(incidence); return true; } <commit_msg>Handle incoming updates of completion status in vtodos.<commit_after>/* This file is part of libkcal. Copyright (c) 2001,2004 Cornelius Schumacher <schumacher@kde.org> Copyright (C) 2004 Reinhold Kainhofer <reinhold@kainhofer.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qdir.h> #include <qfile.h> #include <qtextstream.h> #include <klocale.h> #include <kdebug.h> #include <kstandarddirs.h> #include "event.h" #include "todo.h" #include "freebusy.h" #include "icalformat.h" #include "calendar.h" #include "freebusycache.h" #include "scheduler.h" using namespace KCal; ScheduleMessage::ScheduleMessage(IncidenceBase *incidence,int method,ScheduleMessage::Status status) { mIncidence = incidence; mMethod = method; mStatus = status; } QString ScheduleMessage::statusName(ScheduleMessage::Status status) { switch (status) { case PublishUpdate: return i18n("Updated Publish"); case PublishNew: return i18n("Publish"); case Obsolete: return i18n("Obsolete"); case RequestNew: return i18n("New Request"); case RequestUpdate: return i18n("Updated Request"); default: return i18n("Unknown Status: %1").arg(QString::number(status)); } } struct Scheduler::Private { Private() : mFreeBusyCache( 0 ) {} FreeBusyCache *mFreeBusyCache; }; Scheduler::Scheduler(Calendar *calendar) { mCalendar = calendar; mFormat = new ICalFormat(); mFormat->setTimeZone( calendar->timeZoneId(), !calendar->isLocalTime() ); d = new Private; } Scheduler::~Scheduler() { delete d; delete mFormat; } void Scheduler::setFreeBusyCache( FreeBusyCache *c ) { d->mFreeBusyCache = c; } FreeBusyCache *Scheduler::freeBusyCache() const { return d->mFreeBusyCache; } bool Scheduler::acceptTransaction(IncidenceBase *incidence,Method method,ScheduleMessage::Status status) { kdDebug(5800) << "Scheduler::acceptTransaction, method=" << methodName( method ) << endl; switch (method) { case Publish: return acceptPublish(incidence, status, method); case Request: return acceptRequest(incidence, status); case Add: return acceptAdd(incidence, status); case Cancel: return acceptCancel(incidence, status); case Declinecounter: return acceptDeclineCounter(incidence, status); case Reply: return acceptReply(incidence, status, method); case Refresh: return acceptRefresh(incidence, status); case Counter: return acceptCounter(incidence, status); default: break; } deleteTransaction(incidence); return false; } QString Scheduler::methodName(Method method) { switch (method) { case Publish: return QString::fromLatin1("Publish"); case Request: return QString::fromLatin1("Request"); case Refresh: return QString::fromLatin1("Refresh"); case Cancel: return QString::fromLatin1("Cancel"); case Add: return QString::fromLatin1("Add"); case Reply: return QString::fromLatin1("Reply"); case Counter: return QString::fromLatin1("Counter"); case Declinecounter: return QString::fromLatin1("Decline Counter"); default: return QString::fromLatin1("Unknown"); } } QString Scheduler::translatedMethodName(Method method) { switch (method) { case Publish: return i18n("Publish"); case Request: return i18n("Request"); case Refresh: return i18n("Refresh"); case Cancel: return i18n("Cancel"); case Add: return i18n("Add"); case Reply: return i18n("Reply"); case Counter: return i18n("counter proposal","Counter"); case Declinecounter: return i18n("decline counter proposal","Decline Counter"); default: return i18n("Unknown"); } } bool Scheduler::deleteTransaction(IncidenceBase *) { return true; } bool Scheduler::acceptPublish( IncidenceBase *newIncBase, ScheduleMessage::Status status, Method method ) { if( newIncBase->type() == "FreeBusy" ) { return acceptFreeBusy( newIncBase, method ); } bool res = false; kdDebug(5800) << "Scheduler::acceptPublish, status=" << ScheduleMessage::statusName( status ) << endl; Incidence *newInc = static_cast<Incidence *>( newIncBase ); Incidence *calInc = mCalendar->incidence( newIncBase->uid() ); switch ( status ) { case ScheduleMessage::Unknown: case ScheduleMessage::PublishNew: case ScheduleMessage::PublishUpdate: res = true; if ( calInc ) { if ( (newInc->revision() > calInc->revision()) || (newInc->revision() == calInc->revision() && newInc->lastModified() > calInc->lastModified() ) ) { mCalendar->deleteIncidence( calInc ); } else res = false; } if ( res ) mCalendar->addIncidence( newInc ); break; case ScheduleMessage::Obsolete: res = true; break; default: break; } deleteTransaction( newIncBase ); return res; } bool Scheduler::acceptRequest(IncidenceBase *newIncBase, ScheduleMessage::Status /* status */) { if (newIncBase->type()=="FreeBusy") { // reply to this request is handled in korganizer's incomingdialog return true; } Incidence *newInc = dynamic_cast<Incidence *>( newIncBase ); if ( newInc ) { bool res = true; Incidence *exInc = mCalendar->incidenceFromSchedulingID( newIncBase->uid() ); if ( exInc ) { res = false; if ( (newInc->revision() > exInc->revision()) || (newInc->revision() == exInc->revision() && newInc->lastModified()>exInc->lastModified()) ) { mCalendar->deleteIncidence( exInc ); res = true; } } if ( res ) { // Move the uid to be the schedulingID and make a unique UID newInc->setSchedulingID( newInc->uid() ); newInc->setUid( CalFormat::createUniqueId() ); mCalendar->addIncidence(newInc); } deleteTransaction( newIncBase ); return res; } return false; } bool Scheduler::acceptAdd(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { deleteTransaction(incidence); return false; } bool Scheduler::acceptCancel(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { bool ret = false; Incidence *inc = mCalendar->incidence( incidence->uid() ); if ( inc ) { mCalendar->deleteIncidence( inc ); ret = true; } deleteTransaction(incidence); return ret; } bool Scheduler::acceptDeclineCounter(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { deleteTransaction(incidence); return false; } //bool Scheduler::acceptFreeBusy(Incidence *incidence,ScheduleMessage::Status status) //{ // deleteTransaction(incidence); // return false; //} bool Scheduler::acceptReply(IncidenceBase *incidence,ScheduleMessage::Status /* status */, Method method) { if(incidence->type()=="FreeBusy") { return acceptFreeBusy(incidence, method); } bool ret = false; Event *ev = mCalendar->event(incidence->uid()); Todo *to = mCalendar->todo(incidence->uid()); if (ev || to) { //get matching attendee in calendar kdDebug(5800) << "Scheduler::acceptTransaction match found!" << endl; Attendee::List attendeesIn = incidence->attendees(); Attendee::List attendeesEv; if (ev) attendeesEv = ev->attendees(); if (to) attendeesEv = to->attendees(); Attendee::List::ConstIterator inIt; Attendee::List::ConstIterator evIt; for ( inIt = attendeesIn.begin(); inIt != attendeesIn.end(); ++inIt ) { Attendee *attIn = *inIt; for ( evIt = attendeesEv.begin(); evIt != attendeesEv.end(); ++evIt ) { Attendee *attEv = *evIt; if (attIn->email().lower()==attEv->email().lower()) { //update attendee-info kdDebug(5800) << "Scheduler::acceptTransaction update attendee" << endl; attEv->setStatus(attIn->status()); ret = true; } } } if ( ret ) { // We set at least one of the attendees, so the incidence changed // Note: This should not result in a sequence number bump if ( ev ) ev->updated(); else if ( to ) to->updated(); } if ( to ) { // for VTODO a REPLY can be used to update the completion status of // a task. see RFC2446 3.4.3 Todo *update = dynamic_cast<Todo*> ( incidence ); Q_ASSERT( update ); if ( update && ( to->percentComplete() != update->percentComplete() ) ) { to->setPercentComplete( update->percentComplete() ); to->updated(); } } } else kdError(5800) << "No incidence for scheduling\n"; if (ret) deleteTransaction(incidence); return ret; } bool Scheduler::acceptRefresh(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { // handled in korganizer's IncomingDialog deleteTransaction(incidence); return false; } bool Scheduler::acceptCounter(IncidenceBase *incidence,ScheduleMessage::Status /* status */) { deleteTransaction(incidence); return false; } bool Scheduler::acceptFreeBusy(IncidenceBase *incidence, Method method) { if ( !d->mFreeBusyCache ) { kdError() << "KCal::Scheduler: no FreeBusyCache." << endl; return false; } FreeBusy *freebusy = static_cast<FreeBusy *>(incidence); kdDebug(5800) << "acceptFreeBusy:: freeBusyDirName: " << freeBusyDir() << endl; Person from; if(method == Scheduler::Publish) { from = freebusy->organizer(); } if((method == Scheduler::Reply) && (freebusy->attendeeCount() == 1)) { Attendee *attendee = freebusy->attendees().first(); from = attendee->email(); } if ( !d->mFreeBusyCache->saveFreeBusy( freebusy, from ) ) return false; deleteTransaction(incidence); return true; } <|endoftext|>
<commit_before>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include "SP3EphemerisStore.hpp" #include "BCEphemerisStore.hpp" #include "RinexNavStream.hpp" #include "RinexNavData.hpp" #include "FICStream.hpp" #include "FICData.hpp" #include "EphReader.hpp" #include "FFIdentifier.hpp" using namespace std; using namespace gpstk; // --------------------------------------------------------------------- // --------------------------------------------------------------------- void EphReader::read(const std::string& fn) { FFIdentifier ffid(fn); switch (ffid) { case FFIdentifier::tRinexNav: read_rinex_nav_data(fn); break; case FFIdentifier::tFIC: read_fic_data(fn); break; case FFIdentifier::tSP3: read_sp3_data(fn); break; default: if (verboseLevel) cout << "# Could not determine the format of " << fn << endl; } filesRead.push_back(fn); if (verboseLevel>1) cout << "# Ephemers initial time: " << eph->getInitialTime() << ", final time: " << eph->getFinalTime() << endl; } // end of read() // --------------------------------------------------------------------- // Read in ephemeris data in rinex format // --------------------------------------------------------------------- void EphReader::read_rinex_nav_data(const string& fn) { BCEphemerisStore* bce; if (eph == NULL) { bce = new(BCEphemerisStore); eph = dynamic_cast<EphemerisStore*>(bce); } else { if (typeid(*eph) != typeid(BCEphemerisStore)) throw(FFStreamError("Don't mix nav data types...")); bce = dynamic_cast<BCEphemerisStore*>(eph); } if (verboseLevel>2) cout << "# Reading " << fn << " as RINEX nav."<< endl; RinexNavStream rns(fn.c_str(), ios::in); rns.exceptions(ifstream::failbit); RinexNavData rnd; while (rns >> rnd) bce->addEphemeris(rnd); if (verboseLevel>1) cout << "# Read " << fn << " as RINEX nav. " << endl; } // end of read_rinex_nav_data() void EphReader::read_fic_data(const string& fn) { BCEphemerisStore* bce; if (eph == NULL) { bce = new(BCEphemerisStore); eph = dynamic_cast<EphemerisStore*>(bce); } else { if (typeid(*eph) != typeid(BCEphemerisStore)) throw(FFStreamError("Don't mix nav data types...")); bce = dynamic_cast<BCEphemerisStore*>(eph); } if (verboseLevel>2) cout << "# Reading " << fn << " as FIC nav."<< endl; FICStream fs(fn.c_str(), ios::in); FICHeader header; fs >> header; FICData data; while(fs >> data) if (data.blockNum==9) // Only look at the eng ephemeris bce->addEphemeris(data); if (verboseLevel>1) cout << "# Read " << fn << " as FIC nav."<< endl; } // end of read_fic_data() void EphReader::read_sp3_data(const string& fn) { SP3EphemerisStore* pe; if (eph == NULL) { pe = new(SP3EphemerisStore); eph = dynamic_cast<EphemerisStore*>(pe); } else { if (typeid(*eph) != typeid(SP3EphemerisStore)) throw(FFStreamError("Don't mix nav data types...")); pe = dynamic_cast<SP3EphemerisStore*>(eph); } if (verboseLevel>2) cout << "# Reading " << fn << " as SP3 ephemeris."<< endl; SP3Stream pefile(fn.c_str(),ios::in); pefile.exceptions(ifstream::failbit); SP3Header header; pefile >> header; SP3Data data; while(pefile >> data) pe->addEphemeris(data); if (verboseLevel>1) cout << "# Read " << fn << " as SP3 ephemeris."<< endl; } // end of read_sp3_data() <commit_msg>"Ephemeris" not "Ephemers" in output.<commit_after>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include "SP3EphemerisStore.hpp" #include "BCEphemerisStore.hpp" #include "RinexNavStream.hpp" #include "RinexNavData.hpp" #include "FICStream.hpp" #include "FICData.hpp" #include "EphReader.hpp" #include "FFIdentifier.hpp" using namespace std; using namespace gpstk; // --------------------------------------------------------------------- // --------------------------------------------------------------------- void EphReader::read(const std::string& fn) { FFIdentifier ffid(fn); switch (ffid) { case FFIdentifier::tRinexNav: read_rinex_nav_data(fn); break; case FFIdentifier::tFIC: read_fic_data(fn); break; case FFIdentifier::tSP3: read_sp3_data(fn); break; default: if (verboseLevel) cout << "# Could not determine the format of " << fn << endl; } filesRead.push_back(fn); if (verboseLevel>1) cout << "# Ephemeris initial time: " << eph->getInitialTime() << ", final time: " << eph->getFinalTime() << endl; } // end of read() // --------------------------------------------------------------------- // Read in ephemeris data in rinex format // --------------------------------------------------------------------- void EphReader::read_rinex_nav_data(const string& fn) { BCEphemerisStore* bce; if (eph == NULL) { bce = new(BCEphemerisStore); eph = dynamic_cast<EphemerisStore*>(bce); } else { if (typeid(*eph) != typeid(BCEphemerisStore)) throw(FFStreamError("Don't mix nav data types...")); bce = dynamic_cast<BCEphemerisStore*>(eph); } if (verboseLevel>2) cout << "# Reading " << fn << " as RINEX nav."<< endl; RinexNavStream rns(fn.c_str(), ios::in); rns.exceptions(ifstream::failbit); RinexNavData rnd; while (rns >> rnd) bce->addEphemeris(rnd); if (verboseLevel>1) cout << "# Read " << fn << " as RINEX nav. " << endl; } // end of read_rinex_nav_data() void EphReader::read_fic_data(const string& fn) { BCEphemerisStore* bce; if (eph == NULL) { bce = new(BCEphemerisStore); eph = dynamic_cast<EphemerisStore*>(bce); } else { if (typeid(*eph) != typeid(BCEphemerisStore)) throw(FFStreamError("Don't mix nav data types...")); bce = dynamic_cast<BCEphemerisStore*>(eph); } if (verboseLevel>2) cout << "# Reading " << fn << " as FIC nav."<< endl; FICStream fs(fn.c_str(), ios::in); FICHeader header; fs >> header; FICData data; while(fs >> data) if (data.blockNum==9) // Only look at the eng ephemeris bce->addEphemeris(data); if (verboseLevel>1) cout << "# Read " << fn << " as FIC nav."<< endl; } // end of read_fic_data() void EphReader::read_sp3_data(const string& fn) { SP3EphemerisStore* pe; if (eph == NULL) { pe = new(SP3EphemerisStore); eph = dynamic_cast<EphemerisStore*>(pe); } else { if (typeid(*eph) != typeid(SP3EphemerisStore)) throw(FFStreamError("Don't mix nav data types...")); pe = dynamic_cast<SP3EphemerisStore*>(eph); } if (verboseLevel>2) cout << "# Reading " << fn << " as SP3 ephemeris."<< endl; SP3Stream pefile(fn.c_str(),ios::in); pefile.exceptions(ifstream::failbit); SP3Header header; pefile >> header; SP3Data data; while(pefile >> data) pe->addEphemeris(data); if (verboseLevel>1) cout << "# Read " << fn << " as SP3 ephemeris."<< endl; } // end of read_sp3_data() <|endoftext|>
<commit_before>#include "inc/cxx/json.hpp" #include "test/catch.hpp" #include "test/utils.hpp" #include <type_traits> using namespace std::string_literals; using namespace test::literals; TEST_CASE("can default construct cxx::json") { static_assert(std::is_nothrow_default_constructible_v<cxx::json>); cxx::json const json; REQUIRE(cxx::holds_alternative<cxx::json::document>(json)); REQUIRE(std::size(json) == 0); } TEST_CASE("can copy construct cxx::json") { static_assert(std::is_copy_constructible_v<cxx::json>); cxx::json const orig; cxx::json const copy(orig); REQUIRE(cxx::holds_alternative<cxx::json::document>(orig)); REQUIRE(cxx::holds_alternative<cxx::json::document>(copy)); REQUIRE(orig == copy); } TEST_CASE("can move construct cxx::json") { static_assert(std::is_nothrow_move_constructible_v<cxx::json>); cxx::json orig; cxx::json const copy(std::move(orig)); REQUIRE(cxx::holds_alternative<cxx::json::document>(copy)); } TEST_CASE("can directly initialize cxx::json from std::int64_t") { static_assert(std::is_nothrow_constructible_v<cxx::json, std::int64_t>); std::int64_t const x = 42; cxx::json const json(x); REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can copy initialize cxx::json from std::int64_t") { cxx::json const json = 42l; REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == 42l); } TEST_CASE("can create cxx::json from double") { static_assert(std::is_nothrow_constructible_v<cxx::json, double>); double const x = 3.14; cxx::json const json(x); REQUIRE(cxx::holds_alternative<double>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from bool") { static_assert(std::is_nothrow_constructible_v<cxx::json, bool>); cxx::json const json(true); REQUIRE(cxx::holds_alternative<bool>(json)); REQUIRE(json == true); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from cxx::json::null") { static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::null_t>); cxx::json const json(cxx::json::null); REQUIRE(cxx::holds_alternative<cxx::json::null_t>(json)); REQUIRE(json == cxx::json::null); REQUIRE(std::size(json) == 0); } TEST_CASE("can create cxx::json from std::string") { static_assert(std::is_constructible_v<cxx::json, std::string const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, std::string&&>); std::string const lorem = "lorem"; cxx::json const json(lorem); REQUIRE(cxx::holds_alternative<std::string>(json)); REQUIRE(json == lorem); REQUIRE(std::size(json) == 5); cxx::json const ipsum(std::string("ipsum")); REQUIRE(cxx::holds_alternative<std::string>(ipsum)); REQUIRE(ipsum == std::string("ipsum")); REQUIRE(std::size(ipsum) == 5); } TEST_CASE("can create cxx::json from json::byte_stream") { static_assert(std::is_constructible_v<cxx::json, cxx::json::byte_stream const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::byte_stream&&>); cxx::json::byte_stream const stream = "010203"_hex; cxx::json const json(stream); REQUIRE(cxx::holds_alternative<cxx::json::byte_stream>(json)); REQUIRE(json == stream); REQUIRE(std::size(json) == 3); cxx::json const other("deadbeef"_hex); REQUIRE(cxx::holds_alternative<cxx::json::byte_stream>(other)); REQUIRE(other == "deadbeef"_hex); REQUIRE(std::size(other) == 4); } TEST_CASE("can create cxx::json from cxx::json::array") { static_assert(std::is_constructible_v<cxx::json, cxx::json::array const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::array&&>); cxx::json::array const array = {true, cxx::json::null, 42l, 3.14}; cxx::json const json(array); REQUIRE(cxx::holds_alternative<cxx::json::array>(json)); REQUIRE(json == array); REQUIRE(std::size(json) == 4); cxx::json const arr(cxx::json::array({cxx::json::null, 42l})); REQUIRE(arr == cxx::json::array({cxx::json::null, 42l})); REQUIRE(std::size(arr) == 2); } TEST_CASE("can create cxx::json from cxx::json::document") { static_assert(std::is_constructible_v<cxx::json, cxx::json::document const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::document&&>); cxx::json::document const document = { // clang-format off {"lorem"s, 42l}, {"ipsum"s, cxx::json::null}, {"dolor"s, true}, {"sit"s, 3.14} // clang-format on }; cxx::json const json(document); REQUIRE(cxx::holds_alternative<cxx::json::document>(json)); REQUIRE(json == document); REQUIRE(std::size(json) == 4); cxx::json const doc(cxx::json::document({{"lorem"s, cxx::json::null}, {"ipsum"s, 3.14}})); REQUIRE(cxx::holds_alternative<cxx::json::document>(doc)); REQUIRE(doc == cxx::json::document({{"lorem"s, cxx::json::null}, {"ipsum"s, 3.14}})); REQUIRE(std::size(doc) == 2); } TEST_CASE("can create cxx::json from std::initializer_list<json>") { static_assert(std::is_constructible_v<cxx::json, std::initializer_list<cxx::json>>); cxx::json const json = {42, true, cxx::json::null, 3.14}; REQUIRE(cxx::holds_alternative<cxx::json::array>(json)); REQUIRE(json == cxx::json::array({42, true, cxx::json::null, 3.14})); } TEST_CASE("can create cxx::json from std::initializer_list<cxx::byte>") { static_assert(std::is_constructible_v<cxx::json, std::initializer_list<cxx::byte>>); cxx::json const json = {cxx::byte(0xde), cxx::byte(0xad), cxx::byte(0xbe), cxx::byte(0xef)}; REQUIRE(cxx::holds_alternative<cxx::json::byte_stream>(json)); REQUIRE(json == "deadbeef"_hex); } TEST_CASE("can create cxx::json from std::initializer_list<std::pair<json::key, json>>") { using namespace cxx::literals; static_assert( std::is_constructible_v<cxx::json, std::initializer_list<std::pair<cxx::json::key const, cxx::json>>>); cxx::json const json = { // clang-format off {"lorem"_key, 42}, {"ipsum"_key, true}, {"dolor"_key, cxx::json::null}, {"sit"_key, 3.14} // clang-format on }; REQUIRE(cxx::holds_alternative<cxx::json::document>(json)); REQUIRE(json == // clang-format off cxx::json::document( { {"lorem", 42}, {"ipsum", true}, {"dolor", cxx::json::null}, {"sit", 3.14} } ) // clang-format on ); } TEST_CASE("can directly initialize cxx::json from int") { static_assert(std::is_nothrow_constructible_v<cxx::json, int>); int const x = 42; cxx::json const json(x); REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == x); } TEST_CASE("can copy initialize cxx::json from int") { cxx::json const json = 42; REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == 42); } <commit_msg>test for nested documents<commit_after>#include "inc/cxx/json.hpp" #include "test/catch.hpp" #include "test/utils.hpp" #include <type_traits> using namespace std::string_literals; using namespace test::literals; TEST_CASE("can default construct cxx::json") { static_assert(std::is_nothrow_default_constructible_v<cxx::json>); cxx::json const json; REQUIRE(cxx::holds_alternative<cxx::json::document>(json)); REQUIRE(std::size(json) == 0); } TEST_CASE("can copy construct cxx::json") { static_assert(std::is_copy_constructible_v<cxx::json>); cxx::json const orig; cxx::json const copy(orig); REQUIRE(cxx::holds_alternative<cxx::json::document>(orig)); REQUIRE(cxx::holds_alternative<cxx::json::document>(copy)); REQUIRE(orig == copy); } TEST_CASE("can move construct cxx::json") { static_assert(std::is_nothrow_move_constructible_v<cxx::json>); cxx::json orig; cxx::json const copy(std::move(orig)); REQUIRE(cxx::holds_alternative<cxx::json::document>(copy)); } TEST_CASE("can directly initialize cxx::json from std::int64_t") { static_assert(std::is_nothrow_constructible_v<cxx::json, std::int64_t>); std::int64_t const x = 42; cxx::json const json(x); REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can copy initialize cxx::json from std::int64_t") { cxx::json const json = 42l; REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == 42l); } TEST_CASE("can create cxx::json from double") { static_assert(std::is_nothrow_constructible_v<cxx::json, double>); double const x = 3.14; cxx::json const json(x); REQUIRE(cxx::holds_alternative<double>(json)); REQUIRE(json == x); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from bool") { static_assert(std::is_nothrow_constructible_v<cxx::json, bool>); cxx::json const json(true); REQUIRE(cxx::holds_alternative<bool>(json)); REQUIRE(json == true); REQUIRE(std::size(json) == 1); } TEST_CASE("can create cxx::json from cxx::json::null") { static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::null_t>); cxx::json const json(cxx::json::null); REQUIRE(cxx::holds_alternative<cxx::json::null_t>(json)); REQUIRE(json == cxx::json::null); REQUIRE(std::size(json) == 0); } TEST_CASE("can create cxx::json from std::string") { static_assert(std::is_constructible_v<cxx::json, std::string const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, std::string&&>); std::string const lorem = "lorem"; cxx::json const json(lorem); REQUIRE(cxx::holds_alternative<std::string>(json)); REQUIRE(json == lorem); REQUIRE(std::size(json) == 5); cxx::json const ipsum(std::string("ipsum")); REQUIRE(cxx::holds_alternative<std::string>(ipsum)); REQUIRE(ipsum == std::string("ipsum")); REQUIRE(std::size(ipsum) == 5); } TEST_CASE("can create cxx::json from json::byte_stream") { static_assert(std::is_constructible_v<cxx::json, cxx::json::byte_stream const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::byte_stream&&>); cxx::json::byte_stream const stream = "010203"_hex; cxx::json const json(stream); REQUIRE(cxx::holds_alternative<cxx::json::byte_stream>(json)); REQUIRE(json == stream); REQUIRE(std::size(json) == 3); cxx::json const other("deadbeef"_hex); REQUIRE(cxx::holds_alternative<cxx::json::byte_stream>(other)); REQUIRE(other == "deadbeef"_hex); REQUIRE(std::size(other) == 4); } TEST_CASE("can create cxx::json from cxx::json::array") { static_assert(std::is_constructible_v<cxx::json, cxx::json::array const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::array&&>); cxx::json::array const array = {true, cxx::json::null, 42l, 3.14}; cxx::json const json(array); REQUIRE(cxx::holds_alternative<cxx::json::array>(json)); REQUIRE(json == array); REQUIRE(std::size(json) == 4); cxx::json const arr(cxx::json::array({cxx::json::null, 42l})); REQUIRE(arr == cxx::json::array({cxx::json::null, 42l})); REQUIRE(std::size(arr) == 2); } TEST_CASE("can create cxx::json from cxx::json::document") { static_assert(std::is_constructible_v<cxx::json, cxx::json::document const&>); static_assert(std::is_nothrow_constructible_v<cxx::json, cxx::json::document&&>); cxx::json::document const document = { // clang-format off {"lorem"s, 42l}, {"ipsum"s, cxx::json::null}, {"dolor"s, true}, {"sit"s, 3.14} // clang-format on }; cxx::json const json(document); REQUIRE(cxx::holds_alternative<cxx::json::document>(json)); REQUIRE(json == document); REQUIRE(std::size(json) == 4); cxx::json const doc(cxx::json::document({{"lorem"s, cxx::json::null}, {"ipsum"s, 3.14}})); REQUIRE(cxx::holds_alternative<cxx::json::document>(doc)); REQUIRE(doc == cxx::json::document({{"lorem"s, cxx::json::null}, {"ipsum"s, 3.14}})); REQUIRE(std::size(doc) == 2); } TEST_CASE("can create cxx::json from std::initializer_list<json>") { static_assert(std::is_constructible_v<cxx::json, std::initializer_list<cxx::json>>); cxx::json const json = {42, true, cxx::json::null, 3.14}; REQUIRE(cxx::holds_alternative<cxx::json::array>(json)); REQUIRE(json == cxx::json::array({42, true, cxx::json::null, 3.14})); } TEST_CASE("can create cxx::json from std::initializer_list<cxx::byte>") { static_assert(std::is_constructible_v<cxx::json, std::initializer_list<cxx::byte>>); cxx::json const json = {cxx::byte(0xde), cxx::byte(0xad), cxx::byte(0xbe), cxx::byte(0xef)}; REQUIRE(cxx::holds_alternative<cxx::json::byte_stream>(json)); REQUIRE(json == "deadbeef"_hex); } TEST_CASE("can create cxx::json from std::initializer_list<std::pair<json::key, json>>") { using namespace cxx::literals; static_assert( std::is_constructible_v<cxx::json, std::initializer_list<std::pair<cxx::json::key const, cxx::json>>>); cxx::json const json = { // clang-format off {"lorem"_key, 42}, {"ipsum"_key, true}, {"dolor"_key, cxx::json::null}, {"sit"_key, 3.14} // clang-format on }; REQUIRE(cxx::holds_alternative<cxx::json::document>(json)); REQUIRE(json == // clang-format off cxx::json::document( { {"lorem", 42}, {"ipsum", true}, {"dolor", cxx::json::null}, {"sit", 3.14} } ) // clang-format on ); } TEST_CASE("can create cxx::json from nested document") { using namespace cxx::literals; cxx::json const json = { // clang-format off {"lorem"_key, 42}, {"ipsum"_key, { {"dolor"_key, cxx::json::null}, {"sit"_key, 3.14} } } // clang-format on }; REQUIRE(cxx::holds_alternative<cxx::json::document>(json)); REQUIRE(cxx::holds_alternative<std::int64_t>(json["lorem"])); REQUIRE(cxx::holds_alternative<cxx::json::document>(json["ipsum"])); REQUIRE(json["lorem"] == 42); REQUIRE(json["ipsum"]["dolor"] == cxx::json::null); REQUIRE(json["ipsum"]["sit"] == 3.14); cxx::json const other = { // clang-format off {"a"_key, { {"b"_key, "c"} } } // clang-format on }; REQUIRE(cxx::holds_alternative<cxx::json::document>(other)); REQUIRE(cxx::holds_alternative<cxx::json::document>(other["a"])); REQUIRE(other["a"]["b"] == "c"); } TEST_CASE("can directly initialize cxx::json from int") { static_assert(std::is_nothrow_constructible_v<cxx::json, int>); int const x = 42; cxx::json const json(x); REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == x); } TEST_CASE("can copy initialize cxx::json from int") { cxx::json const json = 42; REQUIRE(cxx::holds_alternative<std::int64_t>(json)); REQUIRE(json == 42); } <|endoftext|>
<commit_before>/* * GAMS - General Algebraic Modeling System C++ API * * Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com> * Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com> * * 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 "gamsjobimpl.h" #include "gmomcc.h" #include "gamscheckpoint.h" #include "gamslog.h" #include "gamsoptions.h" #include "gamsplatform.h" #include "gamspath.h" #include "gamsexceptionexecution.h" #include <sstream> #include <fstream> #include <iostream> #include <array> #include <thread> #ifdef _WIN32 #include <direct.h> #endif using namespace std; namespace gams { GAMSJobImpl::GAMSJobImpl(GAMSWorkspace& workspace, const std::string& jobName, const std::string& fileName, const GAMSCheckpoint* checkpoint) : mWs(workspace), mJobName(jobName), mFileName(fileName) { DEB << "---- Entering GAMSJob constructor ----"; if (checkpoint != nullptr) { if (!GAMSPath::exists(checkpoint->fileName()) ) throw GAMSException("Checkpoint file " + checkpoint->fileName() + " does not exist"); mCheckpointStart = new GAMSCheckpoint(*checkpoint); } } bool GAMSJobImpl::operator!=(const GAMSJobImpl& other) const { return (mWs != other.mWs) || (mJobName != other.mJobName); } bool GAMSJobImpl::operator==(const GAMSJobImpl& other) const { return !(operator!=(other)); } GAMSDatabase GAMSJobImpl::outDB() { return mOutDb; } GAMSJobImpl::~GAMSJobImpl() { delete mCheckpointStart; // this is intended to only free the wrapper, not the *Impl if used anywhere } void GAMSJobImpl::run(GAMSOptions* gamsOptions, GAMSCheckpoint* checkpoint, ostream* output, bool createOutDb, vector<GAMSDatabase> databases) { // TODO(JM) backward replacement of pointer logic with instance of gamsOptions GAMSOptions tmpOpt = GAMSOptions(mWs, gamsOptions); GAMSCheckpoint* tmpCP = nullptr; if (mCheckpointStart) tmpOpt.setRestart(mCheckpointStart->fileName()); if (checkpoint) { if (mCheckpointStart != checkpoint) { tmpCP = new GAMSCheckpoint(mWs, ""); tmpOpt.setSave(tmpCP->fileName()); } else { tmpOpt.setSave(checkpoint->fileName()); } } if (mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) { tmpOpt.setLogOption(3); } else { // can only happen if we are called from GAMSModelInstance if (tmpOpt.logOption() != 2) { if (output == nullptr) tmpOpt.setLogOption(0); else tmpOpt.setLogOption(3); } } if (!databases.empty()) { for (GAMSDatabase db: databases) { db.doExport(""); if (db.inModelName() != "") tmpOpt.setDefine(db.inModelName(), db.name()); } } GAMSPath jobFileInfo(GAMSPath(mWs.workingDirectory()) / mJobName); if (createOutDb && tmpOpt.gdx() == "") tmpOpt.setGdx(mWs.nextDatabaseName()); if (tmpOpt.logFile() == "") tmpOpt.setLogFile(jobFileInfo.suffix(".log").toStdString()); tmpOpt.setOutput(mJobName + ".lst"); tmpOpt.setCurDir(mWs.workingDirectory()); tmpOpt.setInput(mFileName); GAMSPath pfFileName = jobFileInfo.suffix(".pf"); try { tmpOpt.writeOptionFile(pfFileName); } catch (GAMSException& e) { throw GAMSException(e.what() + (" for GAMSJob " + mJobName)); } auto gamsExe = filesystem::path(mWs.systemDirectory()); gamsExe.append(string("gams") + cExeSuffix); string args = "dummy pf=" + mJobName + ".pf"; string result; int exitCode = runProcess(mWs.workingDirectory(), gamsExe.string(), args, result); if (createOutDb) { GAMSPath gdxPath(tmpOpt.gdx()); if (!gdxPath.is_absolute()) gdxPath = GAMSPath(mWs.workingDirectory()) / gdxPath; gdxPath.setSuffix(".gdx"); if (gdxPath.exists()) mOutDb = mWs.addDatabaseFromGDXForcedName(gdxPath.toStdString(), gdxPath.suffix("").filename().string(), ""); } if (output && mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) MSG << result; else if (output) *output << result; if (exitCode != 0) { std::cerr << "GAMS Error code: " << exitCode << std::endl; std::cerr << " with args: " << args << std::endl; std::cerr << " in " << mWs.workingDirectory() << std::endl; if ((mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) && mWs.usingTmpWorkingDir()) throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), set GAMSWorkspace.Debug to KeepFiles or higher or define the \ GAMSWorkspace.WorkingDirectory to receive a listing file with more details", exitCode); else throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), check " + (GAMSPath(mWs.workingDirectory()) / tmpOpt.output()).toStdString() + " for more details", exitCode); } if (tmpCP) { GAMSPath implFile(checkpoint->fileName()); if (implFile.exists()) implFile.remove(); implFile = tmpCP->fileName(); implFile.rename(checkpoint->fileName()); delete tmpCP; tmpCP=nullptr; } if (mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) { // TODO(RG): this is not good style, but apparently needed try { pfFileName.remove(); } catch (...) { } } } bool GAMSJobImpl::interrupt() { /*qint64*/ int pid = 0 /*mProc.processId()*/; // TODO(RG): we need std process handling here if(pid == 0) return false; return GAMSPlatform::interrupt(pid); } int GAMSJobImpl::runProcess(const string where, const string what, const string args, string& output) { lock_guard lck(mRunMutex); ostringstream ssp; string result; FILE* out; #ifdef _WIN32 filesystem::path p = filesystem::current_path(); ssp << "\"" << what << "\"" << " " << args ; _chdir(where.c_str()); // for some reason we need to do this on windows out = _popen(ssp.str().c_str(), "r"); _chdir(p.string().c_str()); // change back to old working dir #else ssp << "cd \"" << where << "\" && \"" << what << "\" " << args; out = popen(ssp.str().c_str(), "r"); #endif if (!out) { std::cerr << "Couldn't start command: " << ssp.str() << std::endl; return -1; } std::array<char, 128> buffer; while (fgets(buffer.data(), 128, out)) result += buffer.data(); output = result; int exitCode; #ifdef _WIN32 exitCode = _pclose(out); #else exitCode = pclose(out); #endif return exitCode; } } <commit_msg>minor adjustments<commit_after>/* * GAMS - General Algebraic Modeling System C++ API * * Copyright (c) 2017-2021 GAMS Software GmbH <support@gams.com> * Copyright (c) 2017-2021 GAMS Development Corp. <support@gams.com> * * 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 "gamsjobimpl.h" #include "gmomcc.h" #include "gamscheckpoint.h" #include "gamslog.h" #include "gamsoptions.h" #include "gamsplatform.h" #include "gamspath.h" #include "gamsexceptionexecution.h" #include <sstream> #include <fstream> #include <iostream> #include <array> #include <thread> #ifdef _WIN32 #include <direct.h> #endif using namespace std; namespace gams { GAMSJobImpl::GAMSJobImpl(GAMSWorkspace& workspace, const std::string& jobName, const std::string& fileName, const GAMSCheckpoint* checkpoint) : mWs(workspace), mJobName(jobName), mFileName(fileName) { DEB << "---- Entering GAMSJob constructor ----"; if (checkpoint != nullptr) { if (!GAMSPath::exists(checkpoint->fileName()) ) throw GAMSException("Checkpoint file " + checkpoint->fileName() + " does not exist"); mCheckpointStart = new GAMSCheckpoint(*checkpoint); } } bool GAMSJobImpl::operator!=(const GAMSJobImpl& other) const { return (mWs != other.mWs) || (mJobName != other.mJobName); } bool GAMSJobImpl::operator==(const GAMSJobImpl& other) const { return !(operator!=(other)); } GAMSDatabase GAMSJobImpl::outDB() { return mOutDb; } GAMSJobImpl::~GAMSJobImpl() { delete mCheckpointStart; // this is intended to only free the wrapper, not the *Impl if used anywhere } void GAMSJobImpl::run(GAMSOptions* gamsOptions, GAMSCheckpoint* checkpoint, ostream* output, bool createOutDb, vector<GAMSDatabase> databases) { // TODO(JM) backward replacement of pointer logic with instance of gamsOptions GAMSOptions tmpOpt = GAMSOptions(mWs, gamsOptions); GAMSCheckpoint* tmpCP = nullptr; if (mCheckpointStart) tmpOpt.setRestart(mCheckpointStart->fileName()); if (checkpoint) { if (mCheckpointStart != checkpoint) { tmpCP = new GAMSCheckpoint(mWs, ""); tmpOpt.setSave(tmpCP->fileName()); } else { tmpOpt.setSave(checkpoint->fileName()); } } if (mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) { tmpOpt.setLogOption(3); } else { // can only happen if we are called from GAMSModelInstance if (tmpOpt.logOption() != 2) { if (output == nullptr) tmpOpt.setLogOption(0); else tmpOpt.setLogOption(3); } } if (!databases.empty()) { for (GAMSDatabase db: databases) { db.doExport(""); if (db.inModelName() != "") tmpOpt.setDefine(db.inModelName(), db.name()); } } GAMSPath jobFileInfo(GAMSPath(mWs.workingDirectory()) / mJobName); if (createOutDb && tmpOpt.gdx() == "") tmpOpt.setGdx(mWs.nextDatabaseName()); if (tmpOpt.logFile() == "") tmpOpt.setLogFile(jobFileInfo.suffix(".log").toStdString()); tmpOpt.setOutput(mJobName + ".lst"); tmpOpt.setCurDir(mWs.workingDirectory()); tmpOpt.setInput(mFileName); GAMSPath pfFileName = jobFileInfo.suffix(".pf"); try { tmpOpt.writeOptionFile(pfFileName); } catch (GAMSException& e) { throw GAMSException(e.what() + (" for GAMSJob " + mJobName)); } auto gamsExe = filesystem::path(mWs.systemDirectory()); gamsExe.append(string("gams") + cExeSuffix); string args = "dummy pf=" + mJobName + ".pf"; string result; int exitCode = runProcess(mWs.workingDirectory(), gamsExe.string(), args, result); if (createOutDb) { GAMSPath gdxPath(tmpOpt.gdx()); if (!gdxPath.is_absolute()) gdxPath = GAMSPath(mWs.workingDirectory()) / gdxPath; gdxPath.setSuffix(".gdx"); if (gdxPath.exists()) mOutDb = mWs.addDatabaseFromGDXForcedName(gdxPath.toStdString(), gdxPath.suffix("").filename().string(), ""); } if (output && mWs.debug() >= GAMSEnum::DebugLevel::ShowLog) MSG << result; else if (output) *output << result; if (exitCode != 0) { std::cerr << "GAMS Error code: " << exitCode << std::endl; std::cerr << " with args: " << args << std::endl; std::cerr << " in " << mWs.workingDirectory() << std::endl; if ((mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) && mWs.usingTmpWorkingDir()) throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), set GAMSWorkspace.Debug to KeepFiles or higher or define the \ GAMSWorkspace.WorkingDirectory to receive a listing file with more details", exitCode); else throw GAMSExceptionExecution("GAMS return code not 0 (" + to_string(exitCode) + "), check " + (GAMSPath(mWs.workingDirectory()) / tmpOpt.output()).toStdString() + " for more details", exitCode); } if (tmpCP) { GAMSPath implFile(checkpoint->fileName()); if (implFile.exists()) implFile.remove(); implFile = tmpCP->fileName(); implFile.rename(checkpoint->fileName()); delete tmpCP; tmpCP=nullptr; } if (mWs.debug() < GAMSEnum::DebugLevel::KeepFiles) { // TODO(RG): this is not good style, but apparently needed try { pfFileName.remove(); } catch (...) { } } } bool GAMSJobImpl::interrupt() { /*qint64*/ int pid = 0 /*mProc.processId()*/; // TODO(RG): we need std process handling here if(pid == 0) return false; return GAMSPlatform::interrupt(pid); } int GAMSJobImpl::runProcess(const string where, const string what, const string args, string& output) { ostringstream ssp; string result; FILE* out; #ifdef _WIN32 filesystem::path p = filesystem::current_path(); ssp << "\"" << what << "\"" << " " << args ; _chdir(where.c_str()); // for some reason we need this on windows out = _popen(ssp.str().c_str(), "rt"); _chdir(p.string().c_str()); // change back to old working dir #else ssp << "cd \"" << where << "\" && \"" << what << "\" " << args; out = popen(ssp.str().c_str(), "r"); #endif if (!out) { std::cerr << "Couldn't start command: " << ssp.str() << std::endl; return -1; } std::array<char, 128> buffer; while (fgets(buffer.data(), 128, out)) result += buffer.data(); output = result; int exitCode; #ifdef _WIN32 exitCode = _pclose(out); #else exitCode = pclose(out); #endif return exitCode; } } <|endoftext|>
<commit_before>/* VideoCapture ------------- This example shows a minimal example on how to list the capture devices, list capabilities and output formats. */ #include <signal.h> #if defined(__APPLE__) || defined(__linux) # include <unistd.h> /* usleep */ #elif defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <videocapture/Capture.h> using namespace ca; bool must_run = true; void fcallback(void* pixels, int nbytes, void* user); void sig_handler(int sig); int main() { printf("\nVideoCapture\n"); signal(SIGINT, sig_handler); int width = 640; int height = 480; Settings cfg; cfg.device = 0; cfg.capability = 0; cfg.format = 0; Capture cap(fcallback, NULL); cap.listDevices(); cap.listOutputFormats(); cap.listCapabilities(cfg.device); if (!cfg.capability = cap.findCapability(cfg.device, width, height, CA_YUYV422)) { if (!cfg.capability = cap.findCapability(cfg.device, width, height, CA_UYVY422)) { printf("Error: tried CA_YUYV422 and CA_UYVY formats; both didn't work."); ::exit(EXIT_FAILURE); } } if(cap.open(cfg) < 0) { printf("Error: cannot open the device.\n"); ::exit(EXIT_FAILURE); } if(cap.start() < 0) { printf("Error: cannot start capture.\n"); ::exit(EXIT_FAILURE); } while(must_run == true) { cap.update(); #if defined(_WIN32) Sleep(5); #else usleep(5 * 1000); #endif } if(cap.stop() < 0) { printf("Error: cannot stop.\n"); } if(cap.close() < 0) { printf("Error: cannot close.\n"); } return EXIT_SUCCESS; } void fcallback(void* pixels, int nbytes, void* user) { printf("Frame callback: %d bytes\n", nbytes); } void sig_handler(int sig) { printf("Handle signal.\n"); must_run = false; } <commit_msg>Tiny bugfix in api_example<commit_after>/* VideoCapture ------------- This example shows a minimal example on how to list the capture devices, list capabilities and output formats. */ #include <signal.h> #if defined(__APPLE__) || defined(__linux) # include <unistd.h> /* usleep */ #elif defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include <videocapture/Capture.h> using namespace ca; bool must_run = true; void fcallback(void* pixels, int nbytes, void* user); void sig_handler(int sig); int main() { printf("\nVideoCapture\n"); signal(SIGINT, sig_handler); int width = 640; int height = 480; Settings cfg; cfg.device = 0; cfg.capability = 0; cfg.format = 0; Capture cap(fcallback, NULL); cap.listDevices(); cap.listOutputFormats(); cap.listCapabilities(cfg.device); cfg.capability = cap.findCapability(cfg.device, width, height, CA_YUYV422); if (!cfg.capability) { cfg.capability = cap.findCapability(cfg.device, width, height, CA_UYVY422); if (!cfg.capability) { printf("Error: tried CA_YUYV422 and CA_UYVY formats; both didn't work."); ::exit(EXIT_FAILURE); } } if(cap.open(cfg) < 0) { printf("Error: cannot open the device.\n"); ::exit(EXIT_FAILURE); } if(cap.start() < 0) { printf("Error: cannot start capture.\n"); ::exit(EXIT_FAILURE); } while(must_run == true) { cap.update(); #if defined(_WIN32) Sleep(5); #else usleep(5 * 1000); #endif } if(cap.stop() < 0) { printf("Error: cannot stop.\n"); } if(cap.close() < 0) { printf("Error: cannot close.\n"); } return EXIT_SUCCESS; } void fcallback(void* pixels, int nbytes, void* user) { printf("Frame callback: %d bytes\n", nbytes); } void sig_handler(int sig) { printf("Handle signal.\n"); must_run = false; } <|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. */ #include <glog/logging.h> #include <process/process.hpp> #include "monitoring/resource_monitor.hpp" using process::Clock; namespace mesos { namespace internal { namespace monitoring { ResourceMonitor::ResourceMonitor(ResourceCollector* _collector) : collector(_collector) {} ResourceMonitor::~ResourceMonitor() { delete collector; } // The default implementation collects only the cpu and memory // for use in creating a UsageMessage Try<UsageReport> ResourceMonitor::collectUsage() { Resources resources; double now = Clock::now(); double duration = 0; collector->collectUsage(); // TODO(adegtiar or sam): consider making this more general to // avoid code duplication and make it more flexible, e.g. // foreach usageType in ["mem_usage", "cpu_usage", ...] // collector->getUsage(usageType); (+ Try stuff, etc) Try<double> memUsage = collector->getMemoryUsage(); if (memUsage.isSome()) { Resource memory; memory.set_type(Resource::SCALAR); memory.set_name("mem_usage"); memory.mutable_scalar()->set_value(memUsage.get()); resources += memory; } else { return Try<UsageReport>::error(memUsage.error()); } Try<Rate> cpuUsage = collector->getCpuUsage(); if (cpuUsage.isSome()) { Rate rate = cpuUsage.get(); Resource cpu; cpu.set_type(Resource::SCALAR); cpu.set_name("cpu_usage"); cpu.mutable_scalar()->set_value(rate.difference); duration = rate.duration; resources += cpu; } else { return Try<UsageReport>::error(cpuUsage.error()); } // TODO(adegtiar or sam): Consider returning partial usage reports. // For now if one fails, the other will almost certainly fail, and // so may not be worthwhile. This could change. return UsageReport(resources, now, duration); } } // namespace monitoring { } // namespace internal { } // namespace mesos { <commit_msg>using new namespace<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. */ #include <glog/logging.h> #include <process/process.hpp> #include "monitoring/resource_monitor.hpp" using process::Clock; namespace mesos { namespace internal { namespace monitoring { ResourceMonitor::ResourceMonitor(ResourceCollector* _collector) : collector(_collector) {} ResourceMonitor::~ResourceMonitor() { delete collector; } // The default implementation collects only the cpu and memory // for use in creating a UsageMessage Try<UsageReport> ResourceMonitor::collectUsage() { Resources resources; double now = Clock::now(); double duration = 0; collector->collectUsage(); // TODO(adegtiar or sam): consider making this more general to // avoid code duplication and make it more flexible, e.g. // foreach usageType in ["mem_usage", "cpu_usage", ...] // collector->getUsage(usageType); (+ Try stuff, etc) Try<double> memUsage = collector->getMemoryUsage(); if (memUsage.isSome()) { Resource memory; memory.set_type(Value::SCALAR); memory.set_name("mem_usage"); memory.mutable_scalar()->set_value(memUsage.get()); resources += memory; } else { return Try<UsageReport>::error(memUsage.error()); } Try<Rate> cpuUsage = collector->getCpuUsage(); if (cpuUsage.isSome()) { Rate rate = cpuUsage.get(); Resource cpu; cpu.set_type(Value::SCALAR); cpu.set_name("cpu_usage"); cpu.mutable_scalar()->set_value(rate.difference); duration = rate.duration; resources += cpu; } else { return Try<UsageReport>::error(cpuUsage.error()); } // TODO(adegtiar or sam): Consider returning partial usage reports. // For now if one fails, the other will almost certainly fail, and // so may not be worthwhile. This could change. return UsageReport(resources, now, duration); } } // namespace monitoring { } // namespace internal { } // namespace mesos { <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file shhrpc.cpp * @author Vladislav Gluhovsky <vlad@ethdev.com> * @date July 2015 */ #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> #include <libdevcore/Log.h> #include <libdevcore/CommonIO.h> #include <libethcore/CommonJS.h> #include <libwebthree/WebThree.h> #include <libweb3jsonrpc/WebThreeStubServer.h> #include <jsonrpccpp/server/connectors/httpserver.h> #include <jsonrpccpp/client/connectors/httpclient.h> #include <test/TestHelper.h> #include <test/libweb3jsonrpc/webthreestubclient.h> #include <libethcore/KeyManager.h> #include <libp2p/Common.h> #include <libwhisper/WhisperHost.h> using namespace std; using namespace dev; using namespace dev::eth; using namespace dev::p2p; using namespace dev::shh; namespace js = json_spirit; WebThreeDirect* web3; unique_ptr<WebThreeStubServer> jsonrpcServer; unique_ptr<WebThreeStubClient> jsonrpcClient; static uint16_t const web3port = 30333; struct Setup { Setup() { dev::p2p::NodeIPEndpoint::test_allowLocal = true; static bool setup = false; if (!setup) { setup = true; NetworkPreferences nprefs(std::string(), web3port, false); web3 = new WebThreeDirect("shhrpc-web3", "", WithExisting::Trust, {"eth", "shh"}, nprefs); web3->setIdealPeerCount(1); web3->ethereum()->setForceMining(false); auto server = new jsonrpc::HttpServer(8080); vector<KeyPair> v; KeyManager keyMan; TrivialGasPricer gp; jsonrpcServer = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(*server, *web3, nullptr, v, keyMan, gp)); jsonrpcServer->setIdentities({}); jsonrpcServer->StartListening(); auto client = new jsonrpc::HttpClient("http://localhost:8080"); jsonrpcClient = unique_ptr<WebThreeStubClient>(new WebThreeStubClient(*client)); } } ~Setup() { dev::p2p::NodeIPEndpoint::test_allowLocal = false; } }; BOOST_FIXTURE_TEST_SUITE(shhrpc, Setup) BOOST_AUTO_TEST_CASE(basic) { cnote << "Testing web3 basic functionality..."; web3->startNetwork(); unsigned const step = 10; for (unsigned i = 0; i < 3000 && !web3->haveNetwork(); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(web3->haveNetwork()); uint16_t const port2 = 30334; NetworkPreferences prefs2("127.0.0.1", port2, false); string const version2 = "shhrpc-host2"; Host host2(version2, prefs2); auto whost2 = host2.registerCapability(new WhisperHost()); host2.start(); for (unsigned i = 0; i < 3000 && !host2.haveNetwork(); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(host2.haveNetwork()); web3->addNode(host2.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), port2, port2)); for (unsigned i = 0; i < 3000 && (!web3->peerCount() || !host2.peerCount()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE_EQUAL(host2.peerCount(), 1); BOOST_REQUIRE_EQUAL(web3->peerCount(), 1); vector<PeerSessionInfo> vpeers = web3->peers(); BOOST_REQUIRE(!vpeers.empty()); PeerSessionInfo const& peer = vpeers.back(); BOOST_REQUIRE_EQUAL(peer.id, host2.id()); BOOST_REQUIRE_EQUAL(peer.port, port2); BOOST_REQUIRE_EQUAL(peer.clientVersion, version2); web3->stopNetwork(); for (unsigned i = 0; i < 3000 && (web3->haveNetwork() || host2.haveNetwork()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(!web3->peerCount()); BOOST_REQUIRE(!host2.peerCount()); } BOOST_AUTO_TEST_CASE(send) { cnote << "Testing web3 send..."; bool sent = false; bool ready = false; unsigned result = 0; unsigned const messageCount = 10; unsigned const step = 10; uint16_t port2 = 30337; Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false)); host2.setIdealPeerCount(1); auto whost2 = host2.registerCapability(new WhisperHost()); host2.start(); web3->startNetwork(); std::thread listener([&]() { setThreadName("listener"); ready = true; auto w = whost2->installWatch(BuildTopicMask("odd")); set<unsigned> received; for (unsigned x = 0; x < 9000 && !sent; x += step) this_thread::sleep_for(chrono::milliseconds(step)); for (unsigned x = 0, last = 0; x < 100 && received.size() < messageCount; ++x) { this_thread::sleep_for(chrono::milliseconds(50)); for (auto i: whost2->checkWatch(w)) { Message msg = whost2->envelope(i).open(whost2->fullTopics(w)); last = RLP(msg.payload()).toInt<unsigned>(); if (received.insert(last).second) result += last; } } }); for (unsigned i = 0; i < 2000 && (!host2.haveNetwork() || web3->haveNetwork()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(host2.haveNetwork()); BOOST_REQUIRE(web3->haveNetwork()); web3->requirePeer(host2.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), port2, port2)); for (unsigned i = 0; i < 3000 && (!web3->peerCount() || !host2.peerCount()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE_EQUAL(host2.peerCount(), 1); BOOST_REQUIRE_EQUAL(web3->peerCount(), 1); KeyPair us = KeyPair::create(); for (int i = 0; i < messageCount; ++i) { web3->whisper()->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"), 777000, 1); this_thread::sleep_for(chrono::milliseconds(50)); } sent = true; auto messages = web3->whisper()->all(); BOOST_REQUIRE_EQUAL(messages.size(), messageCount); listener.join(); BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81); } BOOST_AUTO_TEST_CASE(receive) { cnote << "Testing web3 receive..."; bool sent = false; bool ready = false; unsigned result = 0; unsigned const messageCount = 6; unsigned const step = 10; uint16_t port2 = 30338; Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false)); host2.setIdealPeerCount(1); auto whost2 = host2.registerCapability(new WhisperHost()); host2.start(); web3->startNetwork(); std::thread listener([&]() { setThreadName("listener"); ready = true; auto w = web3->whisper()->installWatch(BuildTopicMask("odd")); set<unsigned> received; for (unsigned x = 0; x < 9000 && !sent; x += step) this_thread::sleep_for(chrono::milliseconds(step)); for (unsigned x = 0, last = 0; x < 100 && received.size() < messageCount; ++x) { this_thread::sleep_for(chrono::milliseconds(50)); for (auto i: web3->whisper()->checkWatch(w)) { Message msg = web3->whisper()->envelope(i).open(web3->whisper()->fullTopics(w)); last = RLP(msg.payload()).toInt<unsigned>(); if (received.insert(last).second) result += last; } } }); for (unsigned i = 0; i < 2000 && (!host2.haveNetwork() || web3->haveNetwork()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(host2.haveNetwork()); BOOST_REQUIRE(web3->haveNetwork()); host2.addNode(web3->id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), web3port, web3port)); for (unsigned i = 0; i < 3000 && (!web3->peerCount() || !host2.peerCount()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE_EQUAL(host2.peerCount(), 1); BOOST_REQUIRE_EQUAL(web3->peerCount(), 1); KeyPair us = KeyPair::create(); for (int i = 0; i < messageCount; ++i) { web3->whisper()->post(us.sec(), RLPStream().append(i * i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"), 777000, 1); this_thread::sleep_for(chrono::milliseconds(50)); } sent = true; listener.join(); BOOST_REQUIRE_EQUAL(result, 1 + 27 + 125); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>style fix<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file shhrpc.cpp * @author Vladislav Gluhovsky <vlad@ethdev.com> * @date July 2015 */ #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> #include <libdevcore/Log.h> #include <libdevcore/CommonIO.h> #include <libethcore/CommonJS.h> #include <libwebthree/WebThree.h> #include <libweb3jsonrpc/WebThreeStubServer.h> #include <jsonrpccpp/server/connectors/httpserver.h> #include <jsonrpccpp/client/connectors/httpclient.h> #include <test/TestHelper.h> #include <test/libweb3jsonrpc/webthreestubclient.h> #include <libethcore/KeyManager.h> #include <libp2p/Common.h> #include <libwhisper/WhisperHost.h> using namespace std; using namespace dev; using namespace dev::eth; using namespace dev::p2p; using namespace dev::shh; namespace js = json_spirit; WebThreeDirect* web3; unique_ptr<WebThreeStubServer> jsonrpcServer; unique_ptr<WebThreeStubClient> jsonrpcClient; static uint16_t const web3port = 30333; struct Setup { Setup() { dev::p2p::NodeIPEndpoint::test_allowLocal = true; static bool setup = false; if (!setup) { setup = true; NetworkPreferences nprefs(std::string(), web3port, false); web3 = new WebThreeDirect("shhrpc-web3", "", WithExisting::Trust, {"eth", "shh"}, nprefs); web3->setIdealPeerCount(1); web3->ethereum()->setForceMining(false); auto server = new jsonrpc::HttpServer(8080); vector<KeyPair> v; KeyManager keyMan; TrivialGasPricer gp; jsonrpcServer = unique_ptr<WebThreeStubServer>(new WebThreeStubServer(*server, *web3, nullptr, v, keyMan, gp)); jsonrpcServer->setIdentities({}); jsonrpcServer->StartListening(); auto client = new jsonrpc::HttpClient("http://localhost:8080"); jsonrpcClient = unique_ptr<WebThreeStubClient>(new WebThreeStubClient(*client)); } } ~Setup() { dev::p2p::NodeIPEndpoint::test_allowLocal = false; } }; BOOST_FIXTURE_TEST_SUITE(shhrpc, Setup) BOOST_AUTO_TEST_CASE(basic) { cnote << "Testing web3 basic functionality..."; web3->startNetwork(); unsigned const step = 10; for (unsigned i = 0; i < 3000 && !web3->haveNetwork(); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(web3->haveNetwork()); uint16_t const port2 = 30334; NetworkPreferences prefs2("127.0.0.1", port2, false); string const version2 = "shhrpc-host2"; Host host2(version2, prefs2); auto whost2 = host2.registerCapability(new WhisperHost()); host2.start(); for (unsigned i = 0; i < 3000 && !host2.haveNetwork(); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(host2.haveNetwork()); web3->addNode(host2.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), port2, port2)); for (unsigned i = 0; i < 3000 && (!web3->peerCount() || !host2.peerCount()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE_EQUAL(host2.peerCount(), 1); BOOST_REQUIRE_EQUAL(web3->peerCount(), 1); vector<PeerSessionInfo> vpeers = web3->peers(); BOOST_REQUIRE(!vpeers.empty()); PeerSessionInfo const& peer = vpeers.back(); BOOST_REQUIRE_EQUAL(peer.id, host2.id()); BOOST_REQUIRE_EQUAL(peer.port, port2); BOOST_REQUIRE_EQUAL(peer.clientVersion, version2); web3->stopNetwork(); for (unsigned i = 0; i < 3000 && (web3->haveNetwork() || host2.haveNetwork()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(!web3->peerCount()); BOOST_REQUIRE(!host2.peerCount()); } BOOST_AUTO_TEST_CASE(send) { cnote << "Testing web3 send..."; bool sent = false; bool ready = false; unsigned result = 0; unsigned const messageCount = 10; unsigned const step = 10; uint16_t port2 = 30337; Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false)); host2.setIdealPeerCount(1); auto whost2 = host2.registerCapability(new WhisperHost()); host2.start(); web3->startNetwork(); std::thread listener([&]() { setThreadName("listener"); ready = true; auto w = whost2->installWatch(BuildTopicMask("odd")); set<unsigned> received; for (unsigned x = 0; x < 9000 && !sent; x += step) this_thread::sleep_for(chrono::milliseconds(step)); for (unsigned x = 0, last = 0; x < 100 && received.size() < messageCount; ++x) { this_thread::sleep_for(chrono::milliseconds(50)); for (auto i: whost2->checkWatch(w)) { Message msg = whost2->envelope(i).open(whost2->fullTopics(w)); last = RLP(msg.payload()).toInt<unsigned>(); if (received.insert(last).second) result += last; } } }); for (unsigned i = 0; i < 2000 && (!host2.haveNetwork() || web3->haveNetwork()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(host2.haveNetwork()); BOOST_REQUIRE(web3->haveNetwork()); web3->requirePeer(host2.id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), port2, port2)); for (unsigned i = 0; i < 3000 && (!web3->peerCount() || !host2.peerCount()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE_EQUAL(host2.peerCount(), 1); BOOST_REQUIRE_EQUAL(web3->peerCount(), 1); KeyPair us = KeyPair::create(); for (unsigned i = 0; i < messageCount; ++i) { web3->whisper()->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"), 777000, 1); this_thread::sleep_for(chrono::milliseconds(50)); } sent = true; auto messages = web3->whisper()->all(); BOOST_REQUIRE_EQUAL(messages.size(), messageCount); listener.join(); BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81); } BOOST_AUTO_TEST_CASE(receive) { cnote << "Testing web3 receive..."; bool sent = false; bool ready = false; unsigned result = 0; unsigned const messageCount = 6; unsigned const step = 10; uint16_t port2 = 30338; Host host2("shhrpc-host2", NetworkPreferences("127.0.0.1", port2, false)); host2.setIdealPeerCount(1); auto whost2 = host2.registerCapability(new WhisperHost()); host2.start(); web3->startNetwork(); std::thread listener([&]() { setThreadName("listener"); ready = true; auto w = web3->whisper()->installWatch(BuildTopicMask("odd")); set<unsigned> received; for (unsigned x = 0; x < 9000 && !sent; x += step) this_thread::sleep_for(chrono::milliseconds(step)); for (unsigned x = 0, last = 0; x < 100 && received.size() < messageCount; ++x) { this_thread::sleep_for(chrono::milliseconds(50)); for (auto i: web3->whisper()->checkWatch(w)) { Message msg = web3->whisper()->envelope(i).open(web3->whisper()->fullTopics(w)); last = RLP(msg.payload()).toInt<unsigned>(); if (received.insert(last).second) result += last; } } }); for (unsigned i = 0; i < 2000 && (!host2.haveNetwork() || web3->haveNetwork()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE(host2.haveNetwork()); BOOST_REQUIRE(web3->haveNetwork()); host2.addNode(web3->id(), NodeIPEndpoint(bi::address::from_string("127.0.0.1"), web3port, web3port)); for (unsigned i = 0; i < 3000 && (!web3->peerCount() || !host2.peerCount()); i += step) this_thread::sleep_for(chrono::milliseconds(step)); BOOST_REQUIRE_EQUAL(host2.peerCount(), 1); BOOST_REQUIRE_EQUAL(web3->peerCount(), 1); KeyPair us = KeyPair::create(); for (unsigned i = 0; i < messageCount; ++i) { web3->whisper()->post(us.sec(), RLPStream().append(i * i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"), 777000, 1); this_thread::sleep_for(chrono::milliseconds(50)); } sent = true; listener.join(); BOOST_REQUIRE_EQUAL(result, 1 + 27 + 125); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* -*- Mode: C++; indent-tabs-mode: nil -*- */ #include <config.h> #include <cerrno> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <type_traits> #include <utility> #include <vector> #include <unistd.h> #include <schwa/config.h> #include <schwa/exception.h> #include <schwa/io/logging.h> #include <schwa/port.h> #include <dr-count/main.h> #include <dr-dist/main.h> #include <dr-head/main.h> #include <dr-tail/main.h> #include <dr-ui/main.h> namespace cf = schwa::config; namespace io = schwa::io; namespace port = schwa::port; namespace { // ============================================================================ // Config option parser // ============================================================================ class Main : public cf::Main { protected: std::vector<std::pair<const char *, const char *>> _commands; inline void _add(const char *name, const char *desc) { _commands.push_back(std::pair<const char *, const char *>(name + 3, desc)); } virtual void _help_self(std::ostream &out, const unsigned int) const override; public: Main(const std::string &name, const std::string &desc); }; Main::Main(const std::string &name, const std::string &desc) : cf::Main(name, desc) { _add(schwa::dr_count::PROGRAM_NAME, schwa::dr_count::PROGRAM_DESC); _add(schwa::dr_dist::PROGRAM_NAME, schwa::dr_dist::PROGRAM_DESC); _add(schwa::dr_head::PROGRAM_NAME, schwa::dr_head::PROGRAM_DESC); _add(schwa::dr_tail::PROGRAM_NAME, schwa::dr_tail::PROGRAM_DESC); _add(schwa::dr_ui::PROGRAM_NAME, schwa::dr_ui::PROGRAM_DESC); } void Main::_help_self(std::ostream &out, const unsigned int) const { out << port::BOLD << _full_name << port::OFF << ": " << _desc << std::endl; //out << " Usage: " << _full_name << " [options] (dist|head|list-stores|tail|ui) [command options]" << std::endl; out << " Usage: " << _full_name << " [options] ("; for (decltype(_commands)::size_type i = 0; i != _commands.size(); ++i) { if (i != 0) out << '|'; out << _commands[i].first; } out << ") [command options]" << std::endl; for (auto &pair : _commands) out << " " << port::BOLD << pair.first << port::OFF << ": " << pair.second << std::endl; } // ============================================================================ // main // ============================================================================ static void _main(int argc, char **argv) { // The first unclaimed argument has to be the name of the app to call. if (argc == 1) throw cf::ConfigException("Positional argument {command} is missing."); // Construct the array to pass to execvp. // dr ui --help (argc == 3) std::unique_ptr<char *[]> args(new char*[argc]); std::memcpy(args.get() + 1, argv + 2, (argc - 2) * sizeof(char *)); args[argc - 1] = nullptr; // Construct the name of the binary to exec. const size_t len = std::strlen(argv[1]); std::unique_ptr<char[]> app(new char[3 + len + 1]); std::memcpy(app.get() + 0, "dr-", 3); std::memcpy(app.get() + 3, argv[1], len + 1); // First, try looking in the the directory of argv[0]. std::string path = port::abspath_to_argv0(); path = port::path_dirname(path); path = port::path_join(path, app.get()); std::unique_ptr<char[]> abspath_app(new char[path.size() + 1]); args[0] = abspath_app.get(); std::strcpy(args[0], path.c_str()); execv(args[0], args.get()); // If the first exaec attempt failed, try exec'ing using the current definition of PATH. args[0] = app.get(); execvp(args[0], args.get()); // If we still failed to find the executable, fail. const int errnum = errno; std::ostringstream ss; if (errnum == ENOENT) { ss << "Command '" << argv[1] << "' not found."; throw cf::ConfigException(ss.str()); } else { ss << "Failed to exec dr-" << argv[1] << ": " << std::strerror(errnum) << "."; throw schwa::Exception(ss.str()); } } } int main(int argc, char **argv) { // Construct an option parser. Main cfg("dr", "A dispatcher to other docrep processing tools."); // Parse argv. cfg.allow_unclaimed_args(true); cfg.main<io::PrettyLogger>(argc, argv); // Dispatch to main function. try { _main(argc, argv); } catch (cf::ConfigException &e) { std::cerr << schwa::print_exception("ConfigException", e) << std::endl; cfg.help(std::cerr); return 1; } catch (schwa::Exception &e) { std::cerr << schwa::print_exception(e) << std::endl; return 1; } return 0; } <commit_msg>Corrected extra newline in dr's usage string.<commit_after>/* -*- Mode: C++; indent-tabs-mode: nil -*- */ #include <config.h> #include <cerrno> #include <cstring> #include <iostream> #include <memory> #include <sstream> #include <type_traits> #include <utility> #include <vector> #include <unistd.h> #include <schwa/config.h> #include <schwa/exception.h> #include <schwa/io/logging.h> #include <schwa/port.h> #include <dr-count/main.h> #include <dr-dist/main.h> #include <dr-head/main.h> #include <dr-tail/main.h> #include <dr-ui/main.h> namespace cf = schwa::config; namespace io = schwa::io; namespace port = schwa::port; namespace { // ============================================================================ // Config option parser // ============================================================================ class Main : public cf::Main { protected: std::vector<std::pair<const char *, const char *>> _commands; void _add(const char *name, const char *desc); virtual void _help_self(std::ostream &out, const unsigned int) const override; public: Main(const std::string &name, const std::string &desc); }; Main::Main(const std::string &name, const std::string &desc) : cf::Main(name, desc) { _add(schwa::dr_count::PROGRAM_NAME, schwa::dr_count::PROGRAM_DESC); _add(schwa::dr_dist::PROGRAM_NAME, schwa::dr_dist::PROGRAM_DESC); _add(schwa::dr_head::PROGRAM_NAME, schwa::dr_head::PROGRAM_DESC); _add(schwa::dr_tail::PROGRAM_NAME, schwa::dr_tail::PROGRAM_DESC); _add(schwa::dr_ui::PROGRAM_NAME, schwa::dr_ui::PROGRAM_DESC); } void Main::_add(const char *const name, const char *const desc) { _commands.push_back(std::pair<const char *, const char *>(name + 3, desc)); } void Main::_help_self(std::ostream &out, const unsigned int) const { out << port::BOLD << _full_name << port::OFF << ": " << _desc << std::endl; out << " Usage: " << _full_name << " [options] ("; for (decltype(_commands)::size_type i = 0; i != _commands.size(); ++i) { if (i != 0) out << '|'; out << _commands[i].first; } out << ") [command options]"; for (auto &pair : _commands) out << std::endl << " " << port::BOLD << pair.first << port::OFF << ": " << pair.second; } // ============================================================================ // main // ============================================================================ static void _main(int argc, char **argv) { // The first unclaimed argument has to be the name of the app to call. if (argc == 1) throw cf::ConfigException("Positional argument {command} is missing."); // Construct the array to pass to execvp. // dr ui --help (argc == 3) std::unique_ptr<char *[]> args(new char*[argc]); std::memcpy(args.get() + 1, argv + 2, (argc - 2) * sizeof(char *)); args[argc - 1] = nullptr; // Construct the name of the binary to exec. const size_t len = std::strlen(argv[1]); std::unique_ptr<char[]> app(new char[3 + len + 1]); std::memcpy(app.get() + 0, "dr-", 3); std::memcpy(app.get() + 3, argv[1], len + 1); // First, try looking in the the directory of argv[0]. std::string path = port::abspath_to_argv0(); path = port::path_dirname(path); path = port::path_join(path, app.get()); std::unique_ptr<char[]> abspath_app(new char[path.size() + 1]); args[0] = abspath_app.get(); std::strcpy(args[0], path.c_str()); execv(args[0], args.get()); // If the first exaec attempt failed, try exec'ing using the current definition of PATH. args[0] = app.get(); execvp(args[0], args.get()); // If we still failed to find the executable, fail. const int errnum = errno; std::ostringstream ss; if (errnum == ENOENT) { ss << "Command '" << argv[1] << "' not found."; throw cf::ConfigException(ss.str()); } else { ss << "Failed to exec dr-" << argv[1] << ": " << std::strerror(errnum) << "."; throw schwa::Exception(ss.str()); } } } int main(int argc, char **argv) { // Construct an option parser. Main cfg("dr", "A dispatcher to other docrep processing tools."); // Parse argv. cfg.allow_unclaimed_args(true); cfg.main<io::PrettyLogger>(argc, argv); // Dispatch to main function. try { _main(argc, argv); } catch (cf::ConfigException &e) { std::cerr << schwa::print_exception("ConfigException", e) << std::endl; cfg.help(std::cerr); return 1; } catch (schwa::Exception &e) { std::cerr << schwa::print_exception(e) << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include<iostream> #include <cstdlib> #include <cstdio> #include <array> #include <boost/test/unit_test.hpp> using RawField = std::array<std::array<char, 32>, 32>; using RawStone = std::array<std::array<char, 8>, 8>; constexpr int ROTATE_90 = 1, ROTATE_180 = 2, ROTATE_270 = 4, REVERSED = 8; class Field { private: int score = 0; public: RawField raw = {}; int Score() const { return score; } bool TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info); }; class Stone { public: RawStone raw = {}; }; Field max_score_field; Stone reserved_stones[256]; int number_of_stone = 0; void Parse(Field* f) { for (int i = 0; i < 32; ++i) { fread(f->raw[i].data(), sizeof(char[32]), 1, stdin); getchar(); //CR getchar(); //LF } scanf("\n%d\n", &number_of_stone); for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { fread(reserved_stones[i].raw[j].data(), sizeof(char[8]), 1, stdin); getchar(); //CR getchar(); //LF } getchar(); //CR getchar(); //LF } } void DumpField(const Field& f) { for (int i = 0; i < 32; ++i) { for (int j = 0; j < 32; ++j) { putc(f.raw[i][j], stdout); } puts(""); } } void Solve(Field f, const int look_nth_stone) { if (look_nth_stone > number_of_stone) { if (f.Score() > max_score_field.Score()) { max_score_field = f; } return; } Solve(f, look_nth_stone + 1); Field backup = f; for (int x = -7; x < 32; ++x) { for (int y = -7; y < 32; ++y) { if (f.TryPutStone(look_nth_stone, x, y, 0)) { Solve(f, look_nth_stone+1); f = backup; } } } } void DumpStones() { for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { for (int k = 0; k < 8; ++k) { putc(reserved_stones[i].raw[j][k], stdout); } puts(""); } puts(""); } } int main() { Field reserved_field; // get_problemfile(); Parse(&reserved_field); Solve(reserved_field, 0); DumpField(max_score_field); // solve(); // submit_answer(); return 0; } RawStone StoneRotate(RawStone& stone, int manipulate_info) { RawStone rotated; switch (manipulate_info) { case ROTATE_90: for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x){ rotated[y][x] = stone[x][7-y]; } } return rotated; case ROTATE_180: return StoneRotate(std::move(StoneRotate(stone, ROTATE_90)), ROTATE_90); case ROTATE_270: return StoneRotate(std::move(StoneRotate(stone, ROTATE_180)), ROTATE_90); case REVERSED: for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x) { rotated[y][x] = stone[y][7-x]; } } return rotated; case REVERSED | ROTATE_90: return StoneRotate(std::move(StoneRotate(stone, ROTATE_90), REVERSED); case REVERSED | ROTATE_180: return StoneRotate(std::move(StoneRotate(stone, ROTATE_180), REVERSED); case REVERSED | ROTATE_270: return StoneRotate(std::move(StoneRotate(stone, ROTATE_270), REVERSED); } return stone; } bool Field::TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info) { // 書き換えるので、もどせるようにしておく RawField backup_field = raw; int backup_score = score; RawStone& sraw = reserved_stones[stone_number].raw; for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { if (y + base_y < 0 || y + base_y >= 32 || x + base_x < 0 || x + base_x >= 32) { continue; } if (sraw[y][x] == '1') { if(backup_score != 0 && raw[y + base_y][x + base_x] == '1') { //score = 1、つまり最初に置く石なら判定しない raw = backup_field; score = backup_score; return false; } raw[y + base_y][x + base_x] = '1'; ++score; } } } return true; } <commit_msg>add a test: StoneRotate<commit_after>#include<iostream> #include <cstdlib> #include <cstdio> #include <array> #include <utility> #include <boost/test/unit_test.hpp> using RawField = std::array<std::array<char, 32>, 32>; using RawStone = std::array<std::array<char, 8>, 8>; constexpr int ROTATE_90 = 1, ROTATE_180 = 2, ROTATE_270 = 4, REVERSED = 8; class Field { private: int score = 0; public: RawField raw = {}; int Score() const { return score; } bool TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info); }; class Stone { public: RawStone raw = {}; }; Field max_score_field; Stone reserved_stones[256]; int number_of_stone = 0; void Parse(Field* f) { for (int i = 0; i < 32; ++i) { fread(f->raw[i].data(), sizeof(char[32]), 1, stdin); getchar(); //CR getchar(); //LF } scanf("\n%d\n", &number_of_stone); for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { fread(reserved_stones[i].raw[j].data(), sizeof(char[8]), 1, stdin); getchar(); //CR getchar(); //LF } getchar(); //CR getchar(); //LF } } void DumpField(const Field& f) { for (int i = 0; i < 32; ++i) { for (int j = 0; j < 32; ++j) { putc(f.raw[i][j], stdout); } puts(""); } } void Solve(Field f, const int look_nth_stone) { if (look_nth_stone > number_of_stone) { if (f.Score() > max_score_field.Score()) { max_score_field = f; } return; } Solve(f, look_nth_stone + 1); Field backup = f; for (int x = -7; x < 32; ++x) { for (int y = -7; y < 32; ++y) { if (f.TryPutStone(look_nth_stone, x, y, 0)) { Solve(f, look_nth_stone+1); f = backup; } } } } void DumpStones() { for (int i = 0; i < number_of_stone; ++i) { for (int j = 0; j < 8; ++j) { for (int k = 0; k < 8; ++k) { putc(reserved_stones[i].raw[j][k], stdout); } puts(""); } puts(""); } } int main() { Field reserved_field; // get_problemfile(); Parse(&reserved_field); Solve(reserved_field, 0); DumpField(max_score_field); // solve(); // submit_answer(); return 0; } RawStone StoneRotate(RawStone& stone, int manipulate_info) { RawStone rotated; switch (manipulate_info) { case ROTATE_90: for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x){ rotated[y][x] = stone[x][7-y]; } } return rotated; case ROTATE_180: return StoneRotate(std::move(StoneRotate(stone, ROTATE_90)), ROTATE_90); case ROTATE_270: return StoneRotate(std::move(StoneRotate(stone, ROTATE_180)), ROTATE_90); case REVERSED: for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x) { rotated[y][x] = stone[y][7-x]; } } return rotated; case REVERSED | ROTATE_90: return StoneRotate(std::move(StoneRotate(stone, ROTATE_90), REVERSED); case REVERSED | ROTATE_180: return StoneRotate(std::move(StoneRotate(stone, ROTATE_180), REVERSED); case REVERSED | ROTATE_270: return StoneRotate(std::move(StoneRotate(stone, ROTATE_270), REVERSED); } return stone; } bool Field::TryPutStone(int stone_number, int base_x, int base_y, int manipulate_info) { // 書き換えるので、もどせるようにしておく RawField backup_field = raw; int backup_score = score; RawStone& sraw = reserved_stones[stone_number].raw; for (int x = 0; x < 8; ++x) { for (int y = 0; y < 8; ++y) { if (y + base_y < 0 || y + base_y >= 32 || x + base_x < 0 || x + base_x >= 32) { continue; } if (sraw[y][x] == '1') { if(backup_score != 0 && raw[y + base_y][x + base_x] == '1') { //score = 1、つまり最初に置く石なら判定しない raw = backup_field; score = backup_score; return false; } raw[y + base_y][x + base_x] = '1'; ++score; } } } return true; } // BOOST_AUTO_TEST_CASE(StoneRotate_Test) { RawStone rawstone = { "11111111", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000", "00000000" }; RawStone rotated_90 = { "00000001", "00000001", "00000001", "00000001", "00000001", "00000001", "00000001", "00000001" }; RawStone rotated_by_f = std::move(StoneRotate(rawstone)); BOOST_CHECK_EQUAL(rotated_90, rotated_by_f); } <|endoftext|>
<commit_before>#include "highlighters.hh" #include "assert.hh" #include "window.hh" #include "highlighter_registry.hh" #include "highlighter_group.hh" #include "regex.hh" namespace Kakoune { using namespace std::placeholders; typedef boost::regex_iterator<BufferIterator> RegexIterator; template<typename T> void highlight_range(DisplayBuffer& display_buffer, BufferIterator begin, BufferIterator end, bool skip_replaced, T func) { if (begin == end or end <= display_buffer.range().first or begin >= display_buffer.range().second) return; for (auto& line : display_buffer.lines()) { if (line.buffer_line() >= begin.line() and line.buffer_line() <= end.line()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { bool is_replaced = atom_it->content.type() == AtomContent::ReplacedBufferRange; if (not atom_it->content.has_buffer_range() or (skip_replaced and is_replaced)) continue; if (end <= atom_it->content.begin() or begin >= atom_it->content.end()) continue; if (not is_replaced and begin > atom_it->content.begin()) atom_it = ++line.split(atom_it, begin); if (not is_replaced and end < atom_it->content.end()) { atom_it = line.split(atom_it, end); func(*atom_it); ++atom_it; } else func(*atom_it); } } } } typedef std::unordered_map<size_t, std::pair<Color, Color>> ColorSpec; class RegexColorizer { public: RegexColorizer(Regex regex, ColorSpec colors) : m_regex(std::move(regex)), m_colors(std::move(colors)), m_cache_timestamp(0) { } void operator()(DisplayBuffer& display_buffer) { update_cache_ifn(display_buffer.range()); for (auto& match : m_cache_matches) { for (size_t n = 0; n < match.size(); ++n) { auto col_it = m_colors.find(n); if (col_it == m_colors.end()) continue; highlight_range(display_buffer, match[n].first, match[n].second, true, [&](DisplayAtom& atom) { atom.fg_color = col_it->second.first; atom.bg_color = col_it->second.second; }); } } } private: BufferRange m_cache_range; size_t m_cache_timestamp; std::vector<boost::match_results<BufferIterator>> m_cache_matches; Regex m_regex; ColorSpec m_colors; void update_cache_ifn(const BufferRange& range) { const Buffer& buf = range.first.buffer(); if (m_cache_range.first.is_valid() and &m_cache_range.first.buffer() == &buf and buf.timestamp() == m_cache_timestamp and range.first >= m_cache_range.first and range.second <= m_cache_range.second) return; m_cache_matches.clear(); m_cache_range.first = buf.iterator_at({range.first.line() - 10, 0}); m_cache_range.second = buf.iterator_at({range.second.line() + 10, 0}); m_cache_timestamp = buf.timestamp(); RegexIterator re_it(m_cache_range.first, m_cache_range.second, m_regex); RegexIterator re_end; for (; re_it != re_end; ++re_it) m_cache_matches.push_back(*re_it); } }; Color parse_color(const String& color) { if (color == "default") return Color::Default; if (color == "black") return Color::Black; if (color == "red") return Color::Red; if (color == "green") return Color::Green; if (color == "yellow") return Color::Yellow; if (color == "blue") return Color::Blue; if (color == "magenta") return Color::Magenta; if (color == "cyan") return Color::Cyan; if (color == "white") return Color::White; return Color::Default; } HighlighterAndId colorize_regex_factory(Window& window, const HighlighterParameters params) { if (params.size() < 2) throw runtime_error("wrong parameter count"); try { static Regex color_spec_ex(LR"((\d+):(\w+)(,(\w+))?)"); ColorSpec colors; for (auto it = params.begin() + 1; it != params.end(); ++it) { boost::match_results<String::iterator> res; if (not boost::regex_match(it->begin(), it->end(), res, color_spec_ex)) throw runtime_error("wrong colorspec: '" + *it + "' expected <capture>:<fgcolor>[,<bgcolor>]"); int capture = str_to_int(String(res[1].first, res[1].second)); Color fg_color = parse_color(String(res[2].first, res[2].second)); Color bg_color = res[4].matched ? parse_color(String(res[4].first, res[4].second)) : Color::Default; colors[capture] = { fg_color, bg_color }; } String id = "colre'" + params[0] + "'"; Regex ex(params[0].begin(), params[0].end(), boost::regex::perl | boost::regex::optimize); return HighlighterAndId(id, RegexColorizer(std::move(ex), std::move(colors))); } catch (boost::regex_error& err) { throw runtime_error(String("regex error: ") + err.what()); } } void expand_tabulations(Window& window, DisplayBuffer& display_buffer) { const int tabstop = window.option_manager()["tabstop"].as_int(); for (auto& line : display_buffer.lines()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { if (atom_it->content.type() != AtomContent::BufferRange) continue; auto begin = atom_it->content.begin(); auto end = atom_it->content.end(); for (BufferIterator it = begin; it != end; ++it) { if (*it == '\t') { if (it != begin) atom_it = ++line.split(atom_it, it); if (it+1 != end) atom_it = line.split(atom_it, it+1); int column = 0; for (auto line_it = it.buffer().iterator_at_line_begin(it); line_it != it; ++line_it) { assert(*line_it != '\n'); if (*line_it == '\t') column += tabstop - (column % tabstop); else ++column; } int count = tabstop - (column % tabstop); String padding; for (int i = 0; i < count; ++i) padding += ' '; atom_it->content.replace(padding); break; } } } } } void show_line_numbers(Window& window, DisplayBuffer& display_buffer) { int last_line = window.buffer().line_count(); int digit_count = 0; for (int c = last_line; c > 0; c /= 10) ++digit_count; char format[] = "%?d "; format[1] = '0' + digit_count; for (auto& line : display_buffer.lines()) { char buffer[10]; snprintf(buffer, 10, format, line.buffer_line() + 1); DisplayAtom atom = DisplayAtom(AtomContent(buffer)); atom.fg_color = Color::Black; atom.bg_color = Color::White; line.insert(line.begin(), std::move(atom)); } } void highlight_selections(Window& window, DisplayBuffer& display_buffer) { for (auto& sel : window.selections()) { highlight_range(display_buffer, sel.begin(), sel.end(), false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Underline; }); const BufferIterator& last = sel.last(); highlight_range(display_buffer, last, last+1, false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Reverse; }); } } template<void (*highlighter_func)(DisplayBuffer&)> class SimpleHighlighterFactory { public: SimpleHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, HighlighterFunc(highlighter_func)); } private: String m_id; }; template<void (*highlighter_func)(Window&, DisplayBuffer&)> class WindowHighlighterFactory { public: WindowHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, std::bind(highlighter_func, std::ref(window), _1)); } private: String m_id; }; HighlighterAndId highlighter_group_factory(Window& window, const HighlighterParameters& params) { if (params.size() != 1) throw runtime_error("wrong parameter count"); return HighlighterAndId(params[0], HighlighterGroup()); } void register_highlighters() { HighlighterRegistry& registry = HighlighterRegistry::instance(); registry.register_factory("highlight_selections", WindowHighlighterFactory<highlight_selections>("highlight_selections")); registry.register_factory("expand_tabs", WindowHighlighterFactory<expand_tabulations>("expand_tabs")); registry.register_factory("number_lines", WindowHighlighterFactory<show_line_numbers>("number_lines")); registry.register_factory("regex", colorize_regex_factory); registry.register_factory("group", highlighter_group_factory); } } <commit_msg>RegexColorizer: fix last buffer line highlighting<commit_after>#include "highlighters.hh" #include "assert.hh" #include "window.hh" #include "highlighter_registry.hh" #include "highlighter_group.hh" #include "regex.hh" namespace Kakoune { using namespace std::placeholders; typedef boost::regex_iterator<BufferIterator> RegexIterator; template<typename T> void highlight_range(DisplayBuffer& display_buffer, BufferIterator begin, BufferIterator end, bool skip_replaced, T func) { if (begin == end or end <= display_buffer.range().first or begin >= display_buffer.range().second) return; for (auto& line : display_buffer.lines()) { if (line.buffer_line() >= begin.line() and line.buffer_line() <= end.line()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { bool is_replaced = atom_it->content.type() == AtomContent::ReplacedBufferRange; if (not atom_it->content.has_buffer_range() or (skip_replaced and is_replaced)) continue; if (end <= atom_it->content.begin() or begin >= atom_it->content.end()) continue; if (not is_replaced and begin > atom_it->content.begin()) atom_it = ++line.split(atom_it, begin); if (not is_replaced and end < atom_it->content.end()) { atom_it = line.split(atom_it, end); func(*atom_it); ++atom_it; } else func(*atom_it); } } } } typedef std::unordered_map<size_t, std::pair<Color, Color>> ColorSpec; class RegexColorizer { public: RegexColorizer(Regex regex, ColorSpec colors) : m_regex(std::move(regex)), m_colors(std::move(colors)), m_cache_timestamp(0) { } void operator()(DisplayBuffer& display_buffer) { update_cache_ifn(display_buffer.range()); for (auto& match : m_cache_matches) { for (size_t n = 0; n < match.size(); ++n) { auto col_it = m_colors.find(n); if (col_it == m_colors.end()) continue; highlight_range(display_buffer, match[n].first, match[n].second, true, [&](DisplayAtom& atom) { atom.fg_color = col_it->second.first; atom.bg_color = col_it->second.second; }); } } } private: BufferRange m_cache_range; size_t m_cache_timestamp; std::vector<boost::match_results<BufferIterator>> m_cache_matches; Regex m_regex; ColorSpec m_colors; void update_cache_ifn(const BufferRange& range) { const Buffer& buf = range.first.buffer(); if (m_cache_range.first.is_valid() and &m_cache_range.first.buffer() == &buf and buf.timestamp() == m_cache_timestamp and range.first >= m_cache_range.first and range.second <= m_cache_range.second) return; m_cache_matches.clear(); m_cache_range.first = buf.iterator_at_line_begin(range.first.line() - 10); m_cache_range.second = buf.iterator_at_line_end(range.second.line() + 10); m_cache_timestamp = buf.timestamp(); RegexIterator re_it(m_cache_range.first, m_cache_range.second, m_regex); RegexIterator re_end; for (; re_it != re_end; ++re_it) m_cache_matches.push_back(*re_it); } }; Color parse_color(const String& color) { if (color == "default") return Color::Default; if (color == "black") return Color::Black; if (color == "red") return Color::Red; if (color == "green") return Color::Green; if (color == "yellow") return Color::Yellow; if (color == "blue") return Color::Blue; if (color == "magenta") return Color::Magenta; if (color == "cyan") return Color::Cyan; if (color == "white") return Color::White; return Color::Default; } HighlighterAndId colorize_regex_factory(Window& window, const HighlighterParameters params) { if (params.size() < 2) throw runtime_error("wrong parameter count"); try { static Regex color_spec_ex(LR"((\d+):(\w+)(,(\w+))?)"); ColorSpec colors; for (auto it = params.begin() + 1; it != params.end(); ++it) { boost::match_results<String::iterator> res; if (not boost::regex_match(it->begin(), it->end(), res, color_spec_ex)) throw runtime_error("wrong colorspec: '" + *it + "' expected <capture>:<fgcolor>[,<bgcolor>]"); int capture = str_to_int(String(res[1].first, res[1].second)); Color fg_color = parse_color(String(res[2].first, res[2].second)); Color bg_color = res[4].matched ? parse_color(String(res[4].first, res[4].second)) : Color::Default; colors[capture] = { fg_color, bg_color }; } String id = "colre'" + params[0] + "'"; Regex ex(params[0].begin(), params[0].end(), boost::regex::perl | boost::regex::optimize); return HighlighterAndId(id, RegexColorizer(std::move(ex), std::move(colors))); } catch (boost::regex_error& err) { throw runtime_error(String("regex error: ") + err.what()); } } void expand_tabulations(Window& window, DisplayBuffer& display_buffer) { const int tabstop = window.option_manager()["tabstop"].as_int(); for (auto& line : display_buffer.lines()) { for (auto atom_it = line.begin(); atom_it != line.end(); ++atom_it) { if (atom_it->content.type() != AtomContent::BufferRange) continue; auto begin = atom_it->content.begin(); auto end = atom_it->content.end(); for (BufferIterator it = begin; it != end; ++it) { if (*it == '\t') { if (it != begin) atom_it = ++line.split(atom_it, it); if (it+1 != end) atom_it = line.split(atom_it, it+1); int column = 0; for (auto line_it = it.buffer().iterator_at_line_begin(it); line_it != it; ++line_it) { assert(*line_it != '\n'); if (*line_it == '\t') column += tabstop - (column % tabstop); else ++column; } int count = tabstop - (column % tabstop); String padding; for (int i = 0; i < count; ++i) padding += ' '; atom_it->content.replace(padding); break; } } } } } void show_line_numbers(Window& window, DisplayBuffer& display_buffer) { int last_line = window.buffer().line_count(); int digit_count = 0; for (int c = last_line; c > 0; c /= 10) ++digit_count; char format[] = "%?d "; format[1] = '0' + digit_count; for (auto& line : display_buffer.lines()) { char buffer[10]; snprintf(buffer, 10, format, line.buffer_line() + 1); DisplayAtom atom = DisplayAtom(AtomContent(buffer)); atom.fg_color = Color::Black; atom.bg_color = Color::White; line.insert(line.begin(), std::move(atom)); } } void highlight_selections(Window& window, DisplayBuffer& display_buffer) { for (auto& sel : window.selections()) { highlight_range(display_buffer, sel.begin(), sel.end(), false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Underline; }); const BufferIterator& last = sel.last(); highlight_range(display_buffer, last, last+1, false, [](DisplayAtom& atom) { atom.attribute |= Attributes::Reverse; }); } } template<void (*highlighter_func)(DisplayBuffer&)> class SimpleHighlighterFactory { public: SimpleHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, HighlighterFunc(highlighter_func)); } private: String m_id; }; template<void (*highlighter_func)(Window&, DisplayBuffer&)> class WindowHighlighterFactory { public: WindowHighlighterFactory(const String& id) : m_id(id) {} HighlighterAndId operator()(Window& window, const HighlighterParameters& params) const { return HighlighterAndId(m_id, std::bind(highlighter_func, std::ref(window), _1)); } private: String m_id; }; HighlighterAndId highlighter_group_factory(Window& window, const HighlighterParameters& params) { if (params.size() != 1) throw runtime_error("wrong parameter count"); return HighlighterAndId(params[0], HighlighterGroup()); } void register_highlighters() { HighlighterRegistry& registry = HighlighterRegistry::instance(); registry.register_factory("highlight_selections", WindowHighlighterFactory<highlight_selections>("highlight_selections")); registry.register_factory("expand_tabs", WindowHighlighterFactory<expand_tabulations>("expand_tabs")); registry.register_factory("number_lines", WindowHighlighterFactory<show_line_numbers>("number_lines")); registry.register_factory("regex", colorize_regex_factory); registry.register_factory("group", highlighter_group_factory); } } <|endoftext|>
<commit_before>/*-------------traverse.cpp---------------------------------------------------// * * Purpose: This file tests multiple ways to traverse a tree * *-----------------------------------------------------------------------------*/ #include <iostream> #include <stack> #include <queue> struct node{ node *parent; node **children; int num_children; int ID; }; // Function to create simple tree void create_tree(node* &root, int num_row, int num_child); // Function to do a depth-first search recursively void DFS_recursive(node* &root); // Function to do a depth-first search with a stack void DFS_stack(); // Function to do a breadth-first search with a queue void BFS_queue(); int main(){ // Creating tree node *root; create_tree(root, 3, 3); std::cout << "Tree created!" << '\n'; DFS_recursive(root); } // Function to create simple tree void create_tree(node* &root, int num_row, int num_child){ root = new node; root->ID = num_row; root->num_children = num_child; root->children = new node*[num_child]; if (num_row > 0){ for (int i = 0; i < num_child; ++i){ create_tree(root->children[i], num_row - 1, num_child); } } } // Function to do a depth-first search recursively void DFS_recursive(node* &root){ if (!root){return;} std::cout << root->ID << '\n'; for (int i = 0; i < root->num_children; ++i){ DFS_recursive(root->children[i]); } } <commit_msg>adding method without pointers.<commit_after>/*-------------traverse.cpp---------------------------------------------------// * * Purpose: This file tests multiple ways to traverse a tree * *-----------------------------------------------------------------------------*/ #include <iostream> #include <stack> #include <queue> #include <vector> struct node{ std::vector<node> children; int ID; }; // Function to create simple tree void create_tree(node& root, int num_row, int num_child); // Function to do a depth-first search recursively void DFS_recursive(const node& root); // Function to do a depth-first search with a stack void DFS_stack(); // Function to do a breadth-first search with a queue void BFS_queue(); int main(){ // Creating tree node root; create_tree(root, 3, 2); std::cout << "Tree created!" << '\n'; DFS_recursive(root); } // Function to create simple tree void create_tree(node& root, int num_row, int num_child){ root.ID = num_row; if (num_row == 0){ return; } root.children.reserve(num_child); for (int i = 0; i < num_child; ++i){ node child; create_tree(child, num_row - 1, num_child); root.children.push_back(child); } } // Function to do a depth-first search recursively void DFS_recursive(const node& root){ if (root.children.size() == 0){ return; } std::cout << root.ID << '\n'; for (int i = 0; i < root.children.size(); ++i){ DFS_recursive(root.children[i]); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Iterator implementation for ETL expressions. */ #pragma once #include <iterator> namespace etl { /*! * \brief Configurable iterator for ETL expressions * \tparam Expr The type of expr for which the iterator is working * \tparam Ref Indicates if the iterator returns reference. * \tparam Const Indicates if the iterator returns const reference only. */ template <typename Expr, bool Ref = false, bool Const = true> struct iterator : public std::iterator<std::random_access_iterator_tag, value_t<Expr>> { private: Expr* expr; ///< Pointer to the expression std::size_t i; ///< Current index public: using base_iterator_t = std::iterator<std::random_access_iterator_tag, value_t<Expr>>; ///< The base iterator type using value_type = value_t<Expr>; ///< The value type using reference_t = std::conditional_t<Ref, std::conditional_t<Const, const value_type&, value_type&>, value_type>; ///< The type of reference using pointer_t = std::conditional_t<Const, const value_type*, value_type*>; ///< The type of pointer using difference_t = typename base_iterator_t::difference_type; ///< The type used for subtracting two iterators /*! * \brief Construct a new iterator * \param expr The expr to iterate over. * \param i The starting position */ iterator(Expr& expr, std::size_t i) : expr(&expr), i(i) {} /*! * \brief Dereference the iterator to get the current value * \return a reference to the current element */ reference_t operator*() { return (*expr)[i]; } /*! * \brief Dereferences the iterator at n forward position * \param n The number of forward position to advance * \return a reference to the element at the current position plus n */ reference_t operator[](difference_t n) { return (*expr)[i + n]; } /*! * \brief Dereference the iterator to get the current value * \return a pointer to the current element */ pointer_t operator->() { return &(*expr)[i]; } /*! * \brief Predecrement the iterator * \return a reference to the iterator */ iterator& operator--() { --i; return *this; } /*! * \brief Postdecrement the iterator * \return an iterator the position prior to the decrement. */ iterator operator--(int) { iterator prev(*this); --i; return prev; } /*! * \brief Preincrement the iterator * \return a reference to the iterator */ iterator& operator++() { ++i; return *this; } /*! * \brief Postincrement the iterator * \return an iterator the position prior to the increment. */ iterator operator++(int) { iterator prev(*this); ++i; return prev; } /*! * \brief Advances the iterator n positions * \param n The number of position to advance * \return a reference to the iterator */ iterator& operator+=(difference_t n) { i += n; return *this; } /*! * \brief Back away the iterator n positions * \param n The number of position to back * \return a reference to the iterator */ iterator& operator-=(difference_t n) { i -= n; return *this; } /*! * \brief Creates a new iterator poiting to the current position plus n * \param n The number of position to advance * \return the new interator */ iterator operator+(difference_t n) { iterator it(*this); it += n; return it; } /*! * \brief Creates a new iterator poiting to the current position minus n * \param n The number of position to back away * \return the new interator */ iterator operator-(difference_t n) { iterator it(*this); it -= n; return it; } /*! * \brief Computes the difference between two iterators * \param it the other iterator * \return the number of positions between the two iterators */ difference_t operator-(const iterator& it) { return i - it.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is equal to the other iterator */ bool operator==(const iterator& other) const { return expr == other.expr && i == other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is not equal to the other iterator */ bool operator!=(const iterator& other) const { return !(*this == other); } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is greater than the other iterator */ bool operator>(const iterator& other) const { return i > other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is greater than or equal to the other iterator */ bool operator>=(const iterator& other) const { return i >= other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is less than the other iterator */ bool operator<(const iterator& other) const { return i < other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is less than or equal to the other iterator */ bool operator<=(const iterator& other) const { return i <= other.i; } }; } //end of namespace etl <commit_msg>Cleanup<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Iterator implementation for ETL expressions. */ #pragma once #include <iterator> namespace etl { /*! * \brief Configurable iterator for ETL expressions * \tparam Expr The type of expr for which the iterator is working * \tparam Ref Indicates if the iterator returns reference. * \tparam Const Indicates if the iterator returns const reference only. */ template <typename Expr, bool Ref = false, bool Const = true> struct iterator : public std::iterator<std::random_access_iterator_tag, value_t<Expr>> { private: Expr* expr; ///< Pointer to the expression std::size_t i; ///< Current index public: using base_iterator_t = std::iterator<std::random_access_iterator_tag, value_t<Expr>>; ///< The base iterator type using value_type = value_t<Expr>; ///< The value type using reference_t = std::conditional_t<Ref, std::conditional_t<Const, const value_type&, value_type&>, value_type>; ///< The type of reference using pointer_t = std::conditional_t<Const, const value_type*, value_type*>; ///< The type of pointer using difference_t = typename base_iterator_t::difference_type; ///< The type used for subtracting two iterators /*! * \brief Construct a new iterator * \param expr The expr to iterate over. * \param i The starting position */ iterator(Expr& expr, std::size_t i) : expr(&expr), i(i) {} /*! * \brief Dereference the iterator to get the current value * \return a reference to the current element */ reference_t operator*() { return (*expr)[i]; } /*! * \brief Dereferences the iterator at n forward position * \param n The number of forward position to advance * \return a reference to the element at the current position plus n */ reference_t operator[](difference_t n) { return (*expr)[i + n]; } /*! * \brief Dereference the iterator to get the current value * \return a pointer to the current element */ pointer_t operator->() { return &(*expr)[i]; } /*! * \brief Predecrement the iterator * \return a reference to the iterator */ iterator& operator--() { --i; return *this; } /*! * \brief Postdecrement the iterator * \return an iterator the position prior to the decrement. */ iterator operator--(int) { iterator prev(*this); --i; return prev; } /*! * \brief Preincrement the iterator * \return a reference to the iterator */ iterator& operator++() { ++i; return *this; } /*! * \brief Postincrement the iterator * \return an iterator the position prior to the increment. */ iterator operator++(int) { iterator prev(*this); ++i; return prev; } /*! * \brief Advances the iterator n positions * \param n The number of position to advance * \return a reference to the iterator */ iterator& operator+=(difference_t n) { i += n; return *this; } /*! * \brief Back away the iterator n positions * \param n The number of position to back * \return a reference to the iterator */ iterator& operator-=(difference_t n) { i -= n; return *this; } /*! * \brief Creates a new iterator poiting to the current position plus n * \param n The number of position to advance * \return the new interator */ iterator operator+(difference_t n) { iterator it(*this); it += n; return it; } /*! * \brief Creates a new iterator poiting to the current position minus n * \param n The number of position to back away * \return the new interator */ iterator operator-(difference_t n) { iterator it(*this); it -= n; return it; } /*! * \brief Computes the difference between two iterators * \param it the other iterator * \return the number of positions between the two iterators */ difference_t operator-(const iterator& it) { return i - it.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is equal to the other iterator */ bool operator==(const iterator& other) const { return expr == other.expr && i == other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is not equal to the other iterator */ bool operator!=(const iterator& other) const { return !(*this == other); } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is greater than the other iterator */ bool operator>(const iterator& other) const { return i > other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is greater than or equal to the other iterator */ bool operator>=(const iterator& other) const { return i >= other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is less than the other iterator */ bool operator<(const iterator& other) const { return i < other.i; } /*! * \brief Compare two iterators * \param other The other iterator * \return true if this operator is less than or equal to the other iterator */ bool operator<=(const iterator& other) const { return i <= other.i; } }; } //end of namespace etl <|endoftext|>
<commit_before> #include <ros/ros.h> #include <gtest/gtest.h> #include <control_toolbox/pid.h> using namespace control_toolbox; TEST(ParameterTest, zeroITermBadIBoundsTest) { RecordProperty("description","This test checks robustness against poorly-defined integral term bounds."); Pid pid(1.0, 0.0, 0.0, -1.0, 0.0); double cmd = 0.0; double pe,ie,de; cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-1.0, ie); EXPECT_EQ(2.0, cmd); cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-2.0, ie); EXPECT_EQ(2.0, cmd); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Specifying div-by-zero test, adding other integral term tests<commit_after> #include <ros/ros.h> #include <gtest/gtest.h> #include <control_toolbox/pid.h> #include <boost/math/special_functions/fpclassify.hpp> using namespace control_toolbox; TEST(ParameterTest, zeroITermBadIBoundsTest) { RecordProperty("description","This test checks robustness against divide-by-zero errors when given integral term bounds which do not include 0.0."); Pid pid(1.0, 0.0, 0.0, -1.0, 0.0); double cmd = 0.0; double pe,ie,de; cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_FALSE(boost::math::isinf(ie)); EXPECT_FALSE(boost::math::isnan(cmd)); cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_FALSE(boost::math::isinf(ie)); EXPECT_FALSE(boost::math::isnan(cmd)); } TEST(ParameterTest, integrationWindupTest) { RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is non-zero."); Pid pid(0.0, 1.0, 0.0, 1.0, -1.0); double cmd = 0.0; double pe,ie,de; cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-1.0, ie); EXPECT_EQ(1.0, cmd); cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_EQ(-1.0, ie); EXPECT_EQ(1.0, cmd); } TEST(ParameterTest, integrationWindupZeroGainTest) { RecordProperty("description","This test succeeds if the integral error is prevented from winding up when the integral gain is zero. If the integral error is allowed to wind up while it is disabled, it can cause sudden jumps to the minimum or maximum bound in control command when re-enabled."); double i_gain = 0.0; double i_min = -1.0; double i_max = 1.0; Pid pid(0.0, i_gain, 0.0, i_max, i_min); double cmd = 0.0; double pe,ie,de; cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_LE(i_min, ie); EXPECT_LE(ie, i_max); EXPECT_EQ(0.0, cmd); cmd = pid.updatePid(-1.0, ros::Duration(1.0)); pid.getCurrentPIDErrors(&pe,&ie,&de); EXPECT_LE(i_min, ie); EXPECT_LE(ie, i_max); EXPECT_EQ(0.0, cmd); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* Nazara Engine - Assimp Plugin Copyright (C) 2015 Jérôme "Lynix" Leclercq (lynix680@gmail.com) 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 <CustomStream.hpp> #include <Nazara/Core/String.hpp> #include <Nazara/Utility/Mesh.hpp> #include <Nazara/Utility/IndexIterator.hpp> #include <Nazara/Utility/IndexMapper.hpp> #include <Nazara/Utility/StaticMesh.hpp> #include <assimp/cfileio.h> #include <assimp/cimport.h> #include <assimp/config.h> #include <assimp/mesh.h> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <set> using namespace Nz; void ProcessJoints(aiNode* node, Skeleton* skeleton, const std::set<Nz::String>& joints) { Nz::String jointName(node->mName.data, node->mName.length); if (joints.count(jointName)) { Joint* joint = skeleton->GetJoint(jointName); if (joint) { if (node->mParent) joint->SetParent(skeleton->GetJoint(node->mParent->mName.C_Str())); Matrix4f transformMatrix(node->mTransformation.a1, node->mTransformation.a2, node->mTransformation.a3, node->mTransformation.a4, node->mTransformation.b1, node->mTransformation.b2, node->mTransformation.b3, node->mTransformation.b4, node->mTransformation.c1, node->mTransformation.c2, node->mTransformation.c3, node->mTransformation.c4, node->mTransformation.d1, node->mTransformation.d2, node->mTransformation.d3, node->mTransformation.d4); transformMatrix.InverseAffine(); joint->SetInverseBindMatrix(transformMatrix); } } for (unsigned int i = 0; i < node->mNumChildren; ++i) ProcessJoints(node->mChildren[i], skeleton, joints); } bool IsSupported(const String& extension) { String dotExt = '.' + extension; return (aiIsExtensionSupported(dotExt.GetConstBuffer()) == AI_TRUE); } Ternary Check(Stream& stream, const MeshParams& parameters) { bool skip; if (parameters.custom.GetBooleanParameter("SkipAssimpLoader", &skip) && skip) return Ternary_False; return Ternary_Unknown; } bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) { Nz::String streamPath = stream.GetPath(); FileIOUserdata userdata; userdata.originalFilePath = (!streamPath.IsEmpty()) ? streamPath.GetConstBuffer() : StreamPath; userdata.originalStream = &stream; aiFileIO fileIO; fileIO.CloseProc = StreamCloser; fileIO.OpenProc = StreamOpener; fileIO.UserData = reinterpret_cast<char*>(&userdata); unsigned int postProcess = aiProcess_CalcTangentSpace | aiProcess_JoinIdenticalVertices | aiProcess_MakeLeftHanded | aiProcess_Triangulate | aiProcess_RemoveComponent | aiProcess_GenSmoothNormals | aiProcess_SplitLargeMeshes | aiProcess_LimitBoneWeights | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials | aiProcess_FixInfacingNormals | aiProcess_SortByPType | aiProcess_FindInvalidData | aiProcess_GenUVCoords | aiProcess_TransformUVCoords | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph | aiProcess_FlipWindingOrder | aiProcess_Debone; if (!parameters.flipUVs) postProcess |= aiProcess_FlipUVs; if (parameters.optimizeIndexBuffers) postProcess |= aiProcess_ImproveCacheLocality; float smoothingAngle = 80.f; parameters.custom.GetFloatParameter("AssimpLoader_SmoothingAngle", &smoothingAngle); int triangleLimit = 1'000'000; parameters.custom.GetIntegerParameter("AssimpLoader_TriangleLimit", &triangleLimit); int vertexLimit = 1'000'000; parameters.custom.GetIntegerParameter("AssimpLoader_VertexLimit", &vertexLimit); aiPropertyStore* properties = aiCreatePropertyStore(); aiSetImportPropertyFloat(properties, AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, smoothingAngle); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_SBP_REMOVE, ~aiPrimitiveType_TRIANGLE); //< We only want triangles aiSetImportPropertyInteger(properties, AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, triangleLimit); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_SLM_VERTEX_LIMIT, vertexLimit); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_RVC_FLAGS, aiComponent_COLORS); const aiScene* scene = aiImportFileExWithProperties(userdata.originalFilePath, postProcess, &fileIO, properties); aiReleasePropertyStore(properties); std::set<Nz::String> joints; bool animatedMesh = false; if (parameters.animated) { for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { aiMesh* mesh = scene->mMeshes[i]; if (mesh->HasBones()) // Inline functions can be safely called { animatedMesh = true; for (unsigned int j = 0; j < mesh->mNumBones; ++j) joints.insert(mesh->mBones[j]->mName.C_Str()); } } } if (animatedMesh) { mesh->CreateSkeletal(joints.size()); Skeleton* skeleton = mesh->GetSkeleton(); // First, assign names unsigned int jointIndex = 0; for (const Nz::String& jointName : joints) skeleton->GetJoint(jointIndex++)->SetName(jointName); ProcessJoints(scene->mRootNode, skeleton, joints); return false; } else { mesh->CreateStatic(); for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { aiMesh* iMesh = scene->mMeshes[i]; if (!iMesh->HasBones()) // Don't process skeletal meshs { unsigned int indexCount = iMesh->mNumFaces * 3; unsigned int vertexCount = iMesh->mNumVertices; // Index buffer bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max()); IndexBufferRef indexBuffer = IndexBuffer::New(largeIndices, indexCount, parameters.storage); IndexMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); IndexIterator index = indexMapper.begin(); for (unsigned int j = 0; j < iMesh->mNumFaces; ++j) { aiFace& face = iMesh->mFaces[j]; if (face.mNumIndices != 3) NazaraWarning("Assimp plugin: This face is not a triangle!"); *index++ = face.mIndices[0]; *index++ = face.mIndices[1]; *index++ = face.mIndices[2]; } indexMapper.Unmap(); // Vertex buffer VertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent), vertexCount, parameters.storage); BufferMapper<VertexBuffer> vertexMapper(vertexBuffer, BufferAccess_WriteOnly); MeshVertex* vertex = static_cast<MeshVertex*>(vertexMapper.GetPointer()); for (unsigned int j = 0; j < vertexCount; ++j) { aiVector3D position = iMesh->mVertices[j]; aiVector3D normal = iMesh->mNormals[j]; aiVector3D tangent = iMesh->mTangents[j]; aiVector3D uv = iMesh->mTextureCoords[0][j]; vertex->position = parameters.scale * Vector3f(position.x, position.y, position.z); vertex->normal.Set(normal.x, normal.y, normal.z); vertex->tangent.Set(tangent.x, tangent.y, tangent.z); vertex->uv.Set(uv.x, uv.y); vertex++; } vertexMapper.Unmap(); // Submesh StaticMeshRef subMesh = StaticMesh::New(mesh); subMesh->Create(vertexBuffer); subMesh->SetIndexBuffer(indexBuffer); subMesh->GenerateAABB(); subMesh->SetMaterialIndex(iMesh->mMaterialIndex); mesh->AddSubMesh(subMesh); } } if (parameters.center) mesh->Recenter(); } aiReleaseImport(scene); return true; } extern "C" { NAZARA_EXPORT int PluginLoad() { Nz::MeshLoader::RegisterLoader(IsSupported, Check, Load); return 1; } NAZARA_EXPORT void PluginUnload() { Nz::MeshLoader::UnregisterLoader(IsSupported, Check, Load); } } <commit_msg>Plugins/Assimp: Add material loading<commit_after>/* Nazara Engine - Assimp Plugin Copyright (C) 2015 Jérôme "Lynix" Leclercq (lynix680@gmail.com) 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 <CustomStream.hpp> #include <Nazara/Core/String.hpp> #include <Nazara/Utility/Mesh.hpp> #include <Nazara/Utility/IndexIterator.hpp> #include <Nazara/Utility/IndexMapper.hpp> #include <Nazara/Utility/MaterialData.hpp> #include <Nazara/Utility/StaticMesh.hpp> #include <assimp/cfileio.h> #include <assimp/cimport.h> #include <assimp/config.h> #include <assimp/mesh.h> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <set> using namespace Nz; void ProcessJoints(aiNode* node, Skeleton* skeleton, const std::set<Nz::String>& joints) { Nz::String jointName(node->mName.data, node->mName.length); if (joints.count(jointName)) { Joint* joint = skeleton->GetJoint(jointName); if (joint) { if (node->mParent) joint->SetParent(skeleton->GetJoint(node->mParent->mName.C_Str())); Matrix4f transformMatrix(node->mTransformation.a1, node->mTransformation.a2, node->mTransformation.a3, node->mTransformation.a4, node->mTransformation.b1, node->mTransformation.b2, node->mTransformation.b3, node->mTransformation.b4, node->mTransformation.c1, node->mTransformation.c2, node->mTransformation.c3, node->mTransformation.c4, node->mTransformation.d1, node->mTransformation.d2, node->mTransformation.d3, node->mTransformation.d4); transformMatrix.InverseAffine(); joint->SetInverseBindMatrix(transformMatrix); } } for (unsigned int i = 0; i < node->mNumChildren; ++i) ProcessJoints(node->mChildren[i], skeleton, joints); } bool IsSupported(const String& extension) { String dotExt = '.' + extension; return (aiIsExtensionSupported(dotExt.GetConstBuffer()) == AI_TRUE); } Ternary Check(Stream& stream, const MeshParams& parameters) { bool skip; if (parameters.custom.GetBooleanParameter("SkipAssimpLoader", &skip) && skip) return Ternary_False; return Ternary_Unknown; } bool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters) { Nz::String streamPath = stream.GetPath(); FileIOUserdata userdata; userdata.originalFilePath = (!streamPath.IsEmpty()) ? streamPath.GetConstBuffer() : StreamPath; userdata.originalStream = &stream; aiFileIO fileIO; fileIO.CloseProc = StreamCloser; fileIO.OpenProc = StreamOpener; fileIO.UserData = reinterpret_cast<char*>(&userdata); unsigned int postProcess = aiProcess_CalcTangentSpace | aiProcess_JoinIdenticalVertices | aiProcess_MakeLeftHanded | aiProcess_Triangulate | aiProcess_RemoveComponent | aiProcess_GenSmoothNormals | aiProcess_SplitLargeMeshes | aiProcess_LimitBoneWeights | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials | aiProcess_FixInfacingNormals | aiProcess_SortByPType | aiProcess_FindInvalidData | aiProcess_GenUVCoords | aiProcess_TransformUVCoords | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph | aiProcess_FlipWindingOrder | aiProcess_Debone; if (!parameters.flipUVs) postProcess |= aiProcess_FlipUVs; if (parameters.optimizeIndexBuffers) postProcess |= aiProcess_ImproveCacheLocality; float smoothingAngle = 80.f; parameters.custom.GetFloatParameter("AssimpLoader_SmoothingAngle", &smoothingAngle); int triangleLimit = 1'000'000; parameters.custom.GetIntegerParameter("AssimpLoader_TriangleLimit", &triangleLimit); int vertexLimit = 1'000'000; parameters.custom.GetIntegerParameter("AssimpLoader_VertexLimit", &vertexLimit); aiPropertyStore* properties = aiCreatePropertyStore(); aiSetImportPropertyFloat(properties, AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, smoothingAngle); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_SBP_REMOVE, ~aiPrimitiveType_TRIANGLE); //< We only want triangles aiSetImportPropertyInteger(properties, AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, triangleLimit); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_SLM_VERTEX_LIMIT, vertexLimit); aiSetImportPropertyInteger(properties, AI_CONFIG_PP_RVC_FLAGS, aiComponent_COLORS); const aiScene* scene = aiImportFileExWithProperties(userdata.originalFilePath, postProcess, &fileIO, properties); aiReleasePropertyStore(properties); std::set<Nz::String> joints; bool animatedMesh = false; if (parameters.animated) { for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { aiMesh* mesh = scene->mMeshes[i]; if (mesh->HasBones()) // Inline functions can be safely called { animatedMesh = true; for (unsigned int j = 0; j < mesh->mNumBones; ++j) joints.insert(mesh->mBones[j]->mName.C_Str()); } } } if (animatedMesh) { mesh->CreateSkeletal(joints.size()); Skeleton* skeleton = mesh->GetSkeleton(); // First, assign names unsigned int jointIndex = 0; for (const Nz::String& jointName : joints) skeleton->GetJoint(jointIndex++)->SetName(jointName); ProcessJoints(scene->mRootNode, skeleton, joints); return false; } else { mesh->CreateStatic(); // aiMaterial index in scene => Material index and data in Mesh std::unordered_map<unsigned int, std::pair<unsigned int, ParameterList>> materials; for (unsigned int i = 0; i < scene->mNumMeshes; ++i) { aiMesh* iMesh = scene->mMeshes[i]; if (!iMesh->HasBones()) // Don't process skeletal meshs { unsigned int indexCount = iMesh->mNumFaces * 3; unsigned int vertexCount = iMesh->mNumVertices; // Index buffer bool largeIndices = (vertexCount > std::numeric_limits<UInt16>::max()); IndexBufferRef indexBuffer = IndexBuffer::New(largeIndices, indexCount, parameters.storage); IndexMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite); IndexIterator index = indexMapper.begin(); for (unsigned int j = 0; j < iMesh->mNumFaces; ++j) { aiFace& face = iMesh->mFaces[j]; if (face.mNumIndices != 3) NazaraWarning("Assimp plugin: This face is not a triangle!"); *index++ = face.mIndices[0]; *index++ = face.mIndices[1]; *index++ = face.mIndices[2]; } indexMapper.Unmap(); // Vertex buffer VertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent), vertexCount, parameters.storage); BufferMapper<VertexBuffer> vertexMapper(vertexBuffer, BufferAccess_WriteOnly); MeshVertex* vertex = static_cast<MeshVertex*>(vertexMapper.GetPointer()); for (unsigned int j = 0; j < vertexCount; ++j) { aiVector3D position = iMesh->mVertices[j]; aiVector3D normal = iMesh->mNormals[j]; aiVector3D tangent = iMesh->mTangents[j]; aiVector3D uv = iMesh->mTextureCoords[0][j]; vertex->position = parameters.scale * Vector3f(position.x, position.y, position.z); vertex->normal.Set(normal.x, normal.y, normal.z); vertex->tangent.Set(tangent.x, tangent.y, tangent.z); vertex->uv.Set(uv.x, uv.y); vertex++; } vertexMapper.Unmap(); // Submesh StaticMeshRef subMesh = StaticMesh::New(mesh); subMesh->Create(vertexBuffer); subMesh->SetIndexBuffer(indexBuffer); subMesh->GenerateAABB(); subMesh->SetMaterialIndex(iMesh->mMaterialIndex); auto matIt = materials.find(iMesh->mMaterialIndex); if (matIt == materials.end()) { ParameterList matData; aiMaterial* aiMat = scene->mMaterials[iMesh->mMaterialIndex]; auto ConvertColor = [&] (const char* aiKey, unsigned int aiType, unsigned int aiIndex, const char* colorKey) { aiColor4D color; if (aiGetMaterialColor(aiMat, aiKey, aiType, aiIndex, &color) == aiReturn_SUCCESS) { matData.SetParameter(MaterialData::CustomDefined); matData.SetParameter(colorKey, Color(static_cast<UInt8>(color.r * 255), static_cast<UInt8>(color.g * 255), static_cast<UInt8>(color.b * 255), static_cast<UInt8>(color.a * 255))); } }; auto ConvertTexture = [&] (aiTextureType aiType, const char* textureKey, const char* wrapKey = nullptr) { aiString path; aiTextureMapMode mapMode; if (aiGetMaterialTexture(aiMat, aiType, 0, &path, nullptr, nullptr, nullptr, nullptr, &mapMode, nullptr) == aiReturn_SUCCESS) { matData.SetParameter(MaterialData::CustomDefined); matData.SetParameter(textureKey, stream.GetDirectory() + String(path.data, path.length)); if (wrapKey) { SamplerWrap wrap = SamplerWrap_Default; switch (mapMode) { case aiTextureMapMode_Clamp: case aiTextureMapMode_Decal: wrap = SamplerWrap_Clamp; break; case aiTextureMapMode_Mirror: wrap = SamplerWrap_MirroredRepeat; break; case aiTextureMapMode_Wrap: wrap = SamplerWrap_Repeat; break; default: NazaraWarning("Assimp texture map mode 0x" + String::Number(mapMode, 16) + " not handled"); break; } matData.SetParameter(wrapKey, static_cast<int>(wrap)); } } }; ConvertColor(AI_MATKEY_COLOR_AMBIENT, MaterialData::AmbientColor); ConvertColor(AI_MATKEY_COLOR_DIFFUSE, MaterialData::DiffuseColor); ConvertColor(AI_MATKEY_COLOR_SPECULAR, MaterialData::SpecularColor); ConvertTexture(aiTextureType_DIFFUSE, MaterialData::DiffuseTexturePath, MaterialData::DiffuseWrap); ConvertTexture(aiTextureType_EMISSIVE, MaterialData::EmissiveTexturePath); ConvertTexture(aiTextureType_HEIGHT, MaterialData::HeightTexturePath); ConvertTexture(aiTextureType_NORMALS, MaterialData::NormalTexturePath); ConvertTexture(aiTextureType_OPACITY, MaterialData::AlphaTexturePath); ConvertTexture(aiTextureType_SPECULAR, MaterialData::SpecularTexturePath, MaterialData::SpecularWrap); int iValue; if (aiGetMaterialInteger(aiMat, AI_MATKEY_TWOSIDED, &iValue)) matData.SetParameter(MaterialData::FaceCulling, !iValue); matIt = materials.insert(std::make_pair(iMesh->mMaterialIndex, std::make_pair(materials.size(), std::move(matData)))).first; } subMesh->SetMaterialIndex(matIt->first); mesh->AddSubMesh(subMesh); } mesh->SetMaterialCount(std::max<unsigned int>(materials.size(), 1)); for (const auto& pair : materials) mesh->SetMaterialData(pair.second.first, pair.second.second); } if (parameters.center) mesh->Recenter(); } aiReleaseImport(scene); return true; } extern "C" { NAZARA_EXPORT int PluginLoad() { Nz::MeshLoader::RegisterLoader(IsSupported, Check, Load); return 1; } NAZARA_EXPORT void PluginUnload() { Nz::MeshLoader::UnregisterLoader(IsSupported, Check, Load); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef UNIQUE_PTR_H #define UNIQUE_PTR_H #include <tuple.hpp> #include <algorithms.hpp> namespace std { template<typename T> struct default_delete { constexpr default_delete() = default; constexpr default_delete(const default_delete&) {} void operator()(T* ptr) const { static_assert(sizeof(T) > 0, "Type must be complete"); delete ptr; } }; //Partial specialization for arrays template<typename T> struct default_delete<T[]> { constexpr default_delete() = default; constexpr default_delete(const default_delete&) {} void operator()(T* ptr) const { static_assert(sizeof(T) > 0, "Type must be complete"); delete[] ptr; } }; template <typename T, typename D = default_delete<T>> class unique_ptr { public: typedef T* pointer_type; typedef T element_type; typedef D deleter_type; private: typedef tuple<pointer_type, deleter_type> data_impl; data_impl _data; public: unique_ptr() : _data() {} unique_ptr(decltype(nullptr)) : unique_ptr() {} explicit unique_ptr(pointer_type p) : _data(make_tuple(p, deleter_type())) {} unique_ptr(unique_ptr&& u) : _data(make_tuple(u.release(), u.get_deleter())) {} unique_ptr& operator=(unique_ptr&& u){ reset(u.release()); get_deleter() = std::forward<deleter_type>(u.get_deleter()); return *this; } ~unique_ptr(){ reset(); } // Disable copy unique_ptr(const unique_ptr& rhs) = delete; unique_ptr& operator=(const unique_ptr& rhs) = delete; unique_ptr& operator=(decltype(nullptr)){ reset(); return *this; } //Access element_type& operator*() const { return *get(); } pointer_type operator->() const { return get(); } pointer_type get() const { return std::get<0>(_data); } deleter_type& get_deleter(){ return std::get<1>(_data); } const deleter_type& get_deleter() const { return std::get<1>(_data); } explicit operator bool() const { return get() == pointer_type() ? false : true; } pointer_type release(){ pointer_type p = get(); std::get<0>(_data) = pointer_type(); return p; } void reset(pointer_type p = pointer_type()){ if(get() != pointer_type()){ get_deleter()(get()); } std::get<0>(_data) = p; } }; //Partial specialization for array template <typename T, typename D> class unique_ptr<T[], D> { public: typedef T* pointer_type; typedef T element_type; typedef D deleter_type; private: typedef tuple<pointer_type, deleter_type> data_impl; data_impl _data; public: unique_ptr() : _data() {} unique_ptr(decltype(nullptr)) : unique_ptr() {} explicit unique_ptr(pointer_type p) : _data(make_tuple(p, deleter_type())) {} unique_ptr(unique_ptr&& u) : _data(make_tuple(u.release(), u.get_deleter())) {} unique_ptr& operator=(unique_ptr&& u){ reset(u.release()); get_deleter() = std::forward<deleter_type>(u.get_deleter()); return *this; } ~unique_ptr(){ reset(); } // Disable copy unique_ptr(const unique_ptr& rhs) = delete; unique_ptr& operator=(const unique_ptr& rhs) = delete; unique_ptr& operator=(decltype(nullptr)){ reset(); return *this; } pointer_type get() const { return std::get<0>(_data); } deleter_type& get_deleter(){ return std::get<1>(_data); } const deleter_type& get_deleter() const { return std::get<1>(_data); } element_type& operator[](size_t i) const { return get()[i]; } explicit operator bool() const { return get() == pointer_type() ? false : true; } pointer_type release(){ pointer_type p = get(); std::get<0>(_data) = pointer_type(); return p; } void reset(){ reset(pointer_type()); } void reset(pointer_type p){ if(get() != pointer_type()){ get_deleter()(get()); } std::get<0>(_data) = p; } }; static_assert(sizeof(unique_ptr<long>) == sizeof(long), "unique_ptr must have zero overhead with default deleter"); static_assert(sizeof(unique_ptr<long[]>) == sizeof(long), "unique_ptr must have zero overhead with default deleter"); } //end of namespace std #endif <commit_msg>Cleanup<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef UNIQUE_PTR_H #define UNIQUE_PTR_H #include <tuple.hpp> #include <algorithms.hpp> namespace std { template<typename T> struct default_delete { constexpr default_delete() = default; constexpr default_delete(const default_delete&) {} void operator()(T* ptr) const { static_assert(sizeof(T) > 0, "Type must be complete"); delete ptr; } }; //Partial specialization for arrays template<typename T> struct default_delete<T[]> { constexpr default_delete() = default; constexpr default_delete(const default_delete&) {} void operator()(T* ptr) const { static_assert(sizeof(T) > 0, "Type must be complete"); delete[] ptr; } }; template <typename T, typename D = default_delete<T>> class unique_ptr { public: typedef T* pointer_type; typedef T element_type; typedef D deleter_type; private: typedef tuple<pointer_type, deleter_type> data_impl; data_impl _data; public: unique_ptr() : _data() {} unique_ptr(decltype(nullptr)) : unique_ptr() {} explicit unique_ptr(pointer_type p) : _data(make_tuple(p, deleter_type())) {} unique_ptr(unique_ptr&& u) : _data(make_tuple(u.release(), u.get_deleter())) {} unique_ptr& operator=(unique_ptr&& u){ reset(u.release()); get_deleter() = std::forward<deleter_type>(u.get_deleter()); return *this; } ~unique_ptr(){ reset(); } // Disable copy unique_ptr(const unique_ptr& rhs) = delete; unique_ptr& operator=(const unique_ptr& rhs) = delete; unique_ptr& operator=(decltype(nullptr)){ reset(); return *this; } //Access element_type& operator*() const { return *get(); } pointer_type operator->() const { return get(); } pointer_type get() const { return std::get<0>(_data); } deleter_type& get_deleter(){ return std::get<1>(_data); } const deleter_type& get_deleter() const { return std::get<1>(_data); } explicit operator bool() const { return get() == pointer_type() ? false : true; } pointer_type release(){ pointer_type p = get(); std::get<0>(_data) = pointer_type(); return p; } void reset(pointer_type p = pointer_type()){ if(get() != pointer_type()){ get_deleter()(get()); } std::get<0>(_data) = p; } }; //Partial specialization for array template <typename T, typename D> class unique_ptr<T[], D> { public: typedef T* pointer_type; typedef T element_type; typedef D deleter_type; private: typedef tuple<pointer_type, deleter_type> data_impl; data_impl _data; public: unique_ptr() : _data() {} unique_ptr(decltype(nullptr)) : unique_ptr() {} explicit unique_ptr(pointer_type p) : _data(make_tuple(p, deleter_type())) {} unique_ptr(unique_ptr&& u) : _data(make_tuple(u.release(), u.get_deleter())) {} unique_ptr& operator=(unique_ptr&& u){ reset(u.release()); get_deleter() = std::forward<deleter_type>(u.get_deleter()); return *this; } ~unique_ptr(){ reset(); } // Disable copy unique_ptr(const unique_ptr& rhs) = delete; unique_ptr& operator=(const unique_ptr& rhs) = delete; unique_ptr& operator=(decltype(nullptr)){ reset(); return *this; } pointer_type get() const { return std::get<0>(_data); } deleter_type& get_deleter(){ return std::get<1>(_data); } const deleter_type& get_deleter() const { return std::get<1>(_data); } element_type& operator[](size_t i) const { return get()[i]; } explicit operator bool() const { return get() == pointer_type() ? false : true; } pointer_type release(){ pointer_type p = get(); std::get<0>(_data) = pointer_type(); return p; } void reset(){ reset(pointer_type()); } void reset(pointer_type p){ auto tmp = get(); std::get<0>(_data) = p; if(tmp){ get_deleter()(tmp); } } }; static_assert(sizeof(unique_ptr<long>) == sizeof(long), "unique_ptr must have zero overhead with default deleter"); static_assert(sizeof(unique_ptr<long[]>) == sizeof(long), "unique_ptr must have zero overhead with default deleter"); } //end of namespace std #endif <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // selectivity.cpp // // Identification: src/optimizer/stats/selectivity.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/stats/selectivity.h" #include "catalog/table_catalog.h" #include "concurrency/transaction_manager_factory.h" #include "function/string_functions.h" namespace peloton { namespace optimizer { double Selectivity::ComputeSelectivity(const std::shared_ptr<TableStats> &stats, const ValueCondition &condition) { switch (condition.type) { case ExpressionType::COMPARE_LESSTHAN: return LessThan(stats, condition); case ExpressionType::COMPARE_GREATERTHAN: return GreaterThan(stats, condition); case ExpressionType::COMPARE_LESSTHANOREQUALTO: return LessThanOrEqualTo(stats, condition); case ExpressionType::COMPARE_GREATERTHANOREQUALTO: return GreaterThanOrEqualTo(stats, condition); case ExpressionType::COMPARE_EQUAL: return Equal(stats, condition); case ExpressionType::COMPARE_NOTEQUAL: return NotEqual(stats, condition); case ExpressionType::COMPARE_LIKE: return Like(stats, condition); case ExpressionType::COMPARE_NOTLIKE: return NotLike(stats, condition); case ExpressionType::COMPARE_IN: return In(stats, condition); case ExpressionType::COMPARE_DISTINCT_FROM: return DistinctFrom(stats, condition); default: LOG_WARN("Expression type %s not supported for computing selectivity", ExpressionTypeToString(condition.type).c_str()); return DEFAULT_SELECTIVITY; } } double Selectivity::LessThan(const std::shared_ptr<TableStats> &table_stats, const ValueCondition &condition) { // Convert peloton value type to raw value (double) double v = StatsUtil::PelotonValueToNumericValue(condition.value); if (std::isnan(v)) { LOG_TRACE("Error computing less than for non-numeric type"); return DEFAULT_SELECTIVITY; } // TODO: make sure condition uses column id. check if column name is not // empty. std::shared_ptr<ColumnStats> column_stats = table_stats->GetColumnStats(condition.column_name); // Return default selectivity if no column stats for given column_id if (column_stats == nullptr) { return DEFAULT_SELECTIVITY; } // Use histogram to estimate selectivity std::vector<double> histogram = column_stats->histogram_bounds; size_t n = histogram.size(); PL_ASSERT(n > 0); // find correspond bin using binary search auto it = std::lower_bound(histogram.begin(), histogram.end(), v); double res = (it - histogram.begin()) * 1.0 / n; PL_ASSERT(res >= 0); PL_ASSERT(res <= 1); return res; } double Selectivity::Equal(const std::shared_ptr<TableStats> &table_stats, const ValueCondition &condition) { double value = StatsUtil::PelotonValueToNumericValue(condition.value); auto column_stats = table_stats->GetColumnStats(condition.column_name); // LOG_INFO("column name %s", condition.column_name); if (std::isnan(value) || column_stats == nullptr) { LOG_DEBUG("Calculate selectivity: return null"); return DEFAULT_SELECTIVITY; } size_t numrows = column_stats->num_rows; // For now only double is supported in stats storage std::vector<double> most_common_vals = column_stats->most_common_vals; std::vector<double> most_common_freqs = column_stats->most_common_freqs; std::vector<double>::iterator first = most_common_vals.begin(), last = most_common_vals.end(); while (first != last) { // For now only double is supported in stats storage if (*first == value) { break; } ++first; } double res = DEFAULT_SELECTIVITY; if (first != last) { // the target value for equality comparison (param value) is // found in most common values size_t idx = first - most_common_vals.begin(); res = most_common_freqs[idx] / (double)numrows; } else { // the target value for equality comparison (parm value) is // NOT found in most common values // (1 - sum(mvf))/(num_distinct - num_mcv) double sum_mvf = 0; std::vector<double>::iterator first = most_common_freqs.begin(), last = most_common_freqs.end(); while (first != last) { sum_mvf += *first; ++first; } if (numrows == 0 || column_stats->cardinality == most_common_vals.size()) { LOG_TRACE("Equal selectivity division by 0."); return DEFAULT_SELECTIVITY; } res = (1 - sum_mvf / (double)numrows) / (column_stats->cardinality - most_common_vals.size()); } PL_ASSERT(res >= 0); PL_ASSERT(res <= 1); return res; } // Selectivity for 'LIKE' operator. The column type must be VARCHAR. // Complete implementation once we support LIKE operator. double Selectivity::Like(const std::shared_ptr<TableStats> &table_stats, const ValueCondition &condition) { // Check whether column type is VARCHAR. if ((condition.value).GetTypeId() != type::TypeId::VARCHAR) { return DEFAULT_SELECTIVITY; } const char *pattern = (condition.value).GetData(); auto column_stats = table_stats->GetColumnStats(condition.column_name); if (column_stats == nullptr) { return DEFAULT_SELECTIVITY; } oid_t column_id = column_stats->column_id; size_t matched_count = 0; size_t total_count = 0; // Sample on the fly auto sampler = table_stats->GetSampler(); PL_ASSERT(sampler != nullptr); if (sampler->GetSampledTuples().empty()) { sampler->AcquireSampleTuples(DEFAULT_SAMPLE_SIZE); } auto &sample_tuples = sampler->GetSampledTuples(); for (size_t i = 0; i < sample_tuples.size(); i++) { auto value = sample_tuples[i]->GetValue(column_id); PL_ASSERT(value.GetTypeId() == type::TypeId::VARCHAR); if (function::StringFunctions::Like(value.GetData(), value.GetLength(), pattern, condition.value.GetLength())) { matched_count++; } } total_count = sample_tuples.size(); LOG_TRACE("total sample size %lu matched tupe %lu", total_count, matched_count); return total_count == 0 ? DEFAULT_SELECTIVITY : (double)matched_count / total_count; } } // namespace optimizer } // namespace peloton <commit_msg>Fix build error++<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // selectivity.cpp // // Identification: src/optimizer/stats/selectivity.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/stats/selectivity.h" #include "catalog/table_catalog.h" #include "concurrency/transaction_manager_factory.h" #include "executor/executor_context.h" #include "function/string_functions.h" namespace peloton { namespace optimizer { double Selectivity::ComputeSelectivity(const std::shared_ptr<TableStats> &stats, const ValueCondition &condition) { switch (condition.type) { case ExpressionType::COMPARE_LESSTHAN: return LessThan(stats, condition); case ExpressionType::COMPARE_GREATERTHAN: return GreaterThan(stats, condition); case ExpressionType::COMPARE_LESSTHANOREQUALTO: return LessThanOrEqualTo(stats, condition); case ExpressionType::COMPARE_GREATERTHANOREQUALTO: return GreaterThanOrEqualTo(stats, condition); case ExpressionType::COMPARE_EQUAL: return Equal(stats, condition); case ExpressionType::COMPARE_NOTEQUAL: return NotEqual(stats, condition); case ExpressionType::COMPARE_LIKE: return Like(stats, condition); case ExpressionType::COMPARE_NOTLIKE: return NotLike(stats, condition); case ExpressionType::COMPARE_IN: return In(stats, condition); case ExpressionType::COMPARE_DISTINCT_FROM: return DistinctFrom(stats, condition); default: LOG_WARN("Expression type %s not supported for computing selectivity", ExpressionTypeToString(condition.type).c_str()); return DEFAULT_SELECTIVITY; } } double Selectivity::LessThan(const std::shared_ptr<TableStats> &table_stats, const ValueCondition &condition) { // Convert peloton value type to raw value (double) double v = StatsUtil::PelotonValueToNumericValue(condition.value); if (std::isnan(v)) { LOG_TRACE("Error computing less than for non-numeric type"); return DEFAULT_SELECTIVITY; } // TODO: make sure condition uses column id. check if column name is not // empty. std::shared_ptr<ColumnStats> column_stats = table_stats->GetColumnStats(condition.column_name); // Return default selectivity if no column stats for given column_id if (column_stats == nullptr) { return DEFAULT_SELECTIVITY; } // Use histogram to estimate selectivity std::vector<double> histogram = column_stats->histogram_bounds; size_t n = histogram.size(); PL_ASSERT(n > 0); // find correspond bin using binary search auto it = std::lower_bound(histogram.begin(), histogram.end(), v); double res = (it - histogram.begin()) * 1.0 / n; PL_ASSERT(res >= 0); PL_ASSERT(res <= 1); return res; } double Selectivity::Equal(const std::shared_ptr<TableStats> &table_stats, const ValueCondition &condition) { double value = StatsUtil::PelotonValueToNumericValue(condition.value); auto column_stats = table_stats->GetColumnStats(condition.column_name); // LOG_INFO("column name %s", condition.column_name); if (std::isnan(value) || column_stats == nullptr) { LOG_DEBUG("Calculate selectivity: return null"); return DEFAULT_SELECTIVITY; } size_t numrows = column_stats->num_rows; // For now only double is supported in stats storage std::vector<double> most_common_vals = column_stats->most_common_vals; std::vector<double> most_common_freqs = column_stats->most_common_freqs; std::vector<double>::iterator first = most_common_vals.begin(), last = most_common_vals.end(); while (first != last) { // For now only double is supported in stats storage if (*first == value) { break; } ++first; } double res = DEFAULT_SELECTIVITY; if (first != last) { // the target value for equality comparison (param value) is // found in most common values size_t idx = first - most_common_vals.begin(); res = most_common_freqs[idx] / (double)numrows; } else { // the target value for equality comparison (parm value) is // NOT found in most common values // (1 - sum(mvf))/(num_distinct - num_mcv) double sum_mvf = 0; std::vector<double>::iterator first = most_common_freqs.begin(), last = most_common_freqs.end(); while (first != last) { sum_mvf += *first; ++first; } if (numrows == 0 || column_stats->cardinality == most_common_vals.size()) { LOG_TRACE("Equal selectivity division by 0."); return DEFAULT_SELECTIVITY; } res = (1 - sum_mvf / (double)numrows) / (column_stats->cardinality - most_common_vals.size()); } PL_ASSERT(res >= 0); PL_ASSERT(res <= 1); return res; } // Selectivity for 'LIKE' operator. The column type must be VARCHAR. // Complete implementation once we support LIKE operator. double Selectivity::Like(const std::shared_ptr<TableStats> &table_stats, const ValueCondition &condition) { // Check whether column type is VARCHAR. if ((condition.value).GetTypeId() != type::TypeId::VARCHAR) { return DEFAULT_SELECTIVITY; } const char *pattern = (condition.value).GetData(); auto column_stats = table_stats->GetColumnStats(condition.column_name); if (column_stats == nullptr) { return DEFAULT_SELECTIVITY; } oid_t column_id = column_stats->column_id; size_t matched_count = 0; size_t total_count = 0; // Sample on the fly auto sampler = table_stats->GetSampler(); PL_ASSERT(sampler != nullptr); if (sampler->GetSampledTuples().empty()) { sampler->AcquireSampleTuples(DEFAULT_SAMPLE_SIZE); } auto &sample_tuples = sampler->GetSampledTuples(); for (size_t i = 0; i < sample_tuples.size(); i++) { auto value = sample_tuples[i]->GetValue(column_id); PL_ASSERT(value.GetTypeId() == type::TypeId::VARCHAR); executor::ExecutorContext dummy_context(nullptr); if (function::StringFunctions::Like(dummy_context, value.GetData(), value.GetLength(), pattern, condition.value.GetLength())) { matched_count++; } } total_count = sample_tuples.size(); LOG_TRACE("total sample size %lu matched tupe %lu", total_count, matched_count); return total_count == 0 ? DEFAULT_SELECTIVITY : (double)matched_count / total_count; } } // namespace optimizer } // namespace peloton <|endoftext|>