text
stringlengths
54
60.6k
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Directory.h" #include "Media.h" #include "Device.h" #include "filesystem/unix/File.h" #include <cstring> #include <cstdlib> #include <dirent.h> #include <limits.h> #include <sys/stat.h> #include <unistd.h> namespace medialibrary { namespace fs { Directory::Directory( const std::string& path, factory::IFileSystem& fsFactory ) : CommonDirectory( toAbsolute( path ), fsFactory ) { } void Directory::read() const { std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( m_path.c_str() ), closedir ); if ( dir == nullptr ) { std::string err( "Failed to open directory " ); err += m_path; err += strerror(errno); throw std::runtime_error( err ); } dirent* result = nullptr; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( strcmp( result->d_name, "." ) == 0 || strcmp( result->d_name, ".." ) == 0 ) { continue; } std::string path = m_path + "/" + result->d_name; struct stat s; if ( lstat( path.c_str(), &s ) != 0 ) { if ( errno == EACCES ) continue; // Ignore EOVERFLOW since we are not (yet?) interested in the file size if ( errno != EOVERFLOW ) { std::string err( "Failed to get file info " ); err += path + ": "; err += strerror(errno); throw std::runtime_error( err ); } } if ( S_ISDIR( s.st_mode ) ) { auto dirPath = toAbsolute( path ); if ( *dirPath.crbegin() != '/' ) dirPath += '/'; //FIXME: This will use toAbsolute again in the constructor. m_dirs.emplace_back( std::make_shared<Directory>( dirPath, m_fsFactory ) ); } else { auto filePath = toAbsolute( path ); m_files.emplace_back( std::make_shared<File>( filePath, s ) ); } } } std::string Directory::toAbsolute( const std::string& path ) { char abs[PATH_MAX]; if ( realpath( path.c_str(), abs ) == nullptr ) { std::string err( "Failed to convert to absolute path" ); err += "(" + path + "): "; err += strerror(errno); throw std::runtime_error( err ); } return std::string{ abs }; } } } <commit_msg>fs: unix: Ignore hidden folders<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<[email protected]> * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Directory.h" #include "Media.h" #include "Device.h" #include "filesystem/unix/File.h" #include <cstring> #include <cstdlib> #include <dirent.h> #include <limits.h> #include <sys/stat.h> #include <unistd.h> namespace medialibrary { namespace fs { Directory::Directory( const std::string& path, factory::IFileSystem& fsFactory ) : CommonDirectory( toAbsolute( path ), fsFactory ) { } void Directory::read() const { std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( m_path.c_str() ), closedir ); if ( dir == nullptr ) { std::string err( "Failed to open directory " ); err += m_path; err += strerror(errno); throw std::runtime_error( err ); } dirent* result = nullptr; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( result->d_name == nullptr || result->d_name[0] == '.' ) continue; std::string path = m_path + "/" + result->d_name; struct stat s; if ( lstat( path.c_str(), &s ) != 0 ) { if ( errno == EACCES ) continue; // Ignore EOVERFLOW since we are not (yet?) interested in the file size if ( errno != EOVERFLOW ) { std::string err( "Failed to get file info " ); err += path + ": "; err += strerror(errno); throw std::runtime_error( err ); } } if ( S_ISDIR( s.st_mode ) ) { auto dirPath = toAbsolute( path ); if ( *dirPath.crbegin() != '/' ) dirPath += '/'; //FIXME: This will use toAbsolute again in the constructor. m_dirs.emplace_back( std::make_shared<Directory>( dirPath, m_fsFactory ) ); } else { auto filePath = toAbsolute( path ); m_files.emplace_back( std::make_shared<File>( filePath, s ) ); } } } std::string Directory::toAbsolute( const std::string& path ) { char abs[PATH_MAX]; if ( realpath( path.c_str(), abs ) == nullptr ) { std::string err( "Failed to convert to absolute path" ); err += "(" + path + "): "; err += strerror(errno); throw std::runtime_error( err ); } return std::string{ abs }; } } } <|endoftext|>
<commit_before>#include <cstdint> #include <iostream> #include <utility> #include <algorithm.hpp> #include <case.hpp> #include <cube.hpp> #include <finder/brute-force.hpp> #include "utils.hpp" using namespace std; using namespace InsertionFinder; using namespace Details; namespace { bool not_searched( const Algorithm& algorithm, size_t insert_place, size_t new_begin, bool swapped ) { if (swapped || insert_place < 2 || algorithm.swappable(insert_place - 1)) { return new_begin >= insert_place; } else { return new_begin >= insert_place - 1; } } }; void BruteForceFinder::Worker::search( const BruteForceFinder::CycleStatus& cycle_status, size_t begin, size_t end ) { bool parity = cycle_status.parity; int corner_cycles = cycle_status.corner_cycles; int edge_cycles = cycle_status.edge_cycles; int placement = cycle_status.placement; if (parity && corner_cycles == 0 && edge_cycles == 0 && placement == 0) { this->search_last_parity(begin, end); return; } else if (!parity && corner_cycles == 1 && edge_cycles == 0 && placement == 0) { this->search_last_corner_cycle(begin, end); return; } else if (!parity && corner_cycles == 0 && edge_cycles == 1 && placement == 0) { this->search_last_edge_cycle(begin, end); return; } else if ( !parity && corner_cycles == 0 && edge_cycles == 0 && Cube::center_cycles[placement] <= 1 ) { this->search_last_placement(placement, begin, end); return; } Algorithm skeleton = this->solving_step.back().skeleton; const int* transform = rotation_permutation[placement]; byte twist_flag{0}; if (this->finder.change_corner) { twist_flag |= CubeTwist::corners; } if (this->finder.change_edge) { twist_flag |= CubeTwist::edges; } Cube state; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { state.twist(skeleton, insert_place, skeleton.length(), twist_flag); state.rotate(placement); state.twist(this->finder.scramble_cube, twist_flag); state.twist(skeleton, 0, insert_place, twist_flag); } else { int twist = skeleton[insert_place - 1]; state.twist_before( transform_twist(transform, Algorithm::inverse_twist[twist]), twist_flag ); state.twist(twist, twist_flag); } this->try_insertion(insert_place, state, cycle_status); if (skeleton.swappable(insert_place)) { Cube swapped_state; swapped_state.twist(skeleton[insert_place - 1], twist_flag); swapped_state.twist( Algorithm::inverse_twist[skeleton[insert_place]], twist_flag ); swapped_state.rotate(placement); swapped_state.twist(state, twist_flag); swapped_state.twist(skeleton[insert_place], twist_flag); swapped_state.twist( Algorithm::inverse_twist[skeleton[insert_place - 1]], twist_flag ); this->try_insertion(insert_place, swapped_state, cycle_status, true); } } } void BruteForceFinder::Worker::search_last_parity(size_t begin, size_t end) { Algorithm skeleton = this->solving_step.back().skeleton; const byte twist_flag = CubeTwist::corners | CubeTwist::edges | CubeTwist::reversed; const auto& parity_index = this->finder.parity_index; int index = -1; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { Cube state; state.twist(skeleton, 0, insert_place, twist_flag); state.twist(this->finder.inverse_scramble_cube, twist_flag); state.twist(skeleton, insert_place, skeleton.length(), twist_flag); index = state.parity_index(); } else { index = Cube::next_parity_index(index, skeleton[insert_place - 1]); } this->try_last_insertion(insert_place, parity_index[index]); if (skeleton.swappable(insert_place)) { int swapped_index = Cube::next_parity_index( Cube::next_parity_index(index, skeleton[insert_place]), Algorithm::inverse_twist[skeleton[insert_place - 1]] ); this->try_last_insertion(insert_place, parity_index[swapped_index], true); } } } void BruteForceFinder::Worker::search_last_corner_cycle(size_t begin, size_t end) { Algorithm skeleton = this->solving_step.back().skeleton; const byte twist_flag = CubeTwist::corners | CubeTwist::reversed; const auto& corner_cycle_index = this->finder.corner_cycle_index; int index = -1; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { Cube state; state.twist(skeleton, 0, insert_place, twist_flag); state.twist(this->finder.inverse_scramble_cube, twist_flag); state.twist(skeleton, insert_place, skeleton.length(), twist_flag); index = state.corner_cycle_index(); } else { index = Cube::next_corner_cycle_index(index, skeleton[insert_place - 1]); } this->try_last_insertion(insert_place, corner_cycle_index[index]); if (skeleton.swappable(insert_place)) { int swapped_index = Cube::next_corner_cycle_index( Cube::next_corner_cycle_index(index, skeleton[insert_place]), Algorithm::inverse_twist[skeleton[insert_place - 1]] ); this->try_last_insertion(insert_place, corner_cycle_index[swapped_index], true); } } } void BruteForceFinder::Worker::search_last_edge_cycle(size_t begin, size_t end) { Algorithm skeleton = this->solving_step.back().skeleton; const byte twist_flag = CubeTwist::edges | CubeTwist::reversed; const auto& edge_cycle_index = this->finder.edge_cycle_index; int index = -1; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { Cube state; state.twist(skeleton, 0, insert_place, twist_flag); state.twist(this->finder.inverse_scramble_cube, twist_flag); state.twist(skeleton, insert_place, skeleton.length(), twist_flag); index = state.edge_cycle_index(); } else { index = Cube::next_edge_cycle_index(index, skeleton[insert_place - 1]); } this->try_last_insertion(insert_place, edge_cycle_index[index]); if (skeleton.swappable(insert_place)) { int swapped_index = Cube::next_edge_cycle_index( Cube::next_edge_cycle_index(index, skeleton[insert_place]), Algorithm::inverse_twist[skeleton[insert_place - 1]] ); this->try_last_insertion(insert_place, edge_cycle_index[swapped_index], true); } } } void BruteForceFinder::Worker::search_last_placement( int placement, size_t begin, size_t end ) { Algorithm skeleton = this->solving_step.back().skeleton; int case_index = this->finder.center_index[Cube::inverse_center[placement]]; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { this->try_last_insertion(insert_place, case_index); if (skeleton.swappable(insert_place)) { this->try_last_insertion(insert_place, case_index, true); } } } void BruteForceFinder::Worker::try_insertion( size_t insert_place, const Cube& state, const CycleStatus& cycle_status, bool swapped ) { if (swapped) { this->solving_step.back().skeleton.swap_adjacent(insert_place); } this->solving_step.back().insert_place = insert_place; uint32_t mask = state.mask(); auto insert_place_mask = this->solving_step.back().skeleton .get_insert_place_mask(insert_place); bool parity = cycle_status.parity; int corner_cycles = cycle_status.corner_cycles; int edge_cycles = cycle_status.edge_cycles; int placement = cycle_status.placement; for (const Case& _case: this->finder.cases) { if (bitcount_less_than_2(mask & _case.mask())) { continue; } bool corner_changed = _case.mask() & 0xff; bool edge_changed = _case.mask() & 0xfff00; bool center_changed = _case.mask() & 0x300000; auto cube = state.twist_effectively( _case.state(), (corner_changed ? CubeTwist::corners : byte{0}) | (edge_changed ? CubeTwist::edges : byte{0}) | (center_changed ? CubeTwist::centers : byte{0}) ); if (!cube) { continue; } bool new_parity = parity ^ _case.has_parity(); int new_corner_cycles = corner_changed ? cube->corner_cycles() : corner_cycles; int new_edge_cycles = edge_changed ? cube->edge_cycles() : edge_cycles; int new_placement = Cube::placement_twist(placement, _case.rotation()); if ( !new_parity && new_corner_cycles == 0 && new_edge_cycles == 0 && new_placement == 0 ) { this->solution_found(insert_place, _case); } else if ( (Cube::center_cycles[new_placement] > 1 ? 0 : new_parity) + new_corner_cycles + new_edge_cycles + Cube::center_cycles[new_placement] < (Cube::center_cycles[placement] > 1 ? 0 : parity) + corner_cycles + edge_cycles + Cube::center_cycles[placement] ) { for (const Algorithm& algorithm: _case.algorithm_list()) { Insertion& insertion = this->solving_step.back(); insertion.insertion = &algorithm; if (!insertion.skeleton.is_worthy_insertion( algorithm, insert_place, insert_place_mask, this->finder.fewest_moves )) { continue; } auto [new_skeleton, new_begin] = insertion.skeleton.insert(algorithm, insert_place); if ( not_searched(insertion.skeleton, insert_place, new_begin, swapped) && new_skeleton.length() <= this->finder.fewest_moves ) { size_t new_end = new_skeleton.length(); this->solving_step.push_back({move(new_skeleton)}); this->search( {new_parity, new_corner_cycles, new_edge_cycles, new_placement}, new_begin, new_end ); this->solving_step.pop_back(); } } } } if (swapped) { this->solving_step.back().skeleton.swap_adjacent(insert_place); } } void BruteForceFinder::Worker::try_last_insertion( std::size_t insert_place, int case_index, bool swapped ) { if (case_index == -1) { return; } if (swapped) { this->solving_step.back().skeleton.swap_adjacent(insert_place); } this->solution_found(insert_place, this->finder.cases[case_index]); if (swapped) { this->solving_step.back().skeleton.swap_adjacent(insert_place); } } void BruteForceFinder::Worker::solution_found(size_t insert_place, const Case& _case) { this->solving_step.back().insert_place = insert_place; auto insert_place_mask = this->solving_step.back().skeleton .get_insert_place_mask(insert_place); for (const Algorithm& algorithm: _case.algorithm_list()) { Insertion& insertion = this->solving_step.back(); insertion.insertion = &algorithm; if (!insertion.skeleton.is_worthy_insertion( algorithm, insert_place, insert_place_mask, this->finder.fewest_moves )) { continue; } this->solving_step.push_back({ insertion.skeleton.insert(algorithm, insert_place).first, }); this->update_fewest_moves(); this->solving_step.pop_back(); } } void BruteForceFinder::Worker::update_fewest_moves() { BruteForceFinder& finder = this->finder; size_t twists = this->solving_step.back().skeleton.length(); if (twists > finder.fewest_moves) { return; } lock_guard<mutex> lock(finder.fewest_moves_mutex); if (twists > finder.fewest_moves) { return; } if (twists < finder.fewest_moves) { finder.solutions.clear(); finder.fewest_moves = twists; if (this->finder.verbose) { cerr << this->solving_step.back().skeleton << " (" << twists << "f)" << endl; } } finder.solutions.push_back({this->solving_step}); } <commit_msg>improve coding<commit_after>#include <cstdint> #include <iostream> #include <utility> #include <algorithm.hpp> #include <case.hpp> #include <cube.hpp> #include <finder/brute-force.hpp> #include "utils.hpp" using namespace std; using namespace InsertionFinder; using namespace Details; namespace { bool not_searched( const Algorithm& algorithm, size_t insert_place, size_t new_begin, bool swapped ) { if (swapped || insert_place < 2 || algorithm.swappable(insert_place - 1)) { return new_begin >= insert_place; } else { return new_begin >= insert_place - 1; } } }; void BruteForceFinder::Worker::search( const BruteForceFinder::CycleStatus& cycle_status, size_t begin, size_t end ) { bool parity = cycle_status.parity; int corner_cycles = cycle_status.corner_cycles; int edge_cycles = cycle_status.edge_cycles; int placement = cycle_status.placement; if (parity && corner_cycles == 0 && edge_cycles == 0 && placement == 0) { this->search_last_parity(begin, end); return; } else if (!parity && corner_cycles == 1 && edge_cycles == 0 && placement == 0) { this->search_last_corner_cycle(begin, end); return; } else if (!parity && corner_cycles == 0 && edge_cycles == 1 && placement == 0) { this->search_last_edge_cycle(begin, end); return; } else if ( !parity && corner_cycles == 0 && edge_cycles == 0 && Cube::center_cycles[placement] <= 1 ) { this->search_last_placement(placement, begin, end); return; } const Algorithm skeleton = this->solving_step.back().skeleton; const int* transform = rotation_permutation[placement]; byte twist_flag{0}; if (this->finder.change_corner) { twist_flag |= CubeTwist::corners; } if (this->finder.change_edge) { twist_flag |= CubeTwist::edges; } Cube state; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { state.twist(skeleton, insert_place, skeleton.length(), twist_flag); state.rotate(placement); state.twist(this->finder.scramble_cube, twist_flag); state.twist(skeleton, 0, insert_place, twist_flag); } else { int twist = skeleton[insert_place - 1]; state.twist_before( transform_twist(transform, Algorithm::inverse_twist[twist]), twist_flag ); state.twist(twist, twist_flag); } this->try_insertion(insert_place, state, cycle_status); if (skeleton.swappable(insert_place)) { Cube swapped_state; swapped_state.twist(skeleton[insert_place - 1], twist_flag); swapped_state.twist( Algorithm::inverse_twist[skeleton[insert_place]], twist_flag ); swapped_state.rotate(placement); swapped_state.twist(state, twist_flag); swapped_state.twist(skeleton[insert_place], twist_flag); swapped_state.twist( Algorithm::inverse_twist[skeleton[insert_place - 1]], twist_flag ); this->try_insertion(insert_place, swapped_state, cycle_status, true); } } } void BruteForceFinder::Worker::search_last_parity(size_t begin, size_t end) { const Algorithm skeleton = this->solving_step.back().skeleton; const byte twist_flag = CubeTwist::corners | CubeTwist::edges | CubeTwist::reversed; const auto& parity_index = this->finder.parity_index; int index = -1; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { Cube state; state.twist(skeleton, 0, insert_place, twist_flag); state.twist(this->finder.inverse_scramble_cube, twist_flag); state.twist(skeleton, insert_place, skeleton.length(), twist_flag); index = state.parity_index(); } else { index = Cube::next_parity_index(index, skeleton[insert_place - 1]); } this->try_last_insertion(insert_place, parity_index[index]); if (skeleton.swappable(insert_place)) { int swapped_index = Cube::next_parity_index( Cube::next_parity_index(index, skeleton[insert_place]), Algorithm::inverse_twist[skeleton[insert_place - 1]] ); this->try_last_insertion(insert_place, parity_index[swapped_index], true); } } } void BruteForceFinder::Worker::search_last_corner_cycle(size_t begin, size_t end) { const Algorithm skeleton = this->solving_step.back().skeleton; const byte twist_flag = CubeTwist::corners | CubeTwist::reversed; const auto& corner_cycle_index = this->finder.corner_cycle_index; int index = -1; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { Cube state; state.twist(skeleton, 0, insert_place, twist_flag); state.twist(this->finder.inverse_scramble_cube, twist_flag); state.twist(skeleton, insert_place, skeleton.length(), twist_flag); index = state.corner_cycle_index(); } else { index = Cube::next_corner_cycle_index(index, skeleton[insert_place - 1]); } this->try_last_insertion(insert_place, corner_cycle_index[index]); if (skeleton.swappable(insert_place)) { int swapped_index = Cube::next_corner_cycle_index( Cube::next_corner_cycle_index(index, skeleton[insert_place]), Algorithm::inverse_twist[skeleton[insert_place - 1]] ); this->try_last_insertion(insert_place, corner_cycle_index[swapped_index], true); } } } void BruteForceFinder::Worker::search_last_edge_cycle(size_t begin, size_t end) { const Algorithm skeleton = this->solving_step.back().skeleton; const byte twist_flag = CubeTwist::edges | CubeTwist::reversed; const auto& edge_cycle_index = this->finder.edge_cycle_index; int index = -1; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { if (insert_place == begin) { Cube state; state.twist(skeleton, 0, insert_place, twist_flag); state.twist(this->finder.inverse_scramble_cube, twist_flag); state.twist(skeleton, insert_place, skeleton.length(), twist_flag); index = state.edge_cycle_index(); } else { index = Cube::next_edge_cycle_index(index, skeleton[insert_place - 1]); } this->try_last_insertion(insert_place, edge_cycle_index[index]); if (skeleton.swappable(insert_place)) { int swapped_index = Cube::next_edge_cycle_index( Cube::next_edge_cycle_index(index, skeleton[insert_place]), Algorithm::inverse_twist[skeleton[insert_place - 1]] ); this->try_last_insertion(insert_place, edge_cycle_index[swapped_index], true); } } } void BruteForceFinder::Worker::search_last_placement( int placement, size_t begin, size_t end ) { const Algorithm skeleton = this->solving_step.back().skeleton; int case_index = this->finder.center_index[Cube::inverse_center[placement]]; for (size_t insert_place = begin; insert_place <= end; ++insert_place) { this->try_last_insertion(insert_place, case_index); if (skeleton.swappable(insert_place)) { this->try_last_insertion(insert_place, case_index, true); } } } void BruteForceFinder::Worker::try_insertion( size_t insert_place, const Cube& state, const CycleStatus& cycle_status, bool swapped ) { Insertion& insertion = this->solving_step.back(); if (swapped) { insertion.skeleton.swap_adjacent(insert_place); } insertion.insert_place = insert_place; uint32_t mask = state.mask(); auto insert_place_mask = insertion.skeleton.get_insert_place_mask(insert_place); bool parity = cycle_status.parity; int corner_cycles = cycle_status.corner_cycles; int edge_cycles = cycle_status.edge_cycles; int placement = cycle_status.placement; for (const Case& _case: this->finder.cases) { if (bitcount_less_than_2(mask & _case.mask())) { continue; } bool corner_changed = _case.mask() & 0xff; bool edge_changed = _case.mask() & 0xfff00; bool center_changed = _case.mask() & 0x300000; auto cube = state.twist_effectively( _case.state(), (corner_changed ? CubeTwist::corners : byte{0}) | (edge_changed ? CubeTwist::edges : byte{0}) | (center_changed ? CubeTwist::centers : byte{0}) ); if (!cube) { continue; } bool new_parity = parity ^ _case.has_parity(); int new_corner_cycles = corner_changed ? cube->corner_cycles() : corner_cycles; int new_edge_cycles = edge_changed ? cube->edge_cycles() : edge_cycles; int new_placement = Cube::placement_twist(placement, _case.rotation()); if ( !new_parity && new_corner_cycles == 0 && new_edge_cycles == 0 && new_placement == 0 ) { this->solution_found(insert_place, _case); } else if ( (Cube::center_cycles[new_placement] > 1 ? 0 : new_parity) + new_corner_cycles + new_edge_cycles + Cube::center_cycles[new_placement] < (Cube::center_cycles[placement] > 1 ? 0 : parity) + corner_cycles + edge_cycles + Cube::center_cycles[placement] ) { for (const Algorithm& algorithm: _case.algorithm_list()) { Insertion& insertion = this->solving_step.back(); insertion.insertion = &algorithm; if (!insertion.skeleton.is_worthy_insertion( algorithm, insert_place, insert_place_mask, this->finder.fewest_moves )) { continue; } auto [new_skeleton, new_begin] = insertion.skeleton.insert(algorithm, insert_place); if ( not_searched(insertion.skeleton, insert_place, new_begin, swapped) && new_skeleton.length() <= this->finder.fewest_moves ) { size_t new_end = new_skeleton.length(); this->solving_step.push_back({move(new_skeleton)}); this->search( {new_parity, new_corner_cycles, new_edge_cycles, new_placement}, new_begin, new_end ); this->solving_step.pop_back(); } } } } if (swapped) { this->solving_step.back().skeleton.swap_adjacent(insert_place); } } void BruteForceFinder::Worker::try_last_insertion( std::size_t insert_place, int case_index, bool swapped ) { if (case_index == -1) { return; } if (swapped) { this->solving_step.back().skeleton.swap_adjacent(insert_place); } this->solution_found(insert_place, this->finder.cases[case_index]); if (swapped) { this->solving_step.back().skeleton.swap_adjacent(insert_place); } } void BruteForceFinder::Worker::solution_found(size_t insert_place, const Case& _case) { Insertion& insertion = this->solving_step.back(); insertion.insert_place = insert_place; auto insert_place_mask = insertion.skeleton.get_insert_place_mask(insert_place); for (const Algorithm& algorithm: _case.algorithm_list()) { Insertion& insertion = this->solving_step.back(); insertion.insertion = &algorithm; if (!insertion.skeleton.is_worthy_insertion( algorithm, insert_place, insert_place_mask, this->finder.fewest_moves )) { continue; } this->solving_step.push_back({ insertion.skeleton.insert(algorithm, insert_place).first, }); this->update_fewest_moves(); this->solving_step.pop_back(); } } void BruteForceFinder::Worker::update_fewest_moves() { BruteForceFinder& finder = this->finder; size_t twists = this->solving_step.back().skeleton.length(); if (twists > finder.fewest_moves) { return; } lock_guard<mutex> lock(finder.fewest_moves_mutex); if (twists > finder.fewest_moves) { return; } if (twists < finder.fewest_moves) { finder.solutions.clear(); finder.fewest_moves = twists; if (this->finder.verbose) { cerr << this->solving_step.back().skeleton << " (" << twists << "f)" << endl; } } finder.solutions.push_back({this->solving_step}); } <|endoftext|>
<commit_before>#include "generator/LLBkg_Generator.h" // from ROOT #include "TRandom.h" // from project - generator #include "generator/CompGeneratorFactory.h" #include "generator/generator.h" #include "generator/Observables.h" // from project - configuration #include "configuration/CompConfig.h" namespace cptoymc { namespace generator { LLBkg_Generator::LLBkg_Generator() : CompGenerator(), params_mass_{0.}, params_timeandcp_{1.,0.}, params_timeresol_{0.033,0.72,0.,1.0}, params_taggingeffs_{0.30,0.06,0.04}, params_taggingOS_{0.5,0.,0.0,-1.0}, params_taggingSS_{0.5,0.,0.0,-1.0}, comp_cat_(-1001) { std::cout << params_taggingOS_.eta_dist_mean << " - " << params_taggingOS_.eta_dist_sigma << std::endl; std::cout << params_taggingSS_.eta_dist_mean << " - " << params_taggingSS_.eta_dist_sigma << std::endl; } LLBkg_Generator::~LLBkg_Generator() { } void LLBkg_Generator::Configure(const configuration::CompConfig& comp_config) { auto config_ptree = comp_config.model_ptree(); comp_cat_ = comp_config.comp_cat(); // Mass auto sub_config_ptree = config_ptree.get_child("Mass"); params_mass_.expo = sub_config_ptree.get("expo", params_mass_.expo); // TimeAndCP sub_config_ptree = config_ptree.get_child("TimeAndCP"); params_timeandcp_.tau = sub_config_ptree.get("tau", params_timeandcp_.tau); params_timeandcp_.prod_asym = sub_config_ptree.get("AP" , params_timeandcp_.prod_asym); sub_config_ptree = config_ptree.get_child("TimeResol"); params_timeresol_.lognormal_m = sub_config_ptree.get("lognormal_m", params_timeresol_.lognormal_m); params_timeresol_.lognormal_k = sub_config_ptree.get("lognormal_k", params_timeresol_.lognormal_k); params_timeresol_.bias = sub_config_ptree.get("bias" , params_timeresol_.bias ); params_timeresol_.scale = sub_config_ptree.get("scale" , params_timeresol_.scale ); // Tagging sub_config_ptree = config_ptree.get_child("Tagging"); params_taggingeffs_.eff_OS = sub_config_ptree.get("eff_OS" ,params_taggingeffs_.eff_OS ); params_taggingeffs_.eff_SS = sub_config_ptree.get("eff_SS" ,params_taggingeffs_.eff_SS ); params_taggingeffs_.eff_SSOS = sub_config_ptree.get("eff_SSOS" ,params_taggingeffs_.eff_SSOS ); params_taggingOS_.omega = sub_config_ptree.get("omega_OS" , params_taggingOS_.omega ); params_taggingOS_.domega = sub_config_ptree.get("domega_OS" , params_taggingOS_.domega ); params_taggingOS_.eta_dist_mean = sub_config_ptree.get("eta_dist_mean_OS" , params_taggingOS_.eta_dist_mean ); params_taggingOS_.eta_dist_sigma = sub_config_ptree.get("eta_dist_sigma_OS", params_taggingOS_.eta_dist_sigma); params_taggingSS_.omega = sub_config_ptree.get("omega_SS" , params_taggingSS_.omega ); params_taggingSS_.domega = sub_config_ptree.get("domega_SS" , params_taggingSS_.domega ); params_taggingSS_.eta_dist_mean = sub_config_ptree.get("eta_dist_mean_SS" , params_taggingSS_.eta_dist_mean ); params_taggingSS_.eta_dist_sigma = sub_config_ptree.get("eta_dist_sigma_SS", params_taggingSS_.eta_dist_sigma); std::cout << params_taggingOS_.eta_dist_mean << " - " << params_taggingOS_.eta_dist_sigma << std::endl; std::cout << params_taggingSS_.eta_dist_mean << " - " << params_taggingSS_.eta_dist_sigma << std::endl; } bool LLBkg_Generator::TryGenerateEvent(TRandom& rndm, Observables& observables) { bool gen_success = true; observables.comp_cat.set_value(comp_cat_); gen_success &= GenerateMass(rndm, observables.mass_true, observables.mass_meas); gen_success &= GenerateTimeAndTrueTag(rndm, observables.time_true, observables.timeerror, observables.tag_true, observables.time_meas); gen_success &= GenerateTagAndEta(rndm, observables.tag_true, observables.tag_OS, observables.eta_OS, observables.tag_SS, observables.eta_SS, observables.tag_class); return gen_success; } bool LLBkg_Generator::GenerateMass(TRandom& rndm, ObservableReal& obs_mass_true, ObservableReal& obs_mass_meas) { bool gen_success = true; obs_mass_true.value_ = -1000.; gen_success &= GenerateExpo(rndm,-1.*params_mass_.expo,obs_mass_meas.value_, obs_mass_meas.min_value(),obs_mass_meas.max_value()); return gen_success; } bool LLBkg_Generator::GenerateTimeAndTrueTag(TRandom& rndm, ObservableReal& obs_time_true, ObservableReal& obs_timeerror, ObservableInt& obs_tag_true, ObservableReal& obs_time_meas) { unsigned int trials = 0; bool gen_success = true; while (trials < max_trials_) { gen_success = true; // true "tag" according to prodasym obs_tag_true.value_ = (rndm.Uniform() < (1. - params_timeandcp_.prod_asym)/2.) ? +1 : -1; // decay time gen_success &= GenerateExpo(rndm,1./params_timeandcp_.tau,obs_time_true.value_,obs_time_true.min_value(),obs_time_true.max_value()); gen_success &= GenerateLognormal(rndm, params_timeresol_.lognormal_m, params_timeresol_.lognormal_k, obs_timeerror.min_value(), obs_timeerror.max_value(), obs_timeerror.value_); gen_success &= GenerateResolSingleGaussPerEvent(rndm, params_timeresol_.bias, params_timeresol_.scale, obs_timeerror.value_, obs_time_true.value(), obs_time_meas.value_); if (gen_success && obs_time_true.HasValidValue() && obs_time_meas.HasValidValue() && obs_tag_true.HasValidValue()) { break; } else { ++trials; } } if (!gen_success && trials >= max_trials_) { std::cout << "Problem in LLBkg generation for component " << comp_cat_ << ": Maximum trials reached without generating valid values for " << obs_tag_true.dim_name() << "," << obs_time_true.dim_name() << " and " << obs_time_meas.dim_name() << " !!!" << std::endl; } return gen_success; } bool LLBkg_Generator::GenerateTagAndEta(TRandom& rndm, const ObservableInt& obs_tag_true, ObservableInt& obs_tag_OS, ObservableReal& obs_eta_OS, ObservableInt& obs_tag_SS, ObservableReal& obs_eta_SS, ObservableInt& obs_tag_class) { bool gen_success = true; double random_val = rndm.Uniform(); if (random_val < params_taggingeffs_.eff_OS) { // generate OS tags and mistags // gen_success &= GenerateEtaFlat(rndm, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingOS_.eta_dist_mean, params_taggingOS_.eta_dist_sigma, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateTag(rndm, params_taggingOS_.omega, params_taggingOS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_OS.GetValueForType("B") , obs_tag_OS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_OS.value_); obs_tag_SS.value_ = obs_tag_SS.GetValueForType("None"); obs_eta_SS.value_ = 0.5; obs_tag_class.value_ = obs_tag_class.GetValueForType("OSonly"); } else if (random_val < (params_taggingeffs_.eff_OS + params_taggingeffs_.eff_SS)) { // generate SS tags and mistags // gen_success &= GenerateEtaFlat(rndm, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingSS_.eta_dist_mean, params_taggingSS_.eta_dist_sigma, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateTag(rndm, params_taggingSS_.omega, params_taggingSS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_SS.GetValueForType("B") , obs_tag_SS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_SS.value_); obs_tag_OS.value_ = obs_tag_OS.GetValueForType("None"); obs_eta_OS.value_ = 0.5; obs_tag_class.value_ = obs_tag_class.GetValueForType("SSonly"); } else if (random_val < ( params_taggingeffs_.eff_OS + params_taggingeffs_.eff_SS + params_taggingeffs_.eff_SSOS) ) { // generate overlap tags and mistags // gen_success &= GenerateEtaFlat(rndm, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingOS_.eta_dist_mean, params_taggingOS_.eta_dist_sigma, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateTag(rndm, params_taggingOS_.omega, params_taggingOS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_OS.GetValueForType("B") , obs_tag_OS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_OS.value_); // gen_success &= GenerateEtaFlat(rndm, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingSS_.eta_dist_mean, params_taggingSS_.eta_dist_sigma, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateTag(rndm, params_taggingSS_.omega, params_taggingSS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_SS.GetValueForType("B") , obs_tag_SS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_SS.value_); obs_tag_class.value_ = obs_tag_class.GetValueForType("OSandSS"); } else { // untagged obs_tag_SS.value_ = obs_tag_SS.GetValueForType("None"); obs_eta_SS.value_ = 0.5; obs_tag_OS.value_ = obs_tag_OS.GetValueForType("None"); obs_eta_OS.value_ = 0.5; obs_tag_class.value_ = obs_tag_class.GetValueForType("untagged"); } return gen_success; } } // namespace generator } // namespace cptoymc <commit_msg>Removing debug output<commit_after>#include "generator/LLBkg_Generator.h" // from ROOT #include "TRandom.h" // from project - generator #include "generator/CompGeneratorFactory.h" #include "generator/generator.h" #include "generator/Observables.h" // from project - configuration #include "configuration/CompConfig.h" namespace cptoymc { namespace generator { LLBkg_Generator::LLBkg_Generator() : CompGenerator(), params_mass_{0.}, params_timeandcp_{1.,0.}, params_timeresol_{0.033,0.72,0.,1.0}, params_taggingeffs_{0.30,0.06,0.04}, params_taggingOS_{0.5,0.,0.0,-1.0}, params_taggingSS_{0.5,0.,0.0,-1.0}, comp_cat_(-1001) { } LLBkg_Generator::~LLBkg_Generator() { } void LLBkg_Generator::Configure(const configuration::CompConfig& comp_config) { auto config_ptree = comp_config.model_ptree(); comp_cat_ = comp_config.comp_cat(); // Mass auto sub_config_ptree = config_ptree.get_child("Mass"); params_mass_.expo = sub_config_ptree.get("expo", params_mass_.expo); // TimeAndCP sub_config_ptree = config_ptree.get_child("TimeAndCP"); params_timeandcp_.tau = sub_config_ptree.get("tau", params_timeandcp_.tau); params_timeandcp_.prod_asym = sub_config_ptree.get("AP" , params_timeandcp_.prod_asym); sub_config_ptree = config_ptree.get_child("TimeResol"); params_timeresol_.lognormal_m = sub_config_ptree.get("lognormal_m", params_timeresol_.lognormal_m); params_timeresol_.lognormal_k = sub_config_ptree.get("lognormal_k", params_timeresol_.lognormal_k); params_timeresol_.bias = sub_config_ptree.get("bias" , params_timeresol_.bias ); params_timeresol_.scale = sub_config_ptree.get("scale" , params_timeresol_.scale ); // Tagging sub_config_ptree = config_ptree.get_child("Tagging"); params_taggingeffs_.eff_OS = sub_config_ptree.get("eff_OS" ,params_taggingeffs_.eff_OS ); params_taggingeffs_.eff_SS = sub_config_ptree.get("eff_SS" ,params_taggingeffs_.eff_SS ); params_taggingeffs_.eff_SSOS = sub_config_ptree.get("eff_SSOS" ,params_taggingeffs_.eff_SSOS ); params_taggingOS_.omega = sub_config_ptree.get("omega_OS" , params_taggingOS_.omega ); params_taggingOS_.domega = sub_config_ptree.get("domega_OS" , params_taggingOS_.domega ); params_taggingOS_.eta_dist_mean = sub_config_ptree.get("eta_dist_mean_OS" , params_taggingOS_.eta_dist_mean ); params_taggingOS_.eta_dist_sigma = sub_config_ptree.get("eta_dist_sigma_OS", params_taggingOS_.eta_dist_sigma); params_taggingSS_.omega = sub_config_ptree.get("omega_SS" , params_taggingSS_.omega ); params_taggingSS_.domega = sub_config_ptree.get("domega_SS" , params_taggingSS_.domega ); params_taggingSS_.eta_dist_mean = sub_config_ptree.get("eta_dist_mean_SS" , params_taggingSS_.eta_dist_mean ); params_taggingSS_.eta_dist_sigma = sub_config_ptree.get("eta_dist_sigma_SS", params_taggingSS_.eta_dist_sigma); } bool LLBkg_Generator::TryGenerateEvent(TRandom& rndm, Observables& observables) { bool gen_success = true; observables.comp_cat.set_value(comp_cat_); gen_success &= GenerateMass(rndm, observables.mass_true, observables.mass_meas); gen_success &= GenerateTimeAndTrueTag(rndm, observables.time_true, observables.timeerror, observables.tag_true, observables.time_meas); gen_success &= GenerateTagAndEta(rndm, observables.tag_true, observables.tag_OS, observables.eta_OS, observables.tag_SS, observables.eta_SS, observables.tag_class); return gen_success; } bool LLBkg_Generator::GenerateMass(TRandom& rndm, ObservableReal& obs_mass_true, ObservableReal& obs_mass_meas) { bool gen_success = true; obs_mass_true.value_ = -1000.; gen_success &= GenerateExpo(rndm,-1.*params_mass_.expo,obs_mass_meas.value_, obs_mass_meas.min_value(),obs_mass_meas.max_value()); return gen_success; } bool LLBkg_Generator::GenerateTimeAndTrueTag(TRandom& rndm, ObservableReal& obs_time_true, ObservableReal& obs_timeerror, ObservableInt& obs_tag_true, ObservableReal& obs_time_meas) { unsigned int trials = 0; bool gen_success = true; while (trials < max_trials_) { gen_success = true; // true "tag" according to prodasym obs_tag_true.value_ = (rndm.Uniform() < (1. - params_timeandcp_.prod_asym)/2.) ? +1 : -1; // decay time gen_success &= GenerateExpo(rndm,1./params_timeandcp_.tau,obs_time_true.value_,obs_time_true.min_value(),obs_time_true.max_value()); gen_success &= GenerateLognormal(rndm, params_timeresol_.lognormal_m, params_timeresol_.lognormal_k, obs_timeerror.min_value(), obs_timeerror.max_value(), obs_timeerror.value_); gen_success &= GenerateResolSingleGaussPerEvent(rndm, params_timeresol_.bias, params_timeresol_.scale, obs_timeerror.value_, obs_time_true.value(), obs_time_meas.value_); if (gen_success && obs_time_true.HasValidValue() && obs_time_meas.HasValidValue() && obs_tag_true.HasValidValue()) { break; } else { ++trials; } } if (!gen_success && trials >= max_trials_) { std::cout << "Problem in LLBkg generation for component " << comp_cat_ << ": Maximum trials reached without generating valid values for " << obs_tag_true.dim_name() << "," << obs_time_true.dim_name() << " and " << obs_time_meas.dim_name() << " !!!" << std::endl; } return gen_success; } bool LLBkg_Generator::GenerateTagAndEta(TRandom& rndm, const ObservableInt& obs_tag_true, ObservableInt& obs_tag_OS, ObservableReal& obs_eta_OS, ObservableInt& obs_tag_SS, ObservableReal& obs_eta_SS, ObservableInt& obs_tag_class) { bool gen_success = true; double random_val = rndm.Uniform(); if (random_val < params_taggingeffs_.eff_OS) { // generate OS tags and mistags // gen_success &= GenerateEtaFlat(rndm, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingOS_.eta_dist_mean, params_taggingOS_.eta_dist_sigma, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateTag(rndm, params_taggingOS_.omega, params_taggingOS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_OS.GetValueForType("B") , obs_tag_OS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_OS.value_); obs_tag_SS.value_ = obs_tag_SS.GetValueForType("None"); obs_eta_SS.value_ = 0.5; obs_tag_class.value_ = obs_tag_class.GetValueForType("OSonly"); } else if (random_val < (params_taggingeffs_.eff_OS + params_taggingeffs_.eff_SS)) { // generate SS tags and mistags // gen_success &= GenerateEtaFlat(rndm, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingSS_.eta_dist_mean, params_taggingSS_.eta_dist_sigma, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateTag(rndm, params_taggingSS_.omega, params_taggingSS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_SS.GetValueForType("B") , obs_tag_SS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_SS.value_); obs_tag_OS.value_ = obs_tag_OS.GetValueForType("None"); obs_eta_OS.value_ = 0.5; obs_tag_class.value_ = obs_tag_class.GetValueForType("SSonly"); } else if (random_val < ( params_taggingeffs_.eff_OS + params_taggingeffs_.eff_SS + params_taggingeffs_.eff_SSOS) ) { // generate overlap tags and mistags // gen_success &= GenerateEtaFlat(rndm, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingOS_.eta_dist_mean, params_taggingOS_.eta_dist_sigma, obs_eta_OS.min_value(), obs_eta_OS.max_value(), obs_eta_OS.value_); gen_success &= GenerateTag(rndm, params_taggingOS_.omega, params_taggingOS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_OS.GetValueForType("B") , obs_tag_OS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_OS.value_); // gen_success &= GenerateEtaFlat(rndm, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateEtaGauss(rndm, params_taggingSS_.eta_dist_mean, params_taggingSS_.eta_dist_sigma, obs_eta_SS.min_value(), obs_eta_SS.max_value(), obs_eta_SS.value_); gen_success &= GenerateTag(rndm, params_taggingSS_.omega, params_taggingSS_.domega, obs_tag_true.GetValueForType("B") , obs_tag_true.GetValueForType("Bb"), obs_tag_SS.GetValueForType("B") , obs_tag_SS.GetValueForType("Bb"), obs_tag_true.value(), obs_tag_SS.value_); obs_tag_class.value_ = obs_tag_class.GetValueForType("OSandSS"); } else { // untagged obs_tag_SS.value_ = obs_tag_SS.GetValueForType("None"); obs_eta_SS.value_ = 0.5; obs_tag_OS.value_ = obs_tag_OS.GetValueForType("None"); obs_eta_OS.value_ = 0.5; obs_tag_class.value_ = obs_tag_class.GetValueForType("untagged"); } return gen_success; } } // namespace generator } // namespace cptoymc <|endoftext|>
<commit_before>/*********************************************************************************************************************** * Copyright (C) 2016 Andrew Zonenberg and contributors * * * * 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, you may * * find one here: * * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * **********************************************************************************************************************/ #include "../xbpar/xbpar.h" #include "../greenpak4/Greenpak4.h" #include "Greenpak4PAREngine.h" #include <math.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction Greenpak4PAREngine::Greenpak4PAREngine(PARGraph* netlist, PARGraph* device) : PAREngine(netlist, device) { } Greenpak4PAREngine::~Greenpak4PAREngine() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Congestion metrics uint32_t Greenpak4PAREngine::ComputeCongestionCost() { uint32_t costs[2] = {0}; for(uint32_t i=0; i<m_device->GetNumNodes(); i++) { //If no node in the netlist is assigned to us, nothing to do PARGraphNode* node = m_device->GetNodeByIndex(i); PARGraphNode* netnode = node->GetMate(); if(netnode == NULL) continue; //Find all edges crossing the central routing matrix for(uint32_t i=0; i<netnode->GetEdgeCount(); i++) { auto edge = netnode->GetEdgeByIndex(i); auto src = static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()); auto dst = static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()); uint32_t sm = src->GetMatrix(); uint32_t dm = dst->GetMatrix(); //If we're driving a port that isn't general fabric routing, then it doesn't compete for cross connections if(!dst->IsGeneralFabricInput(edge->m_destport)) continue; //If the source has a dual, don't count this in the cost since it can route anywhere if(src->GetDual() != NULL) continue; //If matrices don't match, bump cost if(sm != dm) costs[sm] ++; } } //Squaring each half makes minimizing the larger one more important //vs if we just summed return sqrt(costs[0]*costs[0] + costs[1]*costs[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Print logic void Greenpak4PAREngine::PrintUnroutes(vector<PARGraphEdge*>& unroutes) { printf("\nUnroutable nets (%zu):\n", unroutes.size()); for(auto edge : unroutes) { auto source = static_cast<Greenpak4NetlistEntity*>(edge->m_sourcenode->GetData()); auto sport = dynamic_cast<Greenpak4NetlistPort*>(source); auto scell = dynamic_cast<Greenpak4NetlistCell*>(source); auto dest = static_cast<Greenpak4NetlistEntity*>(edge->m_destnode->GetData()); auto dport = dynamic_cast<Greenpak4NetlistPort*>(dest); auto dcell = dynamic_cast<Greenpak4NetlistCell*>(dest); if(scell != NULL) { auto entity = static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()); printf(" from cell %s (mapped to %s) port %s ", scell->m_name.c_str(), entity->GetDescription().c_str(), edge->m_sourceport.c_str() ); } else if(sport != NULL) { auto iob = static_cast<Greenpak4IOB*>(edge->m_sourcenode->GetMate()->GetData()); printf(" from port %s (mapped to IOB_%d)", sport->m_name.c_str(), iob->GetPinNumber()); } else printf(" from [invalid] "); printf(" to "); if(dcell != NULL) { auto entity = static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()); printf( "cell %s (mapped to %s) pin %s\n", dcell->m_name.c_str(), entity->GetDescription().c_str(), edge->m_destport.c_str() ); } else if(dport != NULL) printf("port %s\n", dport->m_name.c_str()); else printf("[invalid]\n"); } printf("\n"); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Optimization helpers /** @brief Find all nodes that are not optimally placed. This means that the node contributes in some nonzero fashion to the overall score of the system. Nodes are in the NETLIST graph, not the DEVICE graph. */ void Greenpak4PAREngine::FindSubOptimalPlacements(std::vector<PARGraphNode*>& bad_nodes) { std::set<PARGraphNode*> nodes; //Find all nodes that have at least one cross-spine route for(uint32_t i=0; i<m_device->GetNumNodes(); i++) { //If no node in the netlist is assigned to us, nothing to do PARGraphNode* node = m_device->GetNodeByIndex(i); PARGraphNode* netnode = node->GetMate(); if(netnode == NULL) continue; for(uint32_t i=0; i<netnode->GetEdgeCount(); i++) { auto edge = netnode->GetEdgeByIndex(i); auto src = static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()); auto dst = static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()); //Cross connections unsigned int srcmatrix = src->GetMatrix(); if(srcmatrix != dst->GetMatrix()) { //If there's nothing we can do about it, skip if(CantMoveSrc(src)) continue; if(CantMoveDst(dst)) continue; if(!dst->IsGeneralFabricInput(edge->m_destport)) continue; //Anything with a dual is always in an optimal location as far as congestion goes if(src->GetDual() != NULL) continue; //Add the node nodes.insert(edge->m_sourcenode); } } } //Find all nodes that are on one end of an unroutable edge m_unroutableNodes.clear(); std::vector<PARGraphEdge*> unroutes; ComputeUnroutableCost(unroutes); for(auto edge : unroutes) { if(!CantMoveSrc(static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()))) { m_unroutableNodes.insert(edge->m_sourcenode); nodes.insert(edge->m_sourcenode); } if(!CantMoveDst(static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()))) { m_unroutableNodes.insert(edge->m_destnode); nodes.insert(edge->m_destnode); } } //Push into the final output list for(auto x : nodes) bad_nodes.push_back(x); //DEBUG /* printf(" Optimizing (%d bad nodes, %d unroutes)\n", bad_nodes.size(), unroutes.size()); for(auto x : bad_nodes) printf(" * %s\n", static_cast<Greenpak4BitstreamEntity*>(x->GetMate()->GetData())->GetDescription().c_str()); */ } /** @brief Returns true if the given source node cannot be moved */ bool Greenpak4PAREngine::CantMoveSrc(Greenpak4BitstreamEntity* src) { //If source node is an IOB, do NOT add it to the sub-optimal list //because the IOB is constrained and can't move. //It's OK if the destination node is an IOB, moving its source is OK if(dynamic_cast<Greenpak4IOB*>(src) != NULL) return true; //If we have only one node of this type, we can't move it auto pn = src->GetPARNode(); if( (pn != NULL) && (m_device->GetNumNodesWithLabel(pn->GetLabel()) == 1) ) return true; //TODO: if it has a LOC constraint, don't add it //nope, it's movable return false; } /** @brief Returns true if the given destination node cannot be moved */ bool Greenpak4PAREngine::CantMoveDst(Greenpak4BitstreamEntity* dst) { //Oscillator as destination? //if(dynamic_cast<Greenpak4LFOscillator*>(dst) != NULL) // return true; //If we have only one node of this type, we can't move it auto pn = dst->GetPARNode(); if( (pn != NULL) && (m_device->GetNumNodesWithLabel(pn->GetLabel()) == 1) ) return true; //nope, it's movable return false; } /** @brief Find a new (hopefully more efficient) placement for a given netlist node */ PARGraphNode* Greenpak4PAREngine::GetNewPlacementForNode(PARGraphNode* pivot) { //Find which matrix we were assigned to PARGraphNode* current_node = pivot->GetMate(); auto current_site = static_cast<Greenpak4BitstreamEntity*>(current_node->GetData()); uint32_t current_matrix = current_site->GetMatrix(); uint32_t label = current_node->GetLabel(); //Debug log /* bool unroutable = (m_unroutableNodes.find(pivot) != m_unroutableNodes.end()); printf(" Seeking new placement for node %s (unroutable = %d)\n", current_site->GetDescription().c_str(), unroutable); */ //Default to trying the opposite matrix uint32_t target_matrix = 1 - current_matrix; //Make the list of candidate placements std::set<PARGraphNode*> temp_candidates; for(uint32_t i=0; i<m_device->GetNumNodesWithLabel(label); i++) { PARGraphNode* node = m_device->GetNodeByLabelAndIndex(label, i); Greenpak4BitstreamEntity* entity = static_cast<Greenpak4BitstreamEntity*>(node->GetData()); //Do not consider unroutable positions at this time if(0 != ComputeNodeUnroutableCost(pivot, node)) continue; if(entity->GetMatrix() == target_matrix) temp_candidates.insert(node); } //If no routable candidates found in the opposite matrix, check all matrices if(temp_candidates.empty()) { for(uint32_t i=0; i<m_device->GetNumNodesWithLabel(label); i++) { PARGraphNode* node = m_device->GetNodeByLabelAndIndex(label, i); if(0 != ComputeNodeUnroutableCost(pivot, node)) continue; temp_candidates.insert(node); } } //If no routable candidates found anywhere, consider the entire chip and hope we can patch things up later if(temp_candidates.empty()) { //printf(" No routable candidates found\n"); for(uint32_t i=0; i<m_device->GetNumNodesWithLabel(label); i++) temp_candidates.insert(m_device->GetNodeByLabelAndIndex(label, i)); } //Move to a vector for random access std::vector<PARGraphNode*> candidates; for(auto x : temp_candidates) candidates.push_back(x); uint32_t ncandidates = candidates.size(); if(ncandidates == 0) return NULL; //Pick one at random auto c = candidates[rand() % ncandidates]; /* printf(" Selected %s\n", static_cast<Greenpak4BitstreamEntity*>(c->GetData())->GetDescription().c_str()); */ return c; } <commit_msg>Fixed bug where incorrect node label could be used, causing INTERNAL ERROR abort<commit_after>/*********************************************************************************************************************** * Copyright (C) 2016 Andrew Zonenberg and contributors * * * * 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, you may * * find one here: * * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * **********************************************************************************************************************/ #include "../xbpar/xbpar.h" #include "../greenpak4/Greenpak4.h" #include "Greenpak4PAREngine.h" #include <math.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction Greenpak4PAREngine::Greenpak4PAREngine(PARGraph* netlist, PARGraph* device) : PAREngine(netlist, device) { } Greenpak4PAREngine::~Greenpak4PAREngine() { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Congestion metrics uint32_t Greenpak4PAREngine::ComputeCongestionCost() { uint32_t costs[2] = {0}; for(uint32_t i=0; i<m_device->GetNumNodes(); i++) { //If no node in the netlist is assigned to us, nothing to do PARGraphNode* node = m_device->GetNodeByIndex(i); PARGraphNode* netnode = node->GetMate(); if(netnode == NULL) continue; //Find all edges crossing the central routing matrix for(uint32_t i=0; i<netnode->GetEdgeCount(); i++) { auto edge = netnode->GetEdgeByIndex(i); auto src = static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()); auto dst = static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()); uint32_t sm = src->GetMatrix(); uint32_t dm = dst->GetMatrix(); //If we're driving a port that isn't general fabric routing, then it doesn't compete for cross connections if(!dst->IsGeneralFabricInput(edge->m_destport)) continue; //If the source has a dual, don't count this in the cost since it can route anywhere if(src->GetDual() != NULL) continue; //If matrices don't match, bump cost if(sm != dm) costs[sm] ++; } } //Squaring each half makes minimizing the larger one more important //vs if we just summed return sqrt(costs[0]*costs[0] + costs[1]*costs[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Print logic void Greenpak4PAREngine::PrintUnroutes(vector<PARGraphEdge*>& unroutes) { printf("\nUnroutable nets (%zu):\n", unroutes.size()); for(auto edge : unroutes) { auto source = static_cast<Greenpak4NetlistEntity*>(edge->m_sourcenode->GetData()); auto sport = dynamic_cast<Greenpak4NetlistPort*>(source); auto scell = dynamic_cast<Greenpak4NetlistCell*>(source); auto dest = static_cast<Greenpak4NetlistEntity*>(edge->m_destnode->GetData()); auto dport = dynamic_cast<Greenpak4NetlistPort*>(dest); auto dcell = dynamic_cast<Greenpak4NetlistCell*>(dest); if(scell != NULL) { auto entity = static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()); printf(" from cell %s (mapped to %s) port %s ", scell->m_name.c_str(), entity->GetDescription().c_str(), edge->m_sourceport.c_str() ); } else if(sport != NULL) { auto iob = static_cast<Greenpak4IOB*>(edge->m_sourcenode->GetMate()->GetData()); printf(" from port %s (mapped to IOB_%d)", sport->m_name.c_str(), iob->GetPinNumber()); } else printf(" from [invalid] "); printf(" to "); if(dcell != NULL) { auto entity = static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()); printf( "cell %s (mapped to %s) pin %s\n", dcell->m_name.c_str(), entity->GetDescription().c_str(), edge->m_destport.c_str() ); } else if(dport != NULL) printf("port %s\n", dport->m_name.c_str()); else printf("[invalid]\n"); } printf("\n"); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Optimization helpers /** @brief Find all nodes that are not optimally placed. This means that the node contributes in some nonzero fashion to the overall score of the system. Nodes are in the NETLIST graph, not the DEVICE graph. */ void Greenpak4PAREngine::FindSubOptimalPlacements(std::vector<PARGraphNode*>& bad_nodes) { std::set<PARGraphNode*> nodes; //Find all nodes that have at least one cross-spine route for(uint32_t i=0; i<m_device->GetNumNodes(); i++) { //If no node in the netlist is assigned to us, nothing to do PARGraphNode* node = m_device->GetNodeByIndex(i); PARGraphNode* netnode = node->GetMate(); if(netnode == NULL) continue; for(uint32_t i=0; i<netnode->GetEdgeCount(); i++) { auto edge = netnode->GetEdgeByIndex(i); auto src = static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()); auto dst = static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()); //Cross connections unsigned int srcmatrix = src->GetMatrix(); if(srcmatrix != dst->GetMatrix()) { //If there's nothing we can do about it, skip if(CantMoveSrc(src)) continue; if(CantMoveDst(dst)) continue; if(!dst->IsGeneralFabricInput(edge->m_destport)) continue; //Anything with a dual is always in an optimal location as far as congestion goes if(src->GetDual() != NULL) continue; //Add the node nodes.insert(edge->m_sourcenode); } } } //Find all nodes that are on one end of an unroutable edge m_unroutableNodes.clear(); std::vector<PARGraphEdge*> unroutes; ComputeUnroutableCost(unroutes); for(auto edge : unroutes) { if(!CantMoveSrc(static_cast<Greenpak4BitstreamEntity*>(edge->m_sourcenode->GetMate()->GetData()))) { m_unroutableNodes.insert(edge->m_sourcenode); nodes.insert(edge->m_sourcenode); } if(!CantMoveDst(static_cast<Greenpak4BitstreamEntity*>(edge->m_destnode->GetMate()->GetData()))) { m_unroutableNodes.insert(edge->m_destnode); nodes.insert(edge->m_destnode); } } //Push into the final output list for(auto x : nodes) bad_nodes.push_back(x); //DEBUG /* printf(" Optimizing (%d bad nodes, %d unroutes)\n", bad_nodes.size(), unroutes.size()); for(auto x : bad_nodes) printf(" * %s\n", static_cast<Greenpak4BitstreamEntity*>(x->GetMate()->GetData())->GetDescription().c_str()); */ } /** @brief Returns true if the given source node cannot be moved */ bool Greenpak4PAREngine::CantMoveSrc(Greenpak4BitstreamEntity* src) { //If source node is an IOB, do NOT add it to the sub-optimal list //because the IOB is constrained and can't move. //It's OK if the destination node is an IOB, moving its source is OK if(dynamic_cast<Greenpak4IOB*>(src) != NULL) return true; //If we have only one node of this type, we can't move it auto pn = src->GetPARNode(); if( (pn != NULL) && (m_device->GetNumNodesWithLabel(pn->GetLabel()) == 1) ) return true; //TODO: if it has a LOC constraint, don't add it //nope, it's movable return false; } /** @brief Returns true if the given destination node cannot be moved */ bool Greenpak4PAREngine::CantMoveDst(Greenpak4BitstreamEntity* dst) { //Oscillator as destination? //if(dynamic_cast<Greenpak4LFOscillator*>(dst) != NULL) // return true; //If we have only one node of this type, we can't move it auto pn = dst->GetPARNode(); if( (pn != NULL) && (m_device->GetNumNodesWithLabel(pn->GetLabel()) == 1) ) return true; //nope, it's movable return false; } /** @brief Find a new (hopefully more efficient) placement for a given netlist node */ PARGraphNode* Greenpak4PAREngine::GetNewPlacementForNode(PARGraphNode* pivot) { //Find which matrix we were assigned to PARGraphNode* current_node = pivot->GetMate(); auto current_site = static_cast<Greenpak4BitstreamEntity*>(current_node->GetData()); uint32_t current_matrix = current_site->GetMatrix(); //BUGFIX: Use the netlist node's label, not the PAR node uint32_t label = pivot->GetLabel(); //Debug log /* bool unroutable = (m_unroutableNodes.find(pivot) != m_unroutableNodes.end()); printf(" Seeking new placement for node %s (unroutable = %d)\n", current_site->GetDescription().c_str(), unroutable); */ //Default to trying the opposite matrix uint32_t target_matrix = 1 - current_matrix; //Make the list of candidate placements std::set<PARGraphNode*> temp_candidates; for(uint32_t i=0; i<m_device->GetNumNodesWithLabel(label); i++) { PARGraphNode* node = m_device->GetNodeByLabelAndIndex(label, i); Greenpak4BitstreamEntity* entity = static_cast<Greenpak4BitstreamEntity*>(node->GetData()); //Do not consider unroutable positions at this time if(0 != ComputeNodeUnroutableCost(pivot, node)) continue; if(entity->GetMatrix() == target_matrix) temp_candidates.insert(node); } //If no routable candidates found in the opposite matrix, check all matrices if(temp_candidates.empty()) { for(uint32_t i=0; i<m_device->GetNumNodesWithLabel(label); i++) { PARGraphNode* node = m_device->GetNodeByLabelAndIndex(label, i); if(0 != ComputeNodeUnroutableCost(pivot, node)) continue; temp_candidates.insert(node); } } //If no routable candidates found anywhere, consider the entire chip and hope we can patch things up later if(temp_candidates.empty()) { //printf(" No routable candidates found\n"); for(uint32_t i=0; i<m_device->GetNumNodesWithLabel(label); i++) temp_candidates.insert(m_device->GetNodeByLabelAndIndex(label, i)); } //Move to a vector for random access std::vector<PARGraphNode*> candidates; for(auto x : temp_candidates) candidates.push_back(x); uint32_t ncandidates = candidates.size(); if(ncandidates == 0) return NULL; //Pick one at random auto c = candidates[rand() % ncandidates]; /* printf(" Selected %s\n", static_cast<Greenpak4BitstreamEntity*>(c->GetData())->GetDescription().c_str()); */ return c; } <|endoftext|>
<commit_before>/***************************************************************************** * * * Copyright (c) 2013-2016 Boris Pek <[email protected]> * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * *****************************************************************************/ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <sys/types.h> #include <sys/stat.h> #include <cstdlib> #include <cstring> #include <fcgi_stdio.h> #include "Version.h" using namespace std; string basic_str = "/bosixnet/"; string log_dir = "/var/tmp/bosixnet"; string conf_file = "/etc/bosixnet/bosixnet-webui.conf"; map<string, string> hosts_map; bool check_options(int, char **); void read_options(int, char **); void read_config(); void show_help(); void show_version(); void show_html(const string &); void show_hosts(); void read_hosts(); void write_hosts(); bool ends_with(const string &, const string &); bool starts_with(const string &, const string &); bool is_valid_ipv6_address(const string &); string get_env_var(const string &); string get_param(const string &, const string &); string get_conf_var(const string &, const string &); string remove_extra_symbols(const string &, const string &); int main(int argc, char **argv) { if (check_options(argc, argv)) return 0; // Settings in config file have lower priority than command line options. string conf_file_default = conf_file; read_config(); read_options(argc, argv); if (conf_file != conf_file_default) { read_config(); read_options(argc, argv); } read_hosts(); int counter = 0; while (FCGI_Accept() >= 0) { ++counter; string content; string request_method = get_env_var("REQUEST_METHOD"); if (request_method.empty()) { continue; } if (request_method == "GET") { content = get_env_var("QUERY_STRING"); } else { show_html("<center><h2>Only GET request method is allowed!</h2></center>\n"); continue; }; string full_path = get_env_var("SCRIPT_NAME"); string path = get_env_var("SCRIPT_FULL_PATHNAME"); if (ends_with(full_path, basic_str)) { show_hosts(); } else if (ends_with(full_path, basic_str + "hosts")) { show_hosts(); } else if (ends_with(full_path, basic_str + "counter")) { stringstream counter_str; counter_str << counter; show_html("Counter: " + counter_str.str()); } else { string host_name = full_path.substr(full_path.rfind("/") + 1); string new_address = get_param(content, "update="); if (new_address.empty()) { map<string, string>::iterator it = hosts_map.find(host_name); if (it != hosts_map.end()) { show_html(it->second); } else { show_html(""); } } else if (is_valid_ipv6_address(new_address)) { if (hosts_map[host_name] != new_address) { hosts_map[host_name] = new_address; write_hosts(); } show_html(new_address); } else { show_html(new_address + " is not a valid IPv6 address!"); } } } return 0; } bool check_options(int argc, char **argv) { string arg; for (int idx = 1 ; idx < argc ; ++idx) { arg = argv[idx]; if (arg == "-h" || arg == "--help") { show_help(); return true; } else if (arg == "-v" || arg == "--version") { show_version(); return true; } } return false; } void read_options(int argc, char **argv) { if (argc > 2) { string arg; string arg_next; for (int idx = 1 ; idx < argc - 1 ; ++idx) { arg = argv[idx]; arg_next = argv[idx + 1]; if (arg == "-b" || arg == "--basic-str") { basic_str = arg_next; } else if (arg == "-l" || arg == "--log-dir") { log_dir = arg_next; } else if (arg == "-c" || arg == "--conf-file") { conf_file = arg_next; } } } } void read_config() { ifstream file; file.open(conf_file.c_str(), ios::in); if (file.is_open()) { string buff, var, tmp; while (!file.eof()) { getline(file, buff); buff = remove_extra_symbols(buff, " \t"); if (buff.size() >= 3 && buff.at(0) != '#') { var = "BASIC_STR"; tmp = get_conf_var(buff, var); if (!tmp.empty()) { basic_str = tmp; } var = "LOG_DIR"; tmp = get_conf_var(buff, var); if (!tmp.empty()) { log_dir = tmp; } } } file.close(); } } void show_help() { cout << "Usage: bosixnet_webui [options]\n" "\n" "FastCGI program which passively listens for incoming connections and\n" "generates list of hosts in your IPv6 network. This daemon prepares data\n" "which may be put directly into /etc/hosts.\n" "\n" "Generic options:\n" " -h, --help show help\n" " -v, --version show version\n" "\n" "Options:\n" " -b <string>, --basic-str <string> set basic url (default: " + basic_str + ")\n" " -l <dir>, --log-dir <dir> set log directory (default: " + log_dir + ")\n" " -c <file>, --conf-file <file> set config file (default: " + conf_file + ")\n" "\n" "Settings in config file have lower priority than command line options.\n"; } void show_version() { cout << "Version: " << string(VERSION) << "\n"; } void show_html(const string &str) { printf("Content-type: text/html\n\n"); printf("%s", str.c_str()); } void show_hosts() { string log_file = log_dir + "/hosts"; string out = "File " + log_file + " is empty!"; ifstream file; file.open(log_file.c_str(), ios::in); if (file.is_open()) { out.clear(); string buff; while (!file.eof()) { getline(file, buff); out += buff + "<br>\n"; } file.close(); } show_html(out); } void read_hosts() { string log_file = log_dir + "/hosts"; ifstream file; file.open(log_file.c_str(), ios::in); if (file.is_open()) { string buff, host, addr; stringstream str; while (!file.eof()) { getline(file, buff); str.clear(); str << buff; str >> addr; str >> host; if (!addr.empty() && !host.empty()){ if (is_valid_ipv6_address(addr)){ hosts_map[host] = addr; } } } file.close(); } } void write_hosts() { struct stat info; if (stat(log_dir.c_str(), &info)) { if (mkdir(log_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) { cout << "Directory " << log_dir << " was not created!\n"; return; } } string log_file = log_dir + "/hosts"; ofstream file; file.open(log_file.c_str(), ios::out); if (file.is_open()) { for (map<string, string>::iterator it = hosts_map.begin(); it != hosts_map.end(); ++it) { file << it->second << " " << it->first << "\n"; } file.close(); } } bool ends_with(const string &str, const string &sfx) { if (sfx.size() > str.size()) return false; return equal(str.begin() + str.size() - sfx.size(), str.end(), sfx.begin()); } bool starts_with(const string &str, const string &pfx) { if (pfx.size() > str.size()) return false; return equal(str.begin(), str.begin() + pfx.size(), pfx.begin()); } bool is_valid_ipv6_address(const string &str) { size_t len = str.size(); if (len < 8) return false; else if (len > 39) return false; unsigned int counter = 0; const char *p = str.c_str(); while (strstr(p,":")) { ++counter; ++p; } if (counter < 3) return false; else if (str.at(4) != ':') return false; if (str.find_first_not_of(":0123456789abcdefABCDEF") != string::npos) return false; return true; } string get_env_var(const string &var) { char *ptr = getenv(var.c_str()); return (ptr ? string(ptr) : ""); } string get_param(const string &buff, const string &name) { if (buff.empty() || name.empty()) return ""; size_t param_begin = buff.find(name); if (param_begin == string::npos) return ""; param_begin += name.size(); if (param_begin >= buff.size()) return ""; size_t param_end = buff.find("&", param_begin); if (param_end == string::npos) param_end = buff.size(); string out = buff.substr(param_begin, param_end - param_begin); return out; } string get_conf_var(const string &buff, const string &var) { if (!starts_with(buff, var)) return ""; string out = buff.substr(var.size()); out = remove_extra_symbols(out, "= \t\""); return out; } string remove_extra_symbols(const string &str, const string &symbols) { string out = str; size_t pos = out.find_first_not_of(symbols); if (pos != string::npos) { out = out.substr(pos); } pos = out.find_last_not_of(symbols); if (pos != string::npos && pos != out.size() - 1) { out = out.substr(0, pos + 1); } return out; } <commit_msg>[Web UI] Add special page "/timestamps".<commit_after>/***************************************************************************** * * * Copyright (c) 2013-2016 Boris Pek <[email protected]> * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be included * * in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * * *****************************************************************************/ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <ctime> #include <map> #include <sys/types.h> #include <sys/stat.h> #include <cstdlib> #include <cstring> #include <fcgi_stdio.h> #include "Version.h" using namespace std; string basic_str = "/bosixnet/"; string log_dir = "/var/tmp/bosixnet"; string conf_file = "/etc/bosixnet/bosixnet-webui.conf"; map<string, string> hosts_map; map<string, string> timestamps_map; bool check_options(int, char **); void read_options(int, char **); void read_config(); void show_help(); void show_version(); void show_html(const string &); void show_file(const string &); void show_hosts(); void show_timestamps(); void update_timestamp(const string &); void read_file(const string &, map<string, string> &); void read_hosts(); void read_timestamps(); void write_file(const string &, const map<string, string> &); void write_hosts(); void write_timestamps(); bool ends_with(const string &, const string &); bool starts_with(const string &, const string &); bool is_valid_ipv6_address(const string &); string get_env_var(const string &); string get_param(const string &, const string &); string get_conf_var(const string &, const string &); string remove_extra_symbols(const string &, const string &); int main(int argc, char **argv) { if (check_options(argc, argv)) return 0; // Settings in config file have lower priority than command line options. string conf_file_default = conf_file; read_config(); read_options(argc, argv); if (conf_file != conf_file_default) { read_config(); read_options(argc, argv); } read_hosts(); read_timestamps(); int counter = 0; while (FCGI_Accept() >= 0) { ++counter; string content; string request_method = get_env_var("REQUEST_METHOD"); if (request_method.empty()) { continue; } if (request_method == "GET") { content = get_env_var("QUERY_STRING"); } else { show_html("<center><h2>Only GET request method is allowed!</h2></center>\n"); continue; }; string full_path = get_env_var("SCRIPT_NAME"); string path = get_env_var("SCRIPT_FULL_PATHNAME"); if (ends_with(full_path, basic_str)) { show_hosts(); } else if (ends_with(full_path, basic_str + "hosts")) { show_hosts(); } else if (ends_with(full_path, basic_str + "timestamps")) { show_timestamps(); } else if (ends_with(full_path, basic_str + "counter")) { stringstream counter_str; counter_str << counter; show_html("Counter: " + counter_str.str()); } else { string host_name = full_path.substr(full_path.rfind("/") + 1); string new_address = get_param(content, "update="); if (new_address.empty()) { map<string, string>::iterator it = hosts_map.find(host_name); if (it != hosts_map.end()) { show_html(it->second); } else { show_html(""); } } else if (is_valid_ipv6_address(new_address)) { if (hosts_map[host_name] != new_address) { hosts_map[host_name] = new_address; write_hosts(); update_timestamp(host_name); write_timestamps(); } show_html(new_address); } else { show_html(new_address + " is not a valid IPv6 address!"); } } } return 0; } bool check_options(int argc, char **argv) { string arg; for (int idx = 1 ; idx < argc ; ++idx) { arg = argv[idx]; if (arg == "-h" || arg == "--help") { show_help(); return true; } else if (arg == "-v" || arg == "--version") { show_version(); return true; } } return false; } void read_options(int argc, char **argv) { if (argc > 2) { string arg; string arg_next; for (int idx = 1 ; idx < argc - 1 ; ++idx) { arg = argv[idx]; arg_next = argv[idx + 1]; if (arg == "-b" || arg == "--basic-str") { basic_str = arg_next; } else if (arg == "-l" || arg == "--log-dir") { log_dir = arg_next; } else if (arg == "-c" || arg == "--conf-file") { conf_file = arg_next; } } } } void read_config() { ifstream file; file.open(conf_file.c_str(), ios::in); if (file.is_open()) { string buff, var, tmp; while (!file.eof()) { getline(file, buff); buff = remove_extra_symbols(buff, " \t"); if (buff.size() >= 3 && buff.at(0) != '#') { var = "BASIC_STR"; tmp = get_conf_var(buff, var); if (!tmp.empty()) { basic_str = tmp; } var = "LOG_DIR"; tmp = get_conf_var(buff, var); if (!tmp.empty()) { log_dir = tmp; } } } file.close(); } } void show_help() { cout << "Usage: bosixnet_webui [options]\n" "\n" "FastCGI program which passively listens for incoming connections and\n" "generates list of hosts in your IPv6 network. This daemon prepares data\n" "which may be put directly into /etc/hosts.\n" "\n" "Generic options:\n" " -h, --help show help\n" " -v, --version show version\n" "\n" "Options:\n" " -b <string>, --basic-str <string> set basic url (default: " + basic_str + ")\n" " -l <dir>, --log-dir <dir> set log directory (default: " + log_dir + ")\n" " -c <file>, --conf-file <file> set config file (default: " + conf_file + ")\n" "\n" "Settings in config file have lower priority than command line options.\n"; } void show_version() { cout << "Version: " << string(VERSION) << "\n"; } void show_html(const string &str) { printf("Content-type: text/html\n\n"); printf("%s", str.c_str()); } void show_file(const string &file_name) { string log_file = log_dir + file_name; string out = "File " + log_file + " is empty!"; ifstream file; file.open(log_file.c_str(), ios::in); if (file.is_open()) { out.clear(); string buff; while (!file.eof()) { getline(file, buff); out += buff + "<br>\n"; } file.close(); } show_html(out); } void show_hosts() { show_file("/hosts"); } void show_timestamps() { show_file("/timestamps"); } void update_timestamp(const string &host_name) { const time_t current_time = time(0); const struct tm *time_info = localtime(&current_time); char new_timestamp[20]; strftime(new_timestamp, 20, "%F_%H:%M:%S", time_info); timestamps_map[host_name] = string(new_timestamp); } void read_file(const string &file_name, map<string, string> &map_name) { string log_file = log_dir + file_name; ifstream file; file.open(log_file.c_str(), ios::in); if (file.is_open()) { string buff, key, value; stringstream str; while (!file.eof()) { getline(file, buff); str.clear(); str << buff; str >> value; str >> key; if (!value.empty() && !key.empty()) { if (is_valid_ipv6_address(value)) { map_name[key] = value; } } } file.close(); } } void read_hosts() { read_file("/hosts", hosts_map); } void read_timestamps() { read_file("/timestamps", timestamps_map); } void write_file(const string &file_name, const map<string, string> &map_name) { struct stat info; if (stat(log_dir.c_str(), &info)) { if (mkdir(log_dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) { cout << "Directory " << log_dir << " was not created!\n"; return; } } string log_file = log_dir + file_name; ofstream file; file.open(log_file.c_str(), ios::out); if (file.is_open()) { for (map<string, string>::const_iterator it = map_name.cbegin(); it != map_name.cend(); ++it) { file << it->second << " " << it->first << "\n"; } file.close(); } } void write_hosts() { write_file("/hosts", hosts_map); } void write_timestamps() { write_file("/timestamps", timestamps_map); } bool ends_with(const string &str, const string &sfx) { if (sfx.size() > str.size()) return false; return equal(str.begin() + str.size() - sfx.size(), str.end(), sfx.begin()); } bool starts_with(const string &str, const string &pfx) { if (pfx.size() > str.size()) return false; return equal(str.begin(), str.begin() + pfx.size(), pfx.begin()); } bool is_valid_ipv6_address(const string &str) { size_t len = str.size(); if (len < 8) return false; else if (len > 39) return false; unsigned int counter = 0; const char *p = str.c_str(); while (strstr(p,":")) { ++counter; ++p; } if (counter < 3) return false; else if (str.at(4) != ':') return false; if (str.find_first_not_of(":0123456789abcdefABCDEF") != string::npos) return false; return true; } string get_env_var(const string &var) { char *ptr = getenv(var.c_str()); return (ptr ? string(ptr) : ""); } string get_param(const string &buff, const string &name) { if (buff.empty() || name.empty()) return ""; size_t param_begin = buff.find(name); if (param_begin == string::npos) return ""; param_begin += name.size(); if (param_begin >= buff.size()) return ""; size_t param_end = buff.find("&", param_begin); if (param_end == string::npos) param_end = buff.size(); string out = buff.substr(param_begin, param_end - param_begin); return out; } string get_conf_var(const string &buff, const string &var) { if (!starts_with(buff, var)) return ""; string out = buff.substr(var.size()); out = remove_extra_symbols(out, "= \t\""); return out; } string remove_extra_symbols(const string &str, const string &symbols) { string out = str; size_t pos = out.find_first_not_of(symbols); if (pos != string::npos) { out = out.substr(pos); } pos = out.find_last_not_of(symbols); if (pos != string::npos && pos != out.size() - 1) { out = out.substr(0, pos + 1); } return out; } <|endoftext|>
<commit_before>#include "image/registration/linear.h" namespace MR { namespace Image { namespace Registration { using namespace App; const char* initialisation_choices[] = { "mass", "geometric", "none", NULL }; const OptionGroup rigid_options = OptionGroup ("Rigid registration options") + Option ("rigid_out", "the output text file containing the rigid transformation as a 4x4 matrix") + Argument ("file").type_file () + Option ("rigid_scale", "use a multi-resolution scheme by defining a scale factor for each level " "using comma separated values (Default: 0.5,1)") + Argument ("factor").type_sequence_float () + Option ("rigid_niter", "the maximum number of iterations. This can be specified either as a single number " "for all multi-resolution levels, or a single value for each level. (Default: 1000)") + Argument ("num").type_sequence_int (); const OptionGroup affine_options = OptionGroup ("Affine registration options") + Option ("affine_out", "the output text file containing the affine transformation as a 4x4 matrix") + Argument ("file").type_file () + Option ("affine_scale", "use a multi-resolution scheme by defining a scale factor for each level " "using comma separated values (Default: 0.5,1)") + Argument ("factor").type_sequence_float () + Option ("affine_niter", "the maximum number of iterations. This can be specified either as a single number " "for all multi-resolution levels, or a single value for each level. (Default: 1000)") + Argument ("num").type_sequence_int (); const OptionGroup syn_options = OptionGroup ("SyN registration options") + Option ("warp", "the output non-linear warp defined as a deformation field") + Argument ("image").type_file () + Option ("syn_scale", "use a multi-resolution scheme by defining a scale factor for each level " "using comma separated values (Default: 0.5,1)") + Argument ("factor").type_sequence_float () + Option ("syn_niter", "the maximum number of iterations. This can be specified either as a single number " "for all multi-resolution levels, or a single value for each level. (Default: 1000)") + Argument ("num").type_sequence_int () + Option ("smooth_grad", "regularise the gradient field with Gaussian smoothing (standard deviation in mm, Default 3 x voxel_size)") + Argument ("stdev").type_float () + Option ("smooth_disp", "regularise the displacement field with Gaussian smoothing (standard deviation in mm, Default 0.5 x voxel_size)") + Argument ("stdev").type_float () + Option ("grad_step", "the initial gradient step size for SyN registration (Default: 0.12)") //TODO + Argument ("num").type_float (); const OptionGroup initialisation_options = OptionGroup ("Initialisation options") + Option ("rigid_init", "initialise either the rigid, affine, or syn registration with the supplied rigid transformation (as a 4x4 matrix)") + Argument ("file").type_file () + Option ("affine_init", "initialise either the affine, or syn registration with the supplied affine transformation (as a 4x4 matrix)") + Argument ("file").type_file () + Option ("syn_init", "initialise the syn registration with the supplied warp image (which includes the linear transform)") + Argument ("image").type_image_in () + Option ("centre", "for rigid and affine registration only: Initialise the centre of rotation and initial translation. " "Valid choices are: mass (which uses the image center of mass), geometric (geometric image centre) or none. " "Default: mass (which may not be suited for multi-modality registration).") + Argument ("type").type_choice (initialisation_choices); const OptionGroup fod_options = OptionGroup ("FOD registration options") + Option ("directions", "the directions used for FOD reorienation using apodised point spread functions (Default: 60 directions)") + Argument ("file", "a list of directions [az el] generated using the gendir command.").type_file() + Option ("lmax", "explicitly set the lmax to be used in FOD registration. By default FOD registration will " "first use lmax 2 until convergence, then add lmax 4 SH coefficients and run till convergence") + Argument ("num").type_integer () + Option ("noreorientation", "turn off FOD reorientation. Reorientation is on by default if the number " "of volumes in the 4th dimension corresponds to the number of coefficients in an " "antipodally symmetric spherical harmonic series (i.e. 6, 15, 28, 45, 66 etc"); } } } <commit_msg>Updated registration commands to use new argument input output functions<commit_after>#include "image/registration/linear.h" namespace MR { namespace Image { namespace Registration { using namespace App; const char* initialisation_choices[] = { "mass", "geometric", "none", NULL }; const OptionGroup rigid_options = OptionGroup ("Rigid registration options") + Option ("rigid_out", "the output text file containing the rigid transformation as a 4x4 matrix") + Argument ("file").type_file_in () + Option ("rigid_scale", "use a multi-resolution scheme by defining a scale factor for each level " "using comma separated values (Default: 0.5,1)") + Argument ("factor").type_sequence_float () + Option ("rigid_niter", "the maximum number of iterations. This can be specified either as a single number " "for all multi-resolution levels, or a single value for each level. (Default: 1000)") + Argument ("num").type_sequence_int (); const OptionGroup affine_options = OptionGroup ("Affine registration options") + Option ("affine_out", "the output text file containing the affine transformation as a 4x4 matrix") + Argument ("file").type_file_out () + Option ("affine_scale", "use a multi-resolution scheme by defining a scale factor for each level " "using comma separated values (Default: 0.5,1)") + Argument ("factor").type_sequence_float () + Option ("affine_niter", "the maximum number of iterations. This can be specified either as a single number " "for all multi-resolution levels, or a single value for each level. (Default: 1000)") + Argument ("num").type_sequence_int (); const OptionGroup syn_options = OptionGroup ("SyN registration options") + Option ("warp", "the output non-linear warp defined as a deformation field") + Argument ("image").type_file_out () + Option ("syn_scale", "use a multi-resolution scheme by defining a scale factor for each level " "using comma separated values (Default: 0.5,1)") + Argument ("factor").type_sequence_float () + Option ("syn_niter", "the maximum number of iterations. This can be specified either as a single number " "for all multi-resolution levels, or a single value for each level. (Default: 1000)") + Argument ("num").type_sequence_int () + Option ("smooth_grad", "regularise the gradient field with Gaussian smoothing (standard deviation in mm, Default 3 x voxel_size)") + Argument ("stdev").type_float () + Option ("smooth_disp", "regularise the displacement field with Gaussian smoothing (standard deviation in mm, Default 0.5 x voxel_size)") + Argument ("stdev").type_float () + Option ("grad_step", "the initial gradient step size for SyN registration (Default: 0.12)") //TODO + Argument ("num").type_float (); const OptionGroup initialisation_options = OptionGroup ("Initialisation options") + Option ("rigid_init", "initialise either the rigid, affine, or syn registration with the supplied rigid transformation (as a 4x4 matrix)") + Argument ("file").type_file_in () + Option ("affine_init", "initialise either the affine, or syn registration with the supplied affine transformation (as a 4x4 matrix)") + Argument ("file").type_file_in () + Option ("syn_init", "initialise the syn registration with the supplied warp image (which includes the linear transform)") + Argument ("image").type_image_in () + Option ("centre", "for rigid and affine registration only: Initialise the centre of rotation and initial translation. " "Valid choices are: mass (which uses the image center of mass), geometric (geometric image centre) or none. " "Default: mass (which may not be suited for multi-modality registration).") + Argument ("type").type_choice (initialisation_choices); const OptionGroup fod_options = OptionGroup ("FOD registration options") + Option ("directions", "the directions used for FOD reorienation using apodised point spread functions (Default: 60 directions)") + Argument ("file", "a list of directions [az el] generated using the gendir command.").type_file_in () + Option ("lmax", "explicitly set the lmax to be used in FOD registration. By default FOD registration will " "first use lmax 2 until convergence, then add lmax 4 SH coefficients and run till convergence") + Argument ("num").type_integer () + Option ("noreorientation", "turn off FOD reorientation. Reorientation is on by default if the number " "of volumes in the 4th dimension corresponds to the number of coefficients in an " "antipodally symmetric spherical harmonic series (i.e. 6, 15, 28, 45, 66 etc"); } } } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c): 2014 Graeme Hill (http://graemehill.ca) 2016 deipi.com LLC and contributors 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 "guid.h" #include <algorithm> #include <iomanip> #include "/System/Library/Frameworks/CoreFoundation.framework/Headers/CFBase.h" #include "config.h" #ifdef GUID_LIBUUID #include <uuid/uuid.h> #endif #ifdef GUID_FREEBSD #include <uuid.h> #include <cstdint> #include <cstring> #endif #ifdef GUID_CFUUID #include <CoreFoundation/CFUUID.h> #endif #ifdef GUID_WINDOWS #include <objbase.h> #endif using namespace std; // overload << so that it's easy to convert to a string ostream& operator<<(ostream& s, const Guid& guid) { return s << hex << setfill('0') << setw(2) << (int)guid._bytes[0] << setw(2) << (int)guid._bytes[1] << setw(2) << (int)guid._bytes[2] << setw(2) << (int)guid._bytes[3] << "-" << setw(2) << (int)guid._bytes[4] << setw(2) << (int)guid._bytes[5] << "-" << setw(2) << (int)guid._bytes[6] << setw(2) << (int)guid._bytes[7] << "-" << setw(2) << (int)guid._bytes[8] << setw(2) << (int)guid._bytes[9] << "-" << setw(2) << (int)guid._bytes[10] << setw(2) << (int)guid._bytes[11] << setw(2) << (int)guid._bytes[12] << setw(2) << (int)guid._bytes[13] << setw(2) << (int)guid._bytes[14] << setw(2) << (int)guid._bytes[15]; } // create a guid from vector of bytes Guid::Guid(const vector<unsigned char>& bytes) : _bytes(bytes) { } // create a guid from array of bytes Guid::Guid(const unsigned char* bytes) : _bytes(bytes, bytes + 16) { } // converts a single hex char to a number (0 - 15) unsigned char hexDigitToChar(char ch) { if (ch > 47 && ch < 58) return ch - 48; if (ch > 96 && ch < 103) return ch - 87; if (ch > 64 && ch < 71) return ch - 55; return 0; } // converts the two hexadecimal characters to an unsigned char (a byte) unsigned char hexPairToChar(char a, char b) { return hexDigitToChar(a) * 16 + hexDigitToChar(b); } // create a guid from string Guid::Guid(const string& fromString) { char charOne, charTwo; bool lookingForFirstChar = true; _bytes.reserve(16); for (const char& ch : fromString) { if (ch == '-') continue; if (lookingForFirstChar) { charOne = ch; lookingForFirstChar = false; } else { charTwo = ch; auto byte = hexPairToChar(charOne, charTwo); _bytes.push_back(byte); lookingForFirstChar = true; } } } // create empty guid Guid::Guid() : _bytes(16, 0) { } // copy constructor Guid::Guid(const Guid& other) : _bytes(other._bytes) { } // move constructor Guid::Guid(Guid&& other) : _bytes(std::move(other._bytes)) { } // overload assignment operator Guid& Guid::operator=(const Guid &other) { _bytes = other._bytes; return *this; } // overload move operator Guid& Guid::operator=(Guid&& other) { _bytes = std::move(other._bytes); return *this; } // overload equality operator bool Guid::operator==(const Guid& other) const { return _bytes == other._bytes; } // overload inequality operator bool Guid::operator!=(const Guid& other) const { return !operator==(other); } // converts GUID to std::string. std::string Guid::to_string() const { std::ostringstream stream; stream << *this; return stream.str(); } // This is the linux friendly implementation, but it could work on other // systems that have libuuid available #ifdef GUID_LIBUUID Guid GuidGenerator::newGuid() { uuid_t id; uuid_generate_time(id); return id; } #endif // This is the FreBSD version. #ifdef GUID_FREEBSD Guid GuidGenerator::newGuid() { uuid_t id; uint32_t status; uuid_create(&id, &status); if (status != uuid_s_ok) { // Can only be uuid_s_no_memory it seems. throw std::bad_alloc(); } unsigned char byteArray[16]; uuid_enc_be(byteArray, &id); return byteArray; } #endif // this is the mac and ios version #ifdef GUID_CFUUID Guid GuidGenerator::newGuid() { auto newId = CFUUIDCreate(nullptr); auto bytes = CFUUIDGetUUIDBytes(newId); CFRelease(newId); const unsigned char byteArray[16] = { bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, bytes.byte4, bytes.byte5, bytes.byte6, bytes.byte7, bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11, bytes.byte12, bytes.byte13, bytes.byte14, bytes.byte15 }; return byteArray; } #endif // obviously this is the windows version #ifdef GUID_WINDOWS Guid GuidGenerator::newGuid() { GUID newId; CoCreateGuid(&newId); const unsigned char bytes[16] = { (newId.Data1 >> 24) & 0xFF, (newId.Data1 >> 16) & 0xFF, (newId.Data1 >> 8) & 0xFF, (newId.Data1) & 0xff, (newId.Data2 >> 8) & 0xFF, (newId.Data2) & 0xff, (newId.Data3 >> 8) & 0xFF, (newId.Data3) & 0xFF, newId.Data4[0], newId.Data4[1], newId.Data4[2], newId.Data4[3], newId.Data4[4], newId.Data4[5], newId.Data4[6], newId.Data4[7] }; return bytes; } #endif // android version that uses a call to a java api #ifdef GUID_ANDROID GuidGenerator::GuidGenerator(JNIEnv *env) { _env = env; _uuidClass = env->FindClass("java/util/UUID"); _newGuidMethod = env->GetStaticMethodID(_uuidClass, "randomUUID", "()Ljava/util/UUID;"); _mostSignificantBitsMethod = env->GetMethodID(_uuidClass, "getMostSignificantBits", "()J"); _leastSignificantBitsMethod = env->GetMethodID(_uuidClass, "getLeastSignificantBits", "()J"); } Guid GuidGenerator::newGuid() { jobject javaUuid = _env->CallStaticObjectMethod(_uuidClass, _newGuidMethod); jlong mostSignificant = _env->CallLongMethod(javaUuid, _mostSignificantBitsMethod); jlong leastSignificant = _env->CallLongMethod(javaUuid, _leastSignificantBitsMethod); unsigned char bytes[16] = { (mostSignificant >> 56) & 0xFF, (mostSignificant >> 48) & 0xFF, (mostSignificant >> 40) & 0xFF, (mostSignificant >> 32) & 0xFF, (mostSignificant >> 24) & 0xFF, (mostSignificant >> 16) & 0xFF, (mostSignificant >> 8) & 0xFF, (mostSignificant) & 0xFF, (leastSignificant >> 56) & 0xFF, (leastSignificant >> 48) & 0xFF, (leastSignificant >> 40) & 0xFF, (leastSignificant >> 32) & 0xFF, (leastSignificant >> 24) & 0xFF, (leastSignificant >> 16) & 0xFF, (leastSignificant >> 8) & 0xFF, (leastSignificant) & 0xFF, }; return bytes; } #endif <commit_msg>Remove header<commit_after>/* The MIT License (MIT) Copyright (c): 2014 Graeme Hill (http://graemehill.ca) 2016 deipi.com LLC and contributors 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 "guid.h" #include <algorithm> #include <iomanip> #include "config.h" #ifdef GUID_LIBUUID #include <uuid/uuid.h> #endif #ifdef GUID_FREEBSD #include <uuid.h> #include <cstdint> #include <cstring> #endif #ifdef GUID_CFUUID #include <CoreFoundation/CFUUID.h> #endif #ifdef GUID_WINDOWS #include <objbase.h> #endif using namespace std; // overload << so that it's easy to convert to a string ostream& operator<<(ostream& s, const Guid& guid) { return s << hex << setfill('0') << setw(2) << (int)guid._bytes[0] << setw(2) << (int)guid._bytes[1] << setw(2) << (int)guid._bytes[2] << setw(2) << (int)guid._bytes[3] << "-" << setw(2) << (int)guid._bytes[4] << setw(2) << (int)guid._bytes[5] << "-" << setw(2) << (int)guid._bytes[6] << setw(2) << (int)guid._bytes[7] << "-" << setw(2) << (int)guid._bytes[8] << setw(2) << (int)guid._bytes[9] << "-" << setw(2) << (int)guid._bytes[10] << setw(2) << (int)guid._bytes[11] << setw(2) << (int)guid._bytes[12] << setw(2) << (int)guid._bytes[13] << setw(2) << (int)guid._bytes[14] << setw(2) << (int)guid._bytes[15]; } // create a guid from vector of bytes Guid::Guid(const vector<unsigned char>& bytes) : _bytes(bytes) { } // create a guid from array of bytes Guid::Guid(const unsigned char* bytes) : _bytes(bytes, bytes + 16) { } // converts a single hex char to a number (0 - 15) unsigned char hexDigitToChar(char ch) { if (ch > 47 && ch < 58) return ch - 48; if (ch > 96 && ch < 103) return ch - 87; if (ch > 64 && ch < 71) return ch - 55; return 0; } // converts the two hexadecimal characters to an unsigned char (a byte) unsigned char hexPairToChar(char a, char b) { return hexDigitToChar(a) * 16 + hexDigitToChar(b); } // create a guid from string Guid::Guid(const string& fromString) { char charOne, charTwo; bool lookingForFirstChar = true; _bytes.reserve(16); for (const char& ch : fromString) { if (ch == '-') continue; if (lookingForFirstChar) { charOne = ch; lookingForFirstChar = false; } else { charTwo = ch; auto byte = hexPairToChar(charOne, charTwo); _bytes.push_back(byte); lookingForFirstChar = true; } } } // create empty guid Guid::Guid() : _bytes(16, 0) { } // copy constructor Guid::Guid(const Guid& other) : _bytes(other._bytes) { } // move constructor Guid::Guid(Guid&& other) : _bytes(std::move(other._bytes)) { } // overload assignment operator Guid& Guid::operator=(const Guid &other) { _bytes = other._bytes; return *this; } // overload move operator Guid& Guid::operator=(Guid&& other) { _bytes = std::move(other._bytes); return *this; } // overload equality operator bool Guid::operator==(const Guid& other) const { return _bytes == other._bytes; } // overload inequality operator bool Guid::operator!=(const Guid& other) const { return !operator==(other); } // converts GUID to std::string. std::string Guid::to_string() const { std::ostringstream stream; stream << *this; return stream.str(); } // This is the linux friendly implementation, but it could work on other // systems that have libuuid available #ifdef GUID_LIBUUID Guid GuidGenerator::newGuid() { uuid_t id; uuid_generate_time(id); return id; } #endif // This is the FreBSD version. #ifdef GUID_FREEBSD Guid GuidGenerator::newGuid() { uuid_t id; uint32_t status; uuid_create(&id, &status); if (status != uuid_s_ok) { // Can only be uuid_s_no_memory it seems. throw std::bad_alloc(); } unsigned char byteArray[16]; uuid_enc_be(byteArray, &id); return byteArray; } #endif // this is the mac and ios version #ifdef GUID_CFUUID Guid GuidGenerator::newGuid() { auto newId = CFUUIDCreate(nullptr); auto bytes = CFUUIDGetUUIDBytes(newId); CFRelease(newId); const unsigned char byteArray[16] = { bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, bytes.byte4, bytes.byte5, bytes.byte6, bytes.byte7, bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11, bytes.byte12, bytes.byte13, bytes.byte14, bytes.byte15 }; return byteArray; } #endif // obviously this is the windows version #ifdef GUID_WINDOWS Guid GuidGenerator::newGuid() { GUID newId; CoCreateGuid(&newId); const unsigned char bytes[16] = { (newId.Data1 >> 24) & 0xFF, (newId.Data1 >> 16) & 0xFF, (newId.Data1 >> 8) & 0xFF, (newId.Data1) & 0xff, (newId.Data2 >> 8) & 0xFF, (newId.Data2) & 0xff, (newId.Data3 >> 8) & 0xFF, (newId.Data3) & 0xFF, newId.Data4[0], newId.Data4[1], newId.Data4[2], newId.Data4[3], newId.Data4[4], newId.Data4[5], newId.Data4[6], newId.Data4[7] }; return bytes; } #endif // android version that uses a call to a java api #ifdef GUID_ANDROID GuidGenerator::GuidGenerator(JNIEnv *env) { _env = env; _uuidClass = env->FindClass("java/util/UUID"); _newGuidMethod = env->GetStaticMethodID(_uuidClass, "randomUUID", "()Ljava/util/UUID;"); _mostSignificantBitsMethod = env->GetMethodID(_uuidClass, "getMostSignificantBits", "()J"); _leastSignificantBitsMethod = env->GetMethodID(_uuidClass, "getLeastSignificantBits", "()J"); } Guid GuidGenerator::newGuid() { jobject javaUuid = _env->CallStaticObjectMethod(_uuidClass, _newGuidMethod); jlong mostSignificant = _env->CallLongMethod(javaUuid, _mostSignificantBitsMethod); jlong leastSignificant = _env->CallLongMethod(javaUuid, _leastSignificantBitsMethod); unsigned char bytes[16] = { (mostSignificant >> 56) & 0xFF, (mostSignificant >> 48) & 0xFF, (mostSignificant >> 40) & 0xFF, (mostSignificant >> 32) & 0xFF, (mostSignificant >> 24) & 0xFF, (mostSignificant >> 16) & 0xFF, (mostSignificant >> 8) & 0xFF, (mostSignificant) & 0xFF, (leastSignificant >> 56) & 0xFF, (leastSignificant >> 48) & 0xFF, (leastSignificant >> 40) & 0xFF, (leastSignificant >> 32) & 0xFF, (leastSignificant >> 24) & 0xFF, (leastSignificant >> 16) & 0xFF, (leastSignificant >> 8) & 0xFF, (leastSignificant) & 0xFF, }; return bytes; } #endif <|endoftext|>
<commit_before>// hdf5_back.cc #include "hdf5_back.h" #include <cmath> #include <string.h> #include "blob.h" #define STR_SIZE 16 namespace cyclus { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Hdf5Back::Hdf5Back(std::string path) : path_(path) { file_ = H5Fcreate(path_.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); string_type_ = H5Tcopy(H5T_C_S1); H5Tset_size(string_type_, STR_SIZE); H5Tset_strpad(string_type_, H5T_STR_NULLPAD); blob_type_ = H5Tcopy(H5T_C_S1); H5Tset_size(blob_type_, H5T_VARIABLE); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::Notify(EventList evts) { std::map<std::string, EventList> groups; for (EventList::iterator it = evts.begin(); it != evts.end(); ++it) { std::string name = (*it)->title(); if (tbl_size_.count(name) == 0) { Event* ev = *it; CreateTable(ev); } groups[name].push_back(*it); } std::map<std::string, EventList>::iterator it; for (it = groups.begin(); it != groups.end(); ++it) { WriteGroup(it->second); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::Close() { H5Fclose(file_); H5Tclose(string_type_); H5Tclose(blob_type_); std::map<std::string, size_t*>::iterator it; for (it = tbl_offset_.begin(); it != tbl_offset_.end(); ++it) { delete[](it->second); } for (it = tbl_sizes_.begin(); it != tbl_sizes_.end(); ++it) { delete[](it->second); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string Hdf5Back::Name() { return path_; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::CreateTable(Event* ev) { Event::Vals vals = ev->vals(); size_t dst_size = 0; size_t* dst_offset = new size_t[vals.size()]; size_t* dst_sizes = new size_t[vals.size()]; hid_t field_types[vals.size()]; const char* field_names[vals.size()]; for (int i = 0; i < vals.size(); ++i) { dst_offset[i] = dst_size; field_names[i] = vals[i].first; if (vals[i].second.type() == typeid(int)) { field_types[i] = H5T_NATIVE_INT; dst_sizes[i] = sizeof(int); dst_size += sizeof(int); } else if (vals[i].second.type() == typeid(double)) { field_types[i] = H5T_NATIVE_DOUBLE; dst_sizes[i] = sizeof(double); dst_size += sizeof(double); } else if (vals[i].second.type() == typeid(std::string)) { field_types[i] = string_type_; dst_sizes[i] = STR_SIZE; dst_size += STR_SIZE; } else if (vals[i].second.type() == typeid(cyclus::Blob)) { field_types[i] = blob_type_; dst_sizes[i] = sizeof(char*); dst_size += sizeof(char*); } else if (vals[i].second.type() == typeid(boost::uuids::uuid)) { field_types[i] = string_type_; dst_sizes[i] = STR_SIZE; dst_size += STR_SIZE; } else if (vals[i].second.type() == typeid(float)) { field_types[i] = H5T_NATIVE_FLOAT; dst_sizes[i] = sizeof(float); dst_size += sizeof(float); } } herr_t status; const char* title = ev->title().c_str(); int compress = 0; int chunk_size = 50000; void* fill_data = NULL; void* data = NULL; status = H5TBmake_table(title, file_, title, vals.size(), 0, dst_size, field_names, dst_offset, field_types, chunk_size, fill_data, compress, data); // record everything for later tbl_offset_[ev->title()] = dst_offset; tbl_size_[ev->title()] = dst_size; tbl_sizes_[ev->title()] = dst_sizes; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::WriteGroup(EventList& group) { std::string title = group.front()->title(); herr_t status; size_t* offsets = tbl_offset_[title]; size_t* sizes = tbl_sizes_[title]; size_t rowsize = tbl_size_[title]; char* buf = new char[group.size() * rowsize]; FillBuf(buf, group, sizes, rowsize); status = H5TBappend_records(file_, title.c_str(), group.size(), rowsize, offsets, sizes, buf); delete[] buf; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::FillBuf(char* buf, EventList& group, size_t* sizes, size_t rowsize) { Event::Vals header = group.front()->vals(); int valtype[header.size()]; enum Type {STR, NUM, UUID, BLOB}; for (int col = 0; col < header.size(); ++col) { if (header[col].second.type() == typeid(std::string)) { valtype[col] = STR; } else if (header[col].second.type() == typeid(boost::uuids::uuid)) { valtype[col] = UUID; } else if (header[col].second.type() == typeid(cyclus::Blob)) { valtype[col] = BLOB; } else { valtype[col] = NUM; } } size_t offset = 0; const void* val; EventList::iterator it; for (it = group.begin(); it != group.end(); ++it) { for (int col = 0; col < header.size(); ++col) { const boost::spirit::hold_any* a = &((*it)->vals()[col].second); switch (valtype[col]) { case NUM: { val = a->castsmallvoid(); memcpy(buf + offset, val, sizes[col]); break; } case STR: { const std::string s = a->cast<std::string>(); size_t slen = std::min(s.size(), static_cast<size_t>(STR_SIZE)); memcpy(buf + offset, s.c_str(), slen); memset(buf + offset + slen, 0, STR_SIZE - slen); break; } case BLOB: { const char* data = a->cast<cyclus::Blob>().str().c_str(); memcpy(buf + offset, &data, sizes[col]); break; } case UUID: { boost::uuids::uuid uuid = a->cast<boost::uuids::uuid>(); memcpy(buf + offset, &uuid, STR_SIZE); break; } } offset += sizes[col]; } } } } // namespace cyclus <commit_msg>removed extraneous cyclus namespace from hdf_back impl<commit_after>// hdf5_back.cc #include "hdf5_back.h" #include <cmath> #include <string.h> #include "blob.h" #define STR_SIZE 16 namespace cyclus { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Hdf5Back::Hdf5Back(std::string path) : path_(path) { file_ = H5Fcreate(path_.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); string_type_ = H5Tcopy(H5T_C_S1); H5Tset_size(string_type_, STR_SIZE); H5Tset_strpad(string_type_, H5T_STR_NULLPAD); blob_type_ = H5Tcopy(H5T_C_S1); H5Tset_size(blob_type_, H5T_VARIABLE); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::Notify(EventList evts) { std::map<std::string, EventList> groups; for (EventList::iterator it = evts.begin(); it != evts.end(); ++it) { std::string name = (*it)->title(); if (tbl_size_.count(name) == 0) { Event* ev = *it; CreateTable(ev); } groups[name].push_back(*it); } std::map<std::string, EventList>::iterator it; for (it = groups.begin(); it != groups.end(); ++it) { WriteGroup(it->second); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::Close() { H5Fclose(file_); H5Tclose(string_type_); H5Tclose(blob_type_); std::map<std::string, size_t*>::iterator it; for (it = tbl_offset_.begin(); it != tbl_offset_.end(); ++it) { delete[](it->second); } for (it = tbl_sizes_.begin(); it != tbl_sizes_.end(); ++it) { delete[](it->second); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string Hdf5Back::Name() { return path_; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::CreateTable(Event* ev) { Event::Vals vals = ev->vals(); size_t dst_size = 0; size_t* dst_offset = new size_t[vals.size()]; size_t* dst_sizes = new size_t[vals.size()]; hid_t field_types[vals.size()]; const char* field_names[vals.size()]; for (int i = 0; i < vals.size(); ++i) { dst_offset[i] = dst_size; field_names[i] = vals[i].first; if (vals[i].second.type() == typeid(int)) { field_types[i] = H5T_NATIVE_INT; dst_sizes[i] = sizeof(int); dst_size += sizeof(int); } else if (vals[i].second.type() == typeid(double)) { field_types[i] = H5T_NATIVE_DOUBLE; dst_sizes[i] = sizeof(double); dst_size += sizeof(double); } else if (vals[i].second.type() == typeid(std::string)) { field_types[i] = string_type_; dst_sizes[i] = STR_SIZE; dst_size += STR_SIZE; } else if (vals[i].second.type() == typeid(Blob)) { field_types[i] = blob_type_; dst_sizes[i] = sizeof(char*); dst_size += sizeof(char*); } else if (vals[i].second.type() == typeid(boost::uuids::uuid)) { field_types[i] = string_type_; dst_sizes[i] = STR_SIZE; dst_size += STR_SIZE; } else if (vals[i].second.type() == typeid(float)) { field_types[i] = H5T_NATIVE_FLOAT; dst_sizes[i] = sizeof(float); dst_size += sizeof(float); } } herr_t status; const char* title = ev->title().c_str(); int compress = 0; int chunk_size = 50000; void* fill_data = NULL; void* data = NULL; status = H5TBmake_table(title, file_, title, vals.size(), 0, dst_size, field_names, dst_offset, field_types, chunk_size, fill_data, compress, data); // record everything for later tbl_offset_[ev->title()] = dst_offset; tbl_size_[ev->title()] = dst_size; tbl_sizes_[ev->title()] = dst_sizes; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::WriteGroup(EventList& group) { std::string title = group.front()->title(); herr_t status; size_t* offsets = tbl_offset_[title]; size_t* sizes = tbl_sizes_[title]; size_t rowsize = tbl_size_[title]; char* buf = new char[group.size() * rowsize]; FillBuf(buf, group, sizes, rowsize); status = H5TBappend_records(file_, title.c_str(), group.size(), rowsize, offsets, sizes, buf); delete[] buf; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Hdf5Back::FillBuf(char* buf, EventList& group, size_t* sizes, size_t rowsize) { Event::Vals header = group.front()->vals(); int valtype[header.size()]; enum Type {STR, NUM, UUID, BLOB}; for (int col = 0; col < header.size(); ++col) { if (header[col].second.type() == typeid(std::string)) { valtype[col] = STR; } else if (header[col].second.type() == typeid(boost::uuids::uuid)) { valtype[col] = UUID; } else if (header[col].second.type() == typeid(Blob)) { valtype[col] = BLOB; } else { valtype[col] = NUM; } } size_t offset = 0; const void* val; EventList::iterator it; for (it = group.begin(); it != group.end(); ++it) { for (int col = 0; col < header.size(); ++col) { const boost::spirit::hold_any* a = &((*it)->vals()[col].second); switch (valtype[col]) { case NUM: { val = a->castsmallvoid(); memcpy(buf + offset, val, sizes[col]); break; } case STR: { const std::string s = a->cast<std::string>(); size_t slen = std::min(s.size(), static_cast<size_t>(STR_SIZE)); memcpy(buf + offset, s.c_str(), slen); memset(buf + offset + slen, 0, STR_SIZE - slen); break; } case BLOB: { const char* data = a->cast<Blob>().str().c_str(); memcpy(buf + offset, &data, sizes[col]); break; } case UUID: { boost::uuids::uuid uuid = a->cast<boost::uuids::uuid>(); memcpy(buf + offset, &uuid, STR_SIZE); break; } } offset += sizes[col]; } } } } // namespace cyclus <|endoftext|>
<commit_before>#include "ctvm.h" BoostDoubleMatrix tval3_reconstruction(BoostDoubleMatrix Sinogram, BoostDoubleVector TiltAngles){ /* Function: tval3_reconstruction ------------------------------ Perform two-dimensional TVAL3 tomographic reconstruction given a set of measurements (Sinogram) and the measured tilt angles. */ /* <TODO: Everything!> */ unsigned double l = Sinogram.size1(); /* Size of the sample (in pixels) */ unsigned double o = Sinogram.size2(); /* Numbers of tilt angles */ unsigned double m = l * o; /* Numbers of measurements */ unsigned double n = l * l; unsigned double nu = 1; unsigned double lambda = 1; unsigned double beta = 1; unsigned double mu = 1; unsigned double unsigned double Lagrangian; // ? float alpha = 1.05; float tol = 0.5; float delta, rho, eta; BoostDoubleMatrix W (rows, cols); // w(i)? BoostDoubleMatrix A (m, n); BoostDoubleVector Y (m); BoostDoubleVector X (n); BoostDoubleVector NU (); // size ? A = CreateRandomMatrix(m, n); Y = MatrixToVector(Sinogram); // u(i) ? do{ for (unsigned int k = 0; k < m; ++k){ w = w(k+1); u = u(k+1); for (unsigned int i = 0; i < m; ++i){ L(w,u) = L(w(k),u(k)) + [norm_1(w(i)) - transpose(nu(i)) * (D*u - w(i)) + beta/2 * norm_2(D*u - w(i))] - [transpose(lambda) * (A*u - Y) + mu/2 * norm_2(A*u - Y)]; } } } while (Lagrangian > tol) BoostDoubleMatrix RecoveredImage(32,32); // Create a dummy matrix to return return RecoveredImage; }<commit_msg>ctvm v1.2<commit_after>#include "ctvm.h" BoostDoubleMatrix tval3_reconstruction(BoostDoubleMatrix Sinogram, BoostDoubleVector TiltAngles) { /* Function: tval3_reconstruction ------------------------------ Perform two-dimensional TVAL3 tomographic reconstruction given a set of measurements (Sinogram) and the measured tilt angles. */ /* <TODO: Everything!> */ unsigned double l = Sinogram.size1(); /* Size of the sample (in pixels) */ unsigned double o = Sinogram.size2(); /* Numbers of tilt angles */ unsigned double m = l * o; /* Numbers of measurements */ unsigned double n = l * l; unsigned double nu = 1; unsigned double lambda = 1; unsigned double beta = 1; unsigned double mu = 1; unsigned double alpha = unsigned double Lagrangian; // ? float alpha = 1.05; float innerstop, outerstop; float innertol = 0.5, outertol = 0.5, tol = 0.5; // multiple tol float delta, rho, eta; BoostDoubleMatrix W (N, 2); // w(i) = 0 for all i BoostDoubleMatrix NU (N, 2); BoostDoubleMatrix A (m, n); BoostDoubleVector Y (m); BoostDoubleVector X (n); A = CreateRandomMatrix(m, n); Y = MatrixToVector(Sinogram); // u(0) ? for (unsigned int i = 0; i < 2*n; ++i) { do /********************************** TVAL3 SCHEME **********************************/ { for (unsigned int k = 0; k < m; ++k) { w(k+1) = w(k);3 u(k+1) = u(k); for (unsigned int j = 0; j < m; ++j) { delta = 0.5; rho = 0.5; eta = 0.5; w(0) = // ? u(0) = // ? do /****************** ALTERNATING MINIMISATION SCHEME ******************/ { do /* "w sub-problem" */ { alpha(j) = rho * alpha(j); } while (/*(2.33)*/); // ... /* "u sub-problem" */ innerstop = norm_2(u(j+1) - u(j)); } while (innerstop > tol); } // Lagrangian ? // L(w(k+1),u(k+1)) = L(w(k),u(k)) + [norm_1(w(i)) - transpose(nu(i)) * (D*u - w(i)) + beta/2 * norm_2(D*u - w(i))] - [transpose(lambda) * (A*u - Y) + mu/2 * norm_2(A*u - Y)]; } outerstop = norm_2(u(k+1) - u(k)); } while (outerstop > tol); } BoostDoubleMatrix RecoveredImage(32,32); // Create a dummy matrix to return return RecoveredImage; } DoubleBoostVector Gradient2D(DoubleBoostVector U, unsigned double pixel) // pixel = actual pixel number -1 ?? { unsigned double n = U.size (); unsigned double l = sqrt(n); unsigned double rows = 0; unsigned double cols = 0; float q = 0; DoubleBoostVector Di (2); DoubleBoostMatrix X (l, l); X = VectorToMatrix(U, l, l); for (unsigned double i = 0; i < l; ++i) { if (!pixel) { rows = i; cols = 0; break; } else { for (unsigned double j = 0; j < l; ++j) { q = j / pixel; if (q) { rows = i; cols = j; break; } } pixel = pixel - l; } return Di; }<|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the OpenQube project. Copyright 2008-2010 Marcus D. Hanwell This source code is released under the New BSD License, (the "License"). 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 "cube.h" #include <QtCore/QReadWriteLock> #include <QtCore/QDebug> namespace openqube { using Eigen::Vector3i; using Eigen::Vector3f; using Eigen::Vector3d; Cube::Cube() : m_data(0), m_min(0.0, 0.0, 0.0), m_max(0.0, 0.0, 0.0), m_spacing(0.0, 0.0, 0.0), m_points(0, 0, 0), m_minValue(0.0), m_maxValue(0.0), m_lock(new QReadWriteLock) { } Cube::~Cube() { delete m_lock; m_lock = 0; } bool Cube::setLimits(const Vector3d &min, const Vector3d &max, const Vector3i &points) { // We can calculate all necessary properties and initialise our data Vector3d delta = max - min; m_spacing = Vector3d(delta.x() / (points.x()-1), delta.y() / (points.y()-1), delta.z() / (points.z()-1)); m_min = min; m_max = max; m_points = points; m_data.resize(m_points.x() * m_points.y() * m_points.z()); return true; } bool Cube::setLimits(const Vector3d &min, const Vector3d &max, double spacing) { Vector3i points; Vector3d delta = max - min; delta = delta / spacing; points = Vector3i(delta.x(), delta.y(), delta.z()); return setLimits(min, max, points); } bool Cube::setLimits(const Vector3d &min, const Vector3i &dim, double spacing) { Vector3d max = Vector3d(min.x() + (dim.x()-1) * spacing, min.y() + (dim.y()-1) * spacing, min.z() + (dim.z()-1) * spacing); m_min = min; m_max = max; m_points = dim; m_spacing = Vector3d(spacing, spacing, spacing); m_data.resize(m_points.x() * m_points.y() * m_points.z()); return true; } bool Cube::setLimits(const Cube &cube) { m_min = cube.m_min; m_max = cube.m_max; m_points = cube.m_points; m_spacing = cube.m_spacing; m_data.resize(m_points.x() * m_points.y() * m_points.z()); return true; } std::vector<double> * Cube::data() { return &m_data; } bool Cube::setData(const std::vector<double> &values) { if (!values.size()) { qDebug() << "Zero sized vector passed to Cube::setData. Nothing to do."; return false; } if (static_cast<int>(values.size()) == m_points.x() * m_points.y() * m_points.z()) { m_data = values; qDebug() << "Loaded in cube data" << m_data.size(); // Now to update the minimum and maximum values m_minValue = m_maxValue = m_data[0]; foreach(double val, m_data) { if (val < m_minValue) m_minValue = val; else if (val > m_maxValue) m_maxValue = val; } return true; } else { qDebug() << "The vector passed to Cube::setData does not have the correct" << "size. Expected" << m_points.x() * m_points.y() * m_points.z() << "got" << values.size(); return false; } } bool Cube::addData(const std::vector<double> &values) { // Initialise the cube to zero if necessary if (!m_data.size()) { m_data.resize(m_points.x() * m_points.y() * m_points.z()); } if (values.size() != m_data.size() || !values.size()) { qDebug() << "Attempted to add values to cube - sizes do not match..."; return false; } for (unsigned int i = 0; i < m_data.size(); i++) { m_data[i] += values[i]; if (m_data[i] < m_minValue) m_minValue = m_data[i]; else if (m_data[i] > m_maxValue) m_maxValue = m_data[i]; } return true; } unsigned int Cube::closestIndex(const Vector3d &pos) const { int i, j, k; // Calculate how many steps each coordinate is along its axis i = int((pos.x() - m_min.x()) / m_spacing.x()); j = int((pos.y() - m_min.y()) / m_spacing.y()); k = int((pos.z() - m_min.z()) / m_spacing.z()); return i*m_points.y()*m_points.z() + j*m_points.z() + k; } Vector3i Cube::indexVector(const Vector3d &pos) const { // Calculate how many steps each coordinate is along its axis int i, j, k; i = int((pos.x() - m_min.x()) / m_spacing.x()); j = int((pos.y() - m_min.y()) / m_spacing.y()); k = int((pos.z() - m_min.z()) / m_spacing.z()); return Vector3i(i, j, k); } Vector3d Cube::position(unsigned int index) const { int x, y, z; x = int(index / (m_points.y()*m_points.z())); y = int((index - (x*m_points.y()*m_points.z())) / m_points.z()); z = index % m_points.z(); return Vector3d(x * m_spacing.x() + m_min.x(), y * m_spacing.y() + m_min.y(), z * m_spacing.z() + m_min.z()); } double Cube::value(int i, int j, int k) const { unsigned int index = i*m_points.y()*m_points.z() + j*m_points.z() + k; if (index < m_data.size()) return m_data.at(index); else { // qDebug() << "Attempt to identify out of range index" << index << m_data.size(); return 0.0; } } double Cube::value(const Vector3i &pos) const { unsigned int index = pos.x()*m_points.y()*m_points.z() + pos.y()*m_points.z() + pos.z(); if (index < m_data.size()) return m_data.at(index); else { qDebug() << "Attempted to access an index out of range."; return 6969.0; } } float Cube::valuef(const Vector3f &pos) const { // This is a really expensive operation and so should be avoided // Interpolate the value at the supplied vector - trilinear interpolation... Vector3f delta = pos - m_min.cast<float>(); // Find the integer low and high corners Vector3i lC(delta.x() / m_spacing.x(), delta.y() / m_spacing.y(), delta.z() / m_spacing.z()); Vector3i hC(lC.x() + 1, lC.y() + 1, lC.z() + 1); // So there are six corners in total - work out the delta of the position // and the low corner Vector3f P((delta.x() - lC.x()*m_spacing.x()) / m_spacing.x(), (delta.y() - lC.y()*m_spacing.y()) / m_spacing.y(), (delta.z() - lC.z()*m_spacing.z()) / m_spacing.z()); Vector3f dP = Vector3f(1.0, 1.0, 1.0) - P; // Now calculate and return the interpolated value return value(lC.x(), lC.y(), lC.z()) * dP.x() * dP.y() * dP.z() + value(hC.x(), lC.y(), lC.z()) * P.x() * dP.y() * dP.z() + value(lC.x(), hC.y(), lC.z()) * dP.x() * P.y() * dP.z() + value(lC.x(), lC.y(), hC.z()) * dP.x() * dP.y() * P.z() + value(hC.x(), lC.y(), hC.z()) * P.x() * dP.y() * P.z() + value(lC.x(), hC.y(), hC.z()) * dP.x() * P.y() * P.z() + value(hC.x(), hC.y(), lC.z()) * P.x() * P.y() * dP.z() + value(hC.x(), hC.y(), hC.z()) * P.x() * P.y() * P.z(); } double Cube::value(const Vector3d &pos) const { // This is a really expensive operation and so should be avoided // Interpolate the value at the supplied vector - trilinear interpolation... Vector3d delta = pos - m_min; // Find the integer low and high corners Vector3i lC(delta.x() / m_spacing.x(), delta.y() / m_spacing.y(), delta.z() / m_spacing.z()); Vector3i hC(lC.x() + 1, lC.y() + 1, lC.z() + 1); // So there are six corners in total - work out the delta of the position // and the low corner Vector3d P((delta.x() - lC.x()*m_spacing.x()) / m_spacing.x(), (delta.y() - lC.y()*m_spacing.y()) / m_spacing.y(), (delta.z() - lC.z()*m_spacing.z()) / m_spacing.z()); Vector3d dP = Vector3d(1.0, 1.0, 1.0) - P; // Now calculate and return the interpolated value return value(lC.x(), lC.y(), lC.z()) * dP.x() * dP.y() * dP.z() + value(hC.x(), lC.y(), lC.z()) * P.x() * dP.y() * dP.z() + value(lC.x(), hC.y(), lC.z()) * dP.x() * P.y() * dP.z() + value(lC.x(), lC.y(), hC.z()) * dP.x() * dP.y() * P.z() + value(hC.x(), lC.y(), hC.z()) * P.x() * dP.y() * P.z() + value(lC.x(), hC.y(), hC.z()) * dP.x() * P.y() * P.z() + value(hC.x(), hC.y(), lC.z()) * P.x() * P.y() * dP.z() + value(hC.x(), hC.y(), hC.z()) * P.x() * P.y() * P.z(); } bool Cube::setValue(int i, int j, int k, double value) { unsigned int index = i*m_points.y()*m_points.z() + j*m_points.z() + k; if (index < m_data.size()) { m_data[index] = value; return true; } else return false; } QReadWriteLock * Cube::lock() const { return m_lock; } } // End namespace <commit_msg>Don't do bounds checking twice.<commit_after>/****************************************************************************** This source file is part of the OpenQube project. Copyright 2008-2010 Marcus D. Hanwell This source code is released under the New BSD License, (the "License"). 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 "cube.h" #include <QtCore/QReadWriteLock> #include <QtCore/QDebug> namespace openqube { using Eigen::Vector3i; using Eigen::Vector3f; using Eigen::Vector3d; Cube::Cube() : m_data(0), m_min(0.0, 0.0, 0.0), m_max(0.0, 0.0, 0.0), m_spacing(0.0, 0.0, 0.0), m_points(0, 0, 0), m_minValue(0.0), m_maxValue(0.0), m_lock(new QReadWriteLock) { } Cube::~Cube() { delete m_lock; m_lock = 0; } bool Cube::setLimits(const Vector3d &min, const Vector3d &max, const Vector3i &points) { // We can calculate all necessary properties and initialise our data Vector3d delta = max - min; m_spacing = Vector3d(delta.x() / (points.x()-1), delta.y() / (points.y()-1), delta.z() / (points.z()-1)); m_min = min; m_max = max; m_points = points; m_data.resize(m_points.x() * m_points.y() * m_points.z()); return true; } bool Cube::setLimits(const Vector3d &min, const Vector3d &max, double spacing) { Vector3i points; Vector3d delta = max - min; delta = delta / spacing; points = Vector3i(delta.x(), delta.y(), delta.z()); return setLimits(min, max, points); } bool Cube::setLimits(const Vector3d &min, const Vector3i &dim, double spacing) { Vector3d max = Vector3d(min.x() + (dim.x()-1) * spacing, min.y() + (dim.y()-1) * spacing, min.z() + (dim.z()-1) * spacing); m_min = min; m_max = max; m_points = dim; m_spacing = Vector3d(spacing, spacing, spacing); m_data.resize(m_points.x() * m_points.y() * m_points.z()); return true; } bool Cube::setLimits(const Cube &cube) { m_min = cube.m_min; m_max = cube.m_max; m_points = cube.m_points; m_spacing = cube.m_spacing; m_data.resize(m_points.x() * m_points.y() * m_points.z()); return true; } std::vector<double> * Cube::data() { return &m_data; } bool Cube::setData(const std::vector<double> &values) { if (!values.size()) { qDebug() << "Zero sized vector passed to Cube::setData. Nothing to do."; return false; } if (static_cast<int>(values.size()) == m_points.x() * m_points.y() * m_points.z()) { m_data = values; qDebug() << "Loaded in cube data" << m_data.size(); // Now to update the minimum and maximum values m_minValue = m_maxValue = m_data[0]; foreach(double val, m_data) { if (val < m_minValue) m_minValue = val; else if (val > m_maxValue) m_maxValue = val; } return true; } else { qDebug() << "The vector passed to Cube::setData does not have the correct" << "size. Expected" << m_points.x() * m_points.y() * m_points.z() << "got" << values.size(); return false; } } bool Cube::addData(const std::vector<double> &values) { // Initialise the cube to zero if necessary if (!m_data.size()) { m_data.resize(m_points.x() * m_points.y() * m_points.z()); } if (values.size() != m_data.size() || !values.size()) { qDebug() << "Attempted to add values to cube - sizes do not match..."; return false; } for (unsigned int i = 0; i < m_data.size(); i++) { m_data[i] += values[i]; if (m_data[i] < m_minValue) m_minValue = m_data[i]; else if (m_data[i] > m_maxValue) m_maxValue = m_data[i]; } return true; } unsigned int Cube::closestIndex(const Vector3d &pos) const { int i, j, k; // Calculate how many steps each coordinate is along its axis i = int((pos.x() - m_min.x()) / m_spacing.x()); j = int((pos.y() - m_min.y()) / m_spacing.y()); k = int((pos.z() - m_min.z()) / m_spacing.z()); return i*m_points.y()*m_points.z() + j*m_points.z() + k; } Vector3i Cube::indexVector(const Vector3d &pos) const { // Calculate how many steps each coordinate is along its axis int i, j, k; i = int((pos.x() - m_min.x()) / m_spacing.x()); j = int((pos.y() - m_min.y()) / m_spacing.y()); k = int((pos.z() - m_min.z()) / m_spacing.z()); return Vector3i(i, j, k); } Vector3d Cube::position(unsigned int index) const { int x, y, z; x = int(index / (m_points.y()*m_points.z())); y = int((index - (x*m_points.y()*m_points.z())) / m_points.z()); z = index % m_points.z(); return Vector3d(x * m_spacing.x() + m_min.x(), y * m_spacing.y() + m_min.y(), z * m_spacing.z() + m_min.z()); } double Cube::value(int i, int j, int k) const { unsigned int index = i*m_points.y()*m_points.z() + j*m_points.z() + k; if (index < m_data.size()) return m_data[index]; else { // qDebug() << "Attempt to identify out of range index" << index << m_data.size(); return 0.0; } } double Cube::value(const Vector3i &pos) const { unsigned int index = pos.x()*m_points.y()*m_points.z() + pos.y()*m_points.z() + pos.z(); if (index < m_data.size()) return m_data[index]; else { qDebug() << "Attempted to access an index out of range."; return 6969.0; } } float Cube::valuef(const Vector3f &pos) const { // This is a really expensive operation and so should be avoided // Interpolate the value at the supplied vector - trilinear interpolation... Vector3f delta = pos - m_min.cast<float>(); // Find the integer low and high corners Vector3i lC(delta.x() / m_spacing.x(), delta.y() / m_spacing.y(), delta.z() / m_spacing.z()); Vector3i hC(lC.x() + 1, lC.y() + 1, lC.z() + 1); // So there are six corners in total - work out the delta of the position // and the low corner Vector3f P((delta.x() - lC.x()*m_spacing.x()) / m_spacing.x(), (delta.y() - lC.y()*m_spacing.y()) / m_spacing.y(), (delta.z() - lC.z()*m_spacing.z()) / m_spacing.z()); Vector3f dP = Vector3f(1.0, 1.0, 1.0) - P; // Now calculate and return the interpolated value return value(lC.x(), lC.y(), lC.z()) * dP.x() * dP.y() * dP.z() + value(hC.x(), lC.y(), lC.z()) * P.x() * dP.y() * dP.z() + value(lC.x(), hC.y(), lC.z()) * dP.x() * P.y() * dP.z() + value(lC.x(), lC.y(), hC.z()) * dP.x() * dP.y() * P.z() + value(hC.x(), lC.y(), hC.z()) * P.x() * dP.y() * P.z() + value(lC.x(), hC.y(), hC.z()) * dP.x() * P.y() * P.z() + value(hC.x(), hC.y(), lC.z()) * P.x() * P.y() * dP.z() + value(hC.x(), hC.y(), hC.z()) * P.x() * P.y() * P.z(); } double Cube::value(const Vector3d &pos) const { // This is a really expensive operation and so should be avoided // Interpolate the value at the supplied vector - trilinear interpolation... Vector3d delta = pos - m_min; // Find the integer low and high corners Vector3i lC(delta.x() / m_spacing.x(), delta.y() / m_spacing.y(), delta.z() / m_spacing.z()); Vector3i hC(lC.x() + 1, lC.y() + 1, lC.z() + 1); // So there are six corners in total - work out the delta of the position // and the low corner Vector3d P((delta.x() - lC.x()*m_spacing.x()) / m_spacing.x(), (delta.y() - lC.y()*m_spacing.y()) / m_spacing.y(), (delta.z() - lC.z()*m_spacing.z()) / m_spacing.z()); Vector3d dP = Vector3d(1.0, 1.0, 1.0) - P; // Now calculate and return the interpolated value return value(lC.x(), lC.y(), lC.z()) * dP.x() * dP.y() * dP.z() + value(hC.x(), lC.y(), lC.z()) * P.x() * dP.y() * dP.z() + value(lC.x(), hC.y(), lC.z()) * dP.x() * P.y() * dP.z() + value(lC.x(), lC.y(), hC.z()) * dP.x() * dP.y() * P.z() + value(hC.x(), lC.y(), hC.z()) * P.x() * dP.y() * P.z() + value(lC.x(), hC.y(), hC.z()) * dP.x() * P.y() * P.z() + value(hC.x(), hC.y(), lC.z()) * P.x() * P.y() * dP.z() + value(hC.x(), hC.y(), hC.z()) * P.x() * P.y() * P.z(); } bool Cube::setValue(int i, int j, int k, double value) { unsigned int index = i*m_points.y()*m_points.z() + j*m_points.z() + k; if (index < m_data.size()) { m_data[index] = value; return true; } else return false; } QReadWriteLock * Cube::lock() const { return m_lock; } } // End namespace <|endoftext|>
<commit_before>#include "stdafx.h" #include "bbudf.h" #include "curl.h" #include "logger.h" namespace curl { //TODO http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION __thread CURL* ch=NULL; __thread long curl_response_code=0; int curl_global_init_called=0; size_t readfunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ unsigned short length,actual_length; length=size*nmemb; blobcallback* blob=(blobcallback*) userdata; int res; res=blob->blob_get_segment(blob->blob_handle,(ISC_UCHAR*)ptr,length,&actual_length); logger::syslog(0, "xmlreader::readfunction_blob() len=%d,res=%d,actual_length=%d",length,res,actual_length); return actual_length; } size_t writefunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ size_t length=size*nmemb; if(length>0){ blobcallback* outblob=(blobcallback*) userdata; outblob->blob_put_segment(outblob->blob_handle, (ISC_UCHAR*) ptr, length); } return length; } } FBUDF_API void fn_curl_exec(const char* method,const char* url, const char* sslcert, const char* sslcertpassword,const char* cainfo, const char* headers, blobcallback* datablob, const char* cookies, blobcallback* outblob) { curl::curl_response_code=0; if (!outblob || !outblob->blob_handle){ return; } CURLcode code; if(!curl::curl_global_init_called) { code=curl_global_init(CURL_GLOBAL_ALL); if(code != CURLE_OK){ logger::blobprinf(outblob,"curl_global_init() failed: %s\n",curl_easy_strerror(code)); return; } curl::curl_global_init_called=1; } CURL* ch; if(curl::ch==NULL){ curl::ch=curl_easy_init(); if(!curl::ch){ logger::blobprinf(outblob,"curl_easy_init() failed\n"); return; } }else{ curl_easy_reset(curl::ch); } ch=curl::ch; curl_easy_setopt(ch,CURLOPT_NOSIGNAL,1); if (strcmp(method,"GET")==0){ curl_easy_setopt(ch,CURLOPT_HTTPGET,1); }else if (strcmp(method,"POST")==0){ curl_easy_setopt(ch,CURLOPT_POST,1); }else if (strcmp(method,"PUT")==0){ curl_easy_setopt(ch,CURLOPT_PUT,1); }else if (strcmp(method,"HEAD")==0){ curl_easy_setopt(ch,CURLOPT_NOBODY,1); }else{ logger::blobprinf(outblob,"unknown method '%s'",method); return; } curl_easy_setopt(ch,CURLOPT_URL,url); curl_easy_setopt(ch,CURLOPT_SSLCERT,sslcert); curl_easy_setopt(ch,CURLOPT_SSLCERTPASSWD,sslcertpassword); curl_easy_setopt(ch,CURLOPT_CAINFO,cainfo); curl_easy_setopt(ch,CURLOPT_WRITEFUNCTION,curl::writefunction_blob); curl_easy_setopt(ch,CURLOPT_WRITEDATA,outblob); struct curl_slist *slist=NULL; if(headers){ #if defined(WIN32) #else char *saveptr; char *headersdup=strdup(headers); char *token=strtok_r(headersdup, "\n", &saveptr); while(token){ slist = curl_slist_append(slist, token); token=strtok_r(NULL, "\n", &saveptr); } free(headersdup); #endif } curl_easy_setopt(ch, CURLOPT_HTTPHEADER, slist); curl_easy_setopt(ch, CURLOPT_COOKIE, cookies); if(datablob && datablob->blob_handle){ //logger::syslog(0, "setup readfunction_blob(), data length=%d",datablob->blob_total_length); curl_easy_setopt(ch,CURLOPT_READFUNCTION,curl::readfunction_blob); curl_easy_setopt(ch,CURLOPT_READDATA,datablob); if (strcmp(method,"PUT")==0) { curl_easy_setopt(ch,CURLOPT_INFILESIZE,datablob->blob_total_length); }else{ curl_easy_setopt(ch,CURLOPT_POSTFIELDSIZE,datablob->blob_total_length); } } code=curl_easy_perform(ch); if(slist){ curl_slist_free_all(slist); } if(code != CURLE_OK){ logger::blobprinf(outblob,"curl_easy_perform() failed: %s\nsslcert=%s\nsslcertpassword=(%d chars)\ncainfo=%s",curl_easy_strerror(code),sslcert,strlen(sslcertpassword),cainfo); return; } curl_easy_getinfo(ch, CURLINFO_RESPONSE_CODE, &curl::curl_response_code); } FBUDF_API long fn_curl_get_response_code() { return curl::curl_response_code; }<commit_msg>curl_easy_perform() failed: Problem with the local SSL certificate diagonstic message<commit_after>#include "stdafx.h" #include "bbudf.h" #include "curl.h" #include "logger.h" namespace curl { //TODO http://www.openssl.org/docs/crypto/threads.html#DESCRIPTION __thread CURL* ch=NULL; __thread long curl_response_code=0; int curl_global_init_called=0; size_t readfunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ unsigned short length,actual_length; length=size*nmemb; blobcallback* blob=(blobcallback*) userdata; int res; res=blob->blob_get_segment(blob->blob_handle,(ISC_UCHAR*)ptr,length,&actual_length); logger::syslog(0, "xmlreader::readfunction_blob() len=%d,res=%d,actual_length=%d",length,res,actual_length); return actual_length; } size_t writefunction_blob( char *ptr, size_t size, size_t nmemb, void *userdata){ size_t length=size*nmemb; if(length>0){ blobcallback* outblob=(blobcallback*) userdata; outblob->blob_put_segment(outblob->blob_handle, (ISC_UCHAR*) ptr, length); } return length; } } FBUDF_API void fn_curl_exec(const char* method,const char* url, const char* sslcert, const char* sslcertpassword,const char* cainfo, const char* headers, blobcallback* datablob, const char* cookies, blobcallback* outblob) { curl::curl_response_code=0; if (!outblob || !outblob->blob_handle){ return; } CURLcode code; if(!curl::curl_global_init_called) { code=curl_global_init(CURL_GLOBAL_ALL); if(code != CURLE_OK){ logger::blobprinf(outblob,"curl_global_init() failed: %s\n",curl_easy_strerror(code)); return; } curl::curl_global_init_called=1; } CURL* ch; if(curl::ch==NULL){ curl::ch=curl_easy_init(); if(!curl::ch){ logger::blobprinf(outblob,"curl_easy_init() failed\n"); return; } }else{ curl_easy_reset(curl::ch); } ch=curl::ch; curl_easy_setopt(ch,CURLOPT_NOSIGNAL,1); if (strcmp(method,"GET")==0){ curl_easy_setopt(ch,CURLOPT_HTTPGET,1); }else if (strcmp(method,"POST")==0){ curl_easy_setopt(ch,CURLOPT_POST,1); }else if (strcmp(method,"PUT")==0){ curl_easy_setopt(ch,CURLOPT_PUT,1); }else if (strcmp(method,"HEAD")==0){ curl_easy_setopt(ch,CURLOPT_NOBODY,1); }else{ logger::blobprinf(outblob,"unknown method '%s'",method); return; } curl_easy_setopt(ch,CURLOPT_URL,url); curl_easy_setopt(ch,CURLOPT_SSLCERT,sslcert); curl_easy_setopt(ch,CURLOPT_SSLCERTPASSWD,sslcertpassword); curl_easy_setopt(ch,CURLOPT_CAINFO,cainfo); curl_easy_setopt(ch,CURLOPT_WRITEFUNCTION,curl::writefunction_blob); curl_easy_setopt(ch,CURLOPT_WRITEDATA,outblob); struct curl_slist *slist=NULL; if(headers){ #if defined(WIN32) #else char *saveptr; char *headersdup=strdup(headers); char *token=strtok_r(headersdup, "\n", &saveptr); while(token){ slist = curl_slist_append(slist, token); token=strtok_r(NULL, "\n", &saveptr); } free(headersdup); #endif } curl_easy_setopt(ch, CURLOPT_HTTPHEADER, slist); curl_easy_setopt(ch, CURLOPT_COOKIE, cookies); if(datablob && datablob->blob_handle){ //logger::syslog(0, "setup readfunction_blob(), data length=%d",datablob->blob_total_length); curl_easy_setopt(ch,CURLOPT_READFUNCTION,curl::readfunction_blob); curl_easy_setopt(ch,CURLOPT_READDATA,datablob); if (strcmp(method,"PUT")==0) { curl_easy_setopt(ch,CURLOPT_INFILESIZE,datablob->blob_total_length); }else{ curl_easy_setopt(ch,CURLOPT_POSTFIELDSIZE,datablob->blob_total_length); } } code=curl_easy_perform(ch); if(slist){ curl_slist_free_all(slist); } if(code != CURLE_OK){ logger::syslog(1,"curl_easy_perform() failed: %s\nsslcert=%s\nsslcertpassword=(%d chars)\ncainfo=%s",curl_easy_strerror(code),sslcert,strlen(sslcertpassword),cainfo); logger::blobprinf(outblob,"curl_easy_perform() failed: %s",curl_easy_strerror(code)); return; } curl_easy_getinfo(ch, CURLINFO_RESPONSE_CODE, &curl::curl_response_code); } FBUDF_API long fn_curl_get_response_code() { return curl::curl_response_code; }<|endoftext|>
<commit_before> #include "data.h" Data::Data(){ _initial_cellnumber=100; _max_prolif_types=10; _max_immune_types=10; } Data::Data(const Data& other){ _initial_cellnumber=other.return_initial_cellnumber(); _max_prolif_types=other.return_max_prolif_types(); _max_immune_types=other.return_max_immune_types(); } Data::Data(ParameterHandler & parameters){ //defining defaults: _initial_cellnumber=100; _max_prolif_types=10; _max_immune_types=10; _mutation_rate = 1; //overwriting with parameter files parameters.SetValue("initial_cellnumber","initial number of cells = 100",_initial_cellnumber); parameters.SetValue("prolif_types","total number of proliferation phenotypes",_max_prolif_types); parameters.SetValue("immune_types","total number of proliferation phenotypes",_max_immune_types); parameters.SetValue("mutation_rate","total mutation rate = 0.1",_mutation_rate); parameters.print_help(std::cout); } double Data::get_prolif_rate(unsigned int type) const{ //needs to be written! return 0.3+type/double(_max_prolif_types); } <commit_msg>Fixed bug in data.<commit_after> #include "data.h" Data::Data(){ _initial_cellnumber=100; _max_prolif_types=10; _max_immune_types=10; } Data::Data(const Data& other){ _initial_cellnumber=other.return_initial_cellnumber(); _max_prolif_types=other.return_max_prolif_types(); _max_immune_types=other.return_max_immune_types(); _mutation_rate=other.get_mutation_rate(); } Data::Data(ParameterHandler & parameters){ //defining defaults: _initial_cellnumber=100; _max_prolif_types=10; _max_immune_types=10; _mutation_rate = 1.1; //overwriting with parameter files parameters.SetValue("initial_cellnumber","initial number of cells = 100",_initial_cellnumber); parameters.SetValue("prolif_types","total number of proliferation phenotypes",_max_prolif_types); parameters.SetValue("immune_types","total number of proliferation phenotypes",_max_immune_types); parameters.SetValue("mutation_rate","total mutation rate = 0.1",_mutation_rate); parameters.print_help(std::cout); } double Data::get_prolif_rate(unsigned int type) const{ //needs to be written! return 0.3+type/double(_max_prolif_types); } <|endoftext|>
<commit_before>/* * deck.cpp * * Created on: Mar 13, 2016 * Author: Tumblr */ #include <iostream> #include <sstream> #include <algorithm> #include "deck.h" #include "stdlib.h" using namespace std; Deck::Deck() :deckName{ "Test" }, count{ new size_t(0) } { // TODO Auto-generated constructor stuff well_formed(); } Deck::Deck(string name) :deckName{ name }, count{ new size_t(0) } { // TODO Auto-generated constructor stuff well_formed(); } Deck::~Deck() { // TODO Auto-generated destructor stuff } Deck::Deck(const Deck &clone) :deck{ clone.deck }, deckName { clone.deckName }, count{ new size_t(clone.size()) } { // TODO cloning stuff here // passes clone's data to here well_formed(); } Deck* Deck::operator=(const Deck* clone) { // do set equals operations here // set this equal to the clone count = new size_t(clone->size()); deck = clone->deck; well_formed(); return this; } Deck& Deck::operator=(const Deck &clone) { // do set equals operations here // set this equal to the clone count = new size_t(clone.size()); deck = clone.deck; well_formed(); return *this; } string Deck::get_name() const { return deckName; } // removes the top card of the deck and returns it // shifting all the cards up one Card* Deck::draw_card(){ well_formed(); if(*count == 0) return nullptr; Card* ret = deck[0]; for(size_t i = 1; i < *count; i++) deck[i-1] = deck[i]; deck.pop_back(); *count -= 1; well_formed(); return ret; } // removes the card at the given index and returns it // shifting all the cards up one Card* Deck::get_card(size_t index) { well_formed(); if(*count == 0 || index < 0 || index > *count) return nullptr; Card* ret = deck[index]; for(size_t i = index + 1; i < *count; i++) deck[i-1] = deck[i]; deck.pop_back(); *count -= 1; well_formed(); return ret; } // removes the top num cards from the deck and returns // a "Deck" as the drawn cards. shifts all // the cards up num Deck Deck::draw_cards(int num) { Deck ret; if(!well_formed()) return ret; // draws a card from our deck to add // to the return deck; for(int i = 0; i < num; i++) { ret.add_card(draw_card()); } well_formed(); return ret; } // randomizes the order of the deck void Deck::shuffle() { if(!well_formed()) return; // Traverses through the array swapping each index with a random other index for(size_t i = 0; i < *count; i++) { size_t r = rand() % *count; Card* temp; temp = deck[i]; deck[i] = deck[r]; deck[r] = temp; } well_formed(); } // adds a card to the deck and then shuffles the deck bool Deck::add_card(Card* card) { if(!well_formed()) return false; // no room to add the card if(*count == 20) return print_err("No more room to add a card."); // adds the card and increments count deck.push_back(card); *count += 1; return well_formed(); } // adds a card at the specified index. i.e 0 for the top bool Deck::add_card(Card* card, size_t index) { if(!well_formed()) return false; // index can not be larger than count if(index >= *count - 1) return print_err("Index is out of bounds."); // no room to add the card if(*count == 20) return false; // moves all the cards after index down one for(size_t i = *count - 1; i > index; i--) { deck[i + 1] = deck[i]; } // puts the deck in at index and increments count deck[index] = card; *count += 1; well_formed(); return true; } // checks the integrity of the deck and returns false with an error message // if something is wrong. Returns true otherwise. // Rules: // A Deck may not be larger than 20 cards // A deck may not have any nullptr between 0 and count bool Deck::well_formed() { // may not be larger than 60 cards if(*count > deck.size()) return print_err("Count is larger than 20"); for(size_t i = 0; i < *count; i++) { // checks to make sure count is not larger than the size of the deck if(deck[i] == nullptr) return print_err("Count is larger than size of deck"); // COMENTED OUT FOR TESTING //int cardCount = 1; //for(size_t j = i + 1; j < *count; j++) { // adding it here checks the integrity of the array on our first pass // if(deck[i] == nullptr) return print_err("Count is larger than size of deck"); // Card c1 = *deck[i]; // Card c2 = *deck[j]; // if(c1.get_name() == c2.get_name()) cardCount++; // you may not have more than 2 of any card in a deck // if(cardCount > 2) return print_err("You may not have more than 2 of any card"); //} } // if the integrity of this data structure is held, returns true return true; } // prints the error message passed and returns false bool Deck::print_err(string err) { cout << err << endl; return false; } bool compare(Card* a, Card* b) { return (a->get_name() < b->get_name()); } string Deck::to_file() { string ret; int num = 1; sort(deck.begin(), deck.begin() + *count, compare); for(size_t i = 0; i < *count - 1; i++) { // case if we are looking at the last 2 cards of the deck // this will need to be edited slightly when we enforce // card limits if(i + 1 >= *count - 1) { ret += deck[i]->get_name(); ret += " X "; ret += std::to_string(num+1); ret += "\n"; num = 1; } // case for if we are looking at the same card as befor else if(deck[i]->get_name() == deck[i+1]->get_name()) num++; // case for when we have found a new card name else { ret += deck[i]->get_name(); ret += " X "; ret += std::to_string(num); ret += "\n"; num = 1; } } shuffle(); return ret; } string Deck::to_string() const { string ret; for(size_t i = 0; i < *count; i++) { ret += std::to_string(i+1); ret += ") "; ret += deck[i]->get_name(); ret += " - "; ret += std::to_string(deck[i]->get_cost()); ret += " "; } return ret; } <commit_msg>Added Deck method comments<commit_after>/* * deck.cpp * * Created on: Mar 13, 2016 * Author: Tumblr */ #include <iostream> #include <sstream> #include <algorithm> #include "deck.h" #include "stdlib.h" using namespace std; /* * Default Deck constructor */ Deck::Deck() :deckName{ "Test" }, count{ new size_t(0) } { // TODO Auto-generated constructor stuff well_formed(); } /* * Creates a new Deck with the given name */ Deck::Deck(string name) :deckName{ name }, count{ new size_t(0) } { // TODO Auto-generated constructor stuff well_formed(); } /* * Default Deck destructor */ Deck::~Deck() { // TODO Auto-generated destructor stuff } /* * Clone constructore Sets all attributes of this * Deck to the clone */ Deck::Deck(const Deck &clone) :deck{ clone.deck }, deckName { clone.deckName }, count{ new size_t(clone.size()) } { // TODO cloning stuff here // passes clone's data to here well_formed(); } /* * Sets all attriubutes of this Deck to the clone * at the given Deck pointer */ Deck* Deck::operator=(const Deck* clone) { // do set equals operations here // set this equal to the clone count = new size_t(clone->size()); deck = clone->deck; well_formed(); return this; } /* * Sets all attriubutes of this Deck to the clone */ Deck& Deck::operator=(const Deck &clone) { // do set equals operations here // set this equal to the clone count = new size_t(clone.size()); deck = clone.deck; well_formed(); return *this; } /* * Returns the name of the deck as a string */ string Deck::get_name() const { return deckName; } /* * Removes the top card of the deck and returns it * shifting all the cards up one */ Card* Deck::draw_card(){ well_formed(); if(*count == 0) return nullptr; Card* ret = deck[0]; for(size_t i = 1; i < *count; i++) deck[i-1] = deck[i]; deck.pop_back(); *count -= 1; well_formed(); return ret; } // removes the card at the given index and returns it // shifting all the cards up one Card* Deck::get_card(size_t index) { well_formed(); if(*count == 0 || index < 0 || index > *count) return nullptr; Card* ret = deck[index]; for(size_t i = index + 1; i < *count; i++) deck[i-1] = deck[i]; deck.pop_back(); *count -= 1; well_formed(); return ret; } /* * removes the top num cards from the deck and returns * a "Deck" as the drawn cards. shifts all * the cards up num */ Deck Deck::draw_cards(int num) { Deck ret; if(!well_formed()) return ret; // draws a card from our deck to add // to the return deck; for(int i = 0; i < num; i++) { ret.add_card(draw_card()); } well_formed(); return ret; } /* * Simulates the act of shuffling a deck */ void Deck::shuffle() { if(!well_formed()) return; // Traverses through the array swapping each index with a random other index for(size_t i = 0; i < *count; i++) { size_t r = rand() % *count; Card* temp; temp = deck[i]; deck[i] = deck[r]; deck[r] = temp; } well_formed(); } /* * Adds a card to the deck and then shuffles the deck */ bool Deck::add_card(Card* card) { if(!well_formed()) return false; // no room to add the card if(*count == 20) return print_err("No more room to add a card."); // adds the card and increments count deck.push_back(card); *count += 1; return well_formed(); } /* * Adds a card at the specified index. i.e 0 for the top */ bool Deck::add_card(Card* card, size_t index) { if(!well_formed()) return false; // index can not be larger than count if(index >= *count - 1) return print_err("Index is out of bounds."); // no room to add the card if(*count == 20) return false; // moves all the cards after index down one for(size_t i = *count - 1; i > index; i--) { deck[i + 1] = deck[i]; } // puts the deck in at index and increments count deck[index] = card; *count += 1; well_formed(); return true; } /* * checks the integrity of the deck and returns false with an error message * if something is wrong. Returns true otherwise. * Rules: * A Deck may not be larger than 20 cards * A deck may not have any nullptr between 0 and count */ bool Deck::well_formed() { // may not be larger than 60 cards if(*count > deck.size()) return print_err("Count is larger than 20"); for(size_t i = 0; i < *count; i++) { // checks to make sure count is not larger than the size of the deck if(deck[i] == nullptr) return print_err("Count is larger than size of deck"); // COMENTED OUT FOR TESTING //int cardCount = 1; //for(size_t j = i + 1; j < *count; j++) { // adding it here checks the integrity of the array on our first pass // if(deck[i] == nullptr) return print_err("Count is larger than size of deck"); // Card c1 = *deck[i]; // Card c2 = *deck[j]; // if(c1.get_name() == c2.get_name()) cardCount++; // you may not have more than 2 of any card in a deck // if(cardCount > 2) return print_err("You may not have more than 2 of any card"); //} } // if the integrity of this data structure is held, returns true return true; } // prints the error message passed and returns false bool Deck::print_err(string err) { cout << err << endl; return false; } /* * Compares the given cards to check for equlaity */ bool eqlual(Card* a, Card* b) { return (a->get_name() < b->get_name()); } /* * Convers the deck to a deck list file saved in the ../decklists folder */ string Deck::to_file() { string ret; int num = 1; sort(deck.begin(), deck.begin() + *count, equal); for(size_t i = 0; i < *count - 1; i++) { // case if we are looking at the last 2 cards of the deck // this will need to be edited slightly when we enforce // card limits if(i + 1 >= *count - 1) { ret += deck[i]->get_name(); ret += " X "; ret += std::to_string(num+1); ret += "\n"; num = 1; } // case for if we are looking at the same card as befor else if(deck[i]->get_name() == deck[i+1]->get_name()) num++; // case for when we have found a new card name else { ret += deck[i]->get_name(); ret += " X "; ret += std::to_string(num); ret += "\n"; num = 1; } } shuffle(); return ret; } /* * Convers the Deck to a string */ string Deck::to_string() const { string ret; for(size_t i = 0; i < *count; i++) { ret += std::to_string(i+1); ret += ") "; ret += deck[i]->get_name(); ret += " - "; ret += std::to_string(deck[i]->get_cost()); ret += " "; } return ret; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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. =========================================================================*/ // Software Guide : BeginCommandLineArgs // INPUTS: {qb_RoadExtract.tif} // OUTPUTS: {OBIARadiometricAttribute1.png}, {qb_ExtractRoad_Radiometry_pretty.jpg} // STATS::Band1::Mean 0 0.5 16 16 50 1.0 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example shows the basic approach to perform object based analysis on a image. // The input image is firstly segmented using the \doxygen{otb}{MeanShiftSegmentationFilter} // Then each segmented region is converted to a Map of labeled objects. // Afterwards the \doxygen{otb}{otbMultiChannelRAndNIRIndexImageFilter} computes // radiometric attributes for each object. In this example the NDVI is computed. // The computed feature is passed to the \doxygen{otb}{BandsStatisticsAttributesLabelMapFilter} // which computes statistics over the resulting band. // Therefore, region's statistics over each band can be access by concatening // STATS, the band number and the statistical attribute separated by colons. In this example // the mean of the first band (which contains the NDVI) is access over all the regions // with the attribute: 'STATS::Band1::Mean'. // // Software Guide : EndLatex #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMeanShiftSegmentationFilter.h" #include "itkLabelImageToLabelMapFilter.h" #include "otbShapeAttributesLabelMapFilter.h" #include "otbBandsStatisticsAttributesLabelMapFilter.h" #include "itkLabelMapToBinaryImageFilter.h" #include "otbMultiChannelExtractROI.h" #include "otbAttributesMapOpeningLabelMapFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" #include "otbMultiChannelRAndNIRIndexImageFilter.h" #include "otbImageToVectorImageCastFilter.h" int main(int argc, char * argv[]) { if (argc != 11) { std::cerr << "Usage: " << argv[0] << " reffname outfname outprettyfname attribute_name "; std::cerr << "lowerThan tresh spatialRadius rangeRadius minregionsize scale" << std::endl; return EXIT_FAILURE; } const char * reffname = argv[1]; const char * outfname = argv[2]; const char * outprettyfname = argv[3]; const char * attr = argv[4]; bool lowerThan = atoi(argv[5]); double thresh = atof(argv[6]); const unsigned int spatialRadius = atoi(argv[7]); const double rangeRadius = atof(argv[8]); const unsigned int minRegionSize = atoi(argv[9]); const double scale = atoi(argv[10]); const unsigned int Dimension = 2; // Labeled image type typedef unsigned short LabelType; typedef unsigned char MaskPixelType; typedef double PixelType; typedef otb::Image<LabelType, Dimension> LabeledImageType; typedef otb::Image<MaskPixelType, Dimension> MaskImageType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VectorImage<unsigned char, Dimension> OutputVectorImageType; typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<VectorImageType> VectorReaderType; typedef otb::ImageFileWriter<MaskImageType> WriterType; typedef otb::ImageFileWriter<OutputVectorImageType> VectorWriterType; typedef otb::VectorRescaleIntensityImageFilter <VectorImageType, OutputVectorImageType> VectorRescalerType; typedef otb::MultiChannelExtractROI<unsigned char, unsigned char> ChannelExtractorType; // Label map typedef typedef otb::AttributesMapLabelObject<LabelType, Dimension, double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType, LabelMapType> LabelMapFilterType; typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType, VectorImageType> RadiometricLabelMapFilterType; typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType; typedef itk::LabelMapToBinaryImageFilter<LabelMapType, MaskImageType> LabelMapToBinaryImageFilterType; typedef otb::MultiChannelRAndNIRIndexImageFilter<VectorImageType, ImageType> NDVIImageFilterType; typedef otb::ImageToVectorImageCastFilter<ImageType, VectorImageType> ImageToVectorImageCastFilterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(reffname); LabeledReaderType::Pointer lreader = LabeledReaderType::New(); lreader->SetFileName(reffname); VectorReaderType::Pointer vreader = VectorReaderType::New(); vreader->SetFileName(reffname); vreader->Update(); // Software Guide : BeginLatex // // Firstly, segment the input image by using the Mean Shift algorithm (see \ref{sec:MeanShift} for deeper // explanations). // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::MeanShiftSegmentationFilter <VectorImageType, LabeledImageType, VectorImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetSpatialBandwidth(spatialRadius); filter->SetRangeBandwidth(rangeRadius); filter->SetMinRegionSize(minRegionSize); filter->SetThreshold(0.1); filter->SetMaxIterationNumber(100); // Software Guide : EndCodeSnippet // For non regression tests, set the number of threads to 1 // because MeanShift results depends on the number of threads filter->SetNumberOfThreads(1); // Software Guide : BeginLatex // // The \doxygen{otb}{MeanShiftSegmentationFilter} type is instantiated using the image // types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput(vreader->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{itk}{LabelImageToLabelMapFilter} type is instantiated using the output // of the \doxygen{otb}{MeanShiftSegmentationFilter}. This filter produces a labeled image // where each segmented region has a unique label. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); labelMapFilter->SetInput(filter->GetLabelOutput()); labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min()); ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New(); shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Instantiate the \doxygen{otb}{RadiometricLabelMapFilterType} to // compute statistics of the feature image on each label object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Feature image could be one of the following image: // \begin{itemize} // \item GEMI // \item NDVI // \item IR // \item IC // \item IB // \item NDWI2 // \item Intensity // \end{itemize} // // Input image must be convert to the desired coefficient. // In our case, statistics are computed on the NDVI coefficient on each label object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet NDVIImageFilterType:: Pointer ndviImageFilter = NDVIImageFilterType::New(); ndviImageFilter->SetRedIndex(3); ndviImageFilter->SetNIRIndex(4); ndviImageFilter->SetInput(vreader->GetOutput()); ImageToVectorImageCastFilterType::Pointer ndviVectorImageFilter = ImageToVectorImageCastFilterType::New(); ndviVectorImageFilter->SetInput(ndviImageFilter->GetOutput()); radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput()); radiometricLabelMapFilter->SetFeatureImage(ndviVectorImageFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{AttributesMapOpeningLabelMapFilter} will perform the selection. // There are three parameters. \code{AttributeName} specifies the radiometric attribute, \code{Lambda} // controls the thresholding of the input and \code{ReverseOrdering} make this filter to remove the // object with an attribute value greater than \code{Lambda} instead. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New(); opening->SetInput(radiometricLabelMapFilter->GetOutput()); opening->SetAttributeName(attr); opening->SetLambda(thresh); opening->SetReverseOrdering(lowerThan); opening->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, Label objects selected are transform in a Label Image using the // \doxygen{itk}{LabelMapToLabelImageFilter}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapToBinaryImageFilterType::Pointer labelMap2LabeledImage = LabelMapToBinaryImageFilterType::New(); labelMap2LabeledImage->SetInput(opening->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And finally, we declare the writer and call its \code{Update()} method to // trigger the full pipeline execution. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(labelMap2LabeledImage->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet OutputVectorImageType::PixelType minimum, maximum; minimum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); maximum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); minimum.Fill(0); maximum.Fill(255); VectorRescalerType::Pointer vr = VectorRescalerType::New(); vr->SetInput(filter->GetClusteredOutput()); vr->SetOutputMinimum(minimum); vr->SetOutputMaximum(maximum); vr->SetClampThreshold(0.01); ChannelExtractorType::Pointer selecter = ChannelExtractorType::New(); selecter->SetInput(vr->GetOutput()); selecter->SetExtractionRegion(vreader->GetOutput()->GetLargestPossibleRegion()); selecter->SetChannel(3); selecter->SetChannel(2); selecter->SetChannel(1); VectorWriterType::Pointer vectWriter = VectorWriterType::New(); vectWriter->SetFileName(outprettyfname); vectWriter->SetInput(selecter->GetOutput()); vectWriter->Update(); return EXIT_SUCCESS; } // Software Guide : BeginLatex // // Figure~\ref{fig:RADIOMETRIC_LABEL_MAP_FILTER} shows the result of applying // the object selection based on radiometric attributes. // \begin{figure} [htbp] // \center // \includegraphics[width=0.44\textwidth]{qb_ExtractRoad_Radiometry_pretty.eps} // \includegraphics[width=0.44\textwidth]{OBIARadiometricAttribute1.eps} // \itkcaption[Object based extraction based on ]{Vegetation mask resulting from processing.} // \label{fig:RADIOMETRIC_LABEL_MAP_FILTER} // \end{figure} // // Software Guide : EndLatex <commit_msg>BUG: use decent precision for label type<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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. =========================================================================*/ // Software Guide : BeginCommandLineArgs // INPUTS: {qb_RoadExtract.tif} // OUTPUTS: {OBIARadiometricAttribute1.png}, {qb_ExtractRoad_Radiometry_pretty.jpg} // STATS::Band1::Mean 0 0.5 16 16 50 1.0 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example shows the basic approach to perform object based analysis on a image. // The input image is firstly segmented using the \doxygen{otb}{MeanShiftSegmentationFilter} // Then each segmented region is converted to a Map of labeled objects. // Afterwards the \doxygen{otb}{otbMultiChannelRAndNIRIndexImageFilter} computes // radiometric attributes for each object. In this example the NDVI is computed. // The computed feature is passed to the \doxygen{otb}{BandsStatisticsAttributesLabelMapFilter} // which computes statistics over the resulting band. // Therefore, region's statistics over each band can be access by concatening // STATS, the band number and the statistical attribute separated by colons. In this example // the mean of the first band (which contains the NDVI) is access over all the regions // with the attribute: 'STATS::Band1::Mean'. // // Software Guide : EndLatex #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMeanShiftSegmentationFilter.h" #include "itkLabelImageToLabelMapFilter.h" #include "otbShapeAttributesLabelMapFilter.h" #include "otbBandsStatisticsAttributesLabelMapFilter.h" #include "itkLabelMapToBinaryImageFilter.h" #include "otbMultiChannelExtractROI.h" #include "otbAttributesMapOpeningLabelMapFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" #include "otbMultiChannelRAndNIRIndexImageFilter.h" #include "otbImageToVectorImageCastFilter.h" int main(int argc, char * argv[]) { if (argc != 11) { std::cerr << "Usage: " << argv[0] << " reffname outfname outprettyfname attribute_name "; std::cerr << "lowerThan tresh spatialRadius rangeRadius minregionsize scale" << std::endl; return EXIT_FAILURE; } const char * reffname = argv[1]; const char * outfname = argv[2]; const char * outprettyfname = argv[3]; const char * attr = argv[4]; bool lowerThan = atoi(argv[5]); double thresh = atof(argv[6]); const unsigned int spatialRadius = atoi(argv[7]); const double rangeRadius = atof(argv[8]); const unsigned int minRegionSize = atoi(argv[9]); const double scale = atoi(argv[10]); const unsigned int Dimension = 2; // Labeled image type typedef unsigned int LabelType; typedef unsigned char MaskPixelType; typedef double PixelType; typedef otb::Image<LabelType, Dimension> LabeledImageType; typedef otb::Image<MaskPixelType, Dimension> MaskImageType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::VectorImage<PixelType, Dimension> VectorImageType; typedef otb::VectorImage<unsigned char, Dimension> OutputVectorImageType; typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileReader<VectorImageType> VectorReaderType; typedef otb::ImageFileWriter<MaskImageType> WriterType; typedef otb::ImageFileWriter<OutputVectorImageType> VectorWriterType; typedef otb::VectorRescaleIntensityImageFilter <VectorImageType, OutputVectorImageType> VectorRescalerType; typedef otb::MultiChannelExtractROI<unsigned char, unsigned char> ChannelExtractorType; // Label map typedef typedef otb::AttributesMapLabelObject<LabelType, Dimension, double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType, LabelMapType> LabelMapFilterType; typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType; typedef otb::BandsStatisticsAttributesLabelMapFilter<LabelMapType, VectorImageType> RadiometricLabelMapFilterType; typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType; typedef itk::LabelMapToBinaryImageFilter<LabelMapType, MaskImageType> LabelMapToBinaryImageFilterType; typedef otb::MultiChannelRAndNIRIndexImageFilter<VectorImageType, ImageType> NDVIImageFilterType; typedef otb::ImageToVectorImageCastFilter<ImageType, VectorImageType> ImageToVectorImageCastFilterType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(reffname); LabeledReaderType::Pointer lreader = LabeledReaderType::New(); lreader->SetFileName(reffname); VectorReaderType::Pointer vreader = VectorReaderType::New(); vreader->SetFileName(reffname); vreader->Update(); // Software Guide : BeginLatex // // Firstly, segment the input image by using the Mean Shift algorithm (see \ref{sec:MeanShift} for deeper // explanations). // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::MeanShiftSegmentationFilter <VectorImageType, LabeledImageType, VectorImageType> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetSpatialBandwidth(spatialRadius); filter->SetRangeBandwidth(rangeRadius); filter->SetMinRegionSize(minRegionSize); filter->SetThreshold(0.1); filter->SetMaxIterationNumber(100); // Software Guide : EndCodeSnippet // For non regression tests, set the number of threads to 1 // because MeanShift results depends on the number of threads filter->SetNumberOfThreads(1); // Software Guide : BeginLatex // // The \doxygen{otb}{MeanShiftSegmentationFilter} type is instantiated using the image // types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet filter->SetInput(vreader->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{itk}{LabelImageToLabelMapFilter} type is instantiated using the output // of the \doxygen{otb}{MeanShiftSegmentationFilter}. This filter produces a labeled image // where each segmented region has a unique label. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); labelMapFilter->SetInput(filter->GetLabelOutput()); labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min()); ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New(); shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Instantiate the \doxygen{otb}{RadiometricLabelMapFilterType} to // compute statistics of the feature image on each label object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Feature image could be one of the following image: // \begin{itemize} // \item GEMI // \item NDVI // \item IR // \item IC // \item IB // \item NDWI2 // \item Intensity // \end{itemize} // // Input image must be convert to the desired coefficient. // In our case, statistics are computed on the NDVI coefficient on each label object. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet NDVIImageFilterType:: Pointer ndviImageFilter = NDVIImageFilterType::New(); ndviImageFilter->SetRedIndex(3); ndviImageFilter->SetNIRIndex(4); ndviImageFilter->SetInput(vreader->GetOutput()); ImageToVectorImageCastFilterType::Pointer ndviVectorImageFilter = ImageToVectorImageCastFilterType::New(); ndviVectorImageFilter->SetInput(ndviImageFilter->GetOutput()); radiometricLabelMapFilter->SetInput(shapeLabelMapFilter->GetOutput()); radiometricLabelMapFilter->SetFeatureImage(ndviVectorImageFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{AttributesMapOpeningLabelMapFilter} will perform the selection. // There are three parameters. \code{AttributeName} specifies the radiometric attribute, \code{Lambda} // controls the thresholding of the input and \code{ReverseOrdering} make this filter to remove the // object with an attribute value greater than \code{Lambda} instead. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New(); opening->SetInput(radiometricLabelMapFilter->GetOutput()); opening->SetAttributeName(attr); opening->SetLambda(thresh); opening->SetReverseOrdering(lowerThan); opening->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, Label objects selected are transform in a Label Image using the // \doxygen{itk}{LabelMapToLabelImageFilter}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapToBinaryImageFilterType::Pointer labelMap2LabeledImage = LabelMapToBinaryImageFilterType::New(); labelMap2LabeledImage->SetInput(opening->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // And finally, we declare the writer and call its \code{Update()} method to // trigger the full pipeline execution. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(labelMap2LabeledImage->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet OutputVectorImageType::PixelType minimum, maximum; minimum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); maximum.SetSize(vreader->GetOutput()->GetNumberOfComponentsPerPixel()); minimum.Fill(0); maximum.Fill(255); VectorRescalerType::Pointer vr = VectorRescalerType::New(); vr->SetInput(filter->GetClusteredOutput()); vr->SetOutputMinimum(minimum); vr->SetOutputMaximum(maximum); vr->SetClampThreshold(0.01); ChannelExtractorType::Pointer selecter = ChannelExtractorType::New(); selecter->SetInput(vr->GetOutput()); selecter->SetExtractionRegion(vreader->GetOutput()->GetLargestPossibleRegion()); selecter->SetChannel(3); selecter->SetChannel(2); selecter->SetChannel(1); VectorWriterType::Pointer vectWriter = VectorWriterType::New(); vectWriter->SetFileName(outprettyfname); vectWriter->SetInput(selecter->GetOutput()); vectWriter->Update(); return EXIT_SUCCESS; } // Software Guide : BeginLatex // // Figure~\ref{fig:RADIOMETRIC_LABEL_MAP_FILTER} shows the result of applying // the object selection based on radiometric attributes. // \begin{figure} [htbp] // \center // \includegraphics[width=0.44\textwidth]{qb_ExtractRoad_Radiometry_pretty.eps} // \includegraphics[width=0.44\textwidth]{OBIARadiometricAttribute1.eps} // \itkcaption[Object based extraction based on ]{Vegetation mask resulting from processing.} // \label{fig:RADIOMETRIC_LABEL_MAP_FILTER} // \end{figure} // // Software Guide : EndLatex <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{HoughTransform2DCirclesImageFilter} to find circles in a // 2-dimensional image. // // First, we include the header files of the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkHoughTransform2DCirclesImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageRegionIterator.h" #include "itkThresholdImageFilter.h" #include "itkMinimumMaximumImageCalculator.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include <list> #include "itkCastImageFilter.h" #include "itkMath.h" int main( int argc, char *argv[] ) { if( argc < 6 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0] << std::endl; std::cerr << " inputImage " << std::endl; std::cerr << " outputImage" << std::endl; std::cerr << " numberOfCircles " << std::endl; std::cerr << " radius Min " << std::endl; std::cerr << " radius Max " << std::endl; std::cerr << " sweep Angle (default = 0)" << std::endl; std::cerr << " SigmaGradient (default = 1) " << std::endl; std::cerr << " variance of the accumulator blurring (default = 5) " << std::endl; std::cerr << " radius of the disk to remove from the accumulator (default = 10) "<< std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Next, we declare the pixel type and image dimension and specify the // image type to be used as input. We also specify the image type of the // accumulator used in the Hough transform filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef unsigned char PixelType; typedef float AccumulatorPixelType; const unsigned int Dimension = 2; typedef itk::Image< PixelType, Dimension > ImageType; ImageType::IndexType localIndex; typedef itk::Image< AccumulatorPixelType, Dimension > AccumulatorImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We setup a reader to load the input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } ImageType::Pointer localImage = reader->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We create the HoughTransform2DCirclesImageFilter based on the pixel // type of the input image (the resulting image from the // ThresholdImageFilter). // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << "Computing Hough Map" << std::endl; typedef itk::HoughTransform2DCirclesImageFilter<PixelType, AccumulatorPixelType> HoughTransformFilterType; HoughTransformFilterType::Pointer houghFilter = HoughTransformFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We set the input of the filter to be the output of the // ImageFileReader. We set also the number of circles we are looking for. // Basically, the filter computes the Hough map, blurs it using a certain // variance and finds maxima in the Hough map. After a maximum is found, // the local neighborhood, a circle, is removed from the Hough map. // SetDiscRadiusRatio() defines the radius of this disc proportional to // the radius of the disc found. The Hough map is computed by looking at // the points above a certain threshold in the input image. Then, for each // point, a Gaussian derivative function is computed to find the direction // of the normal at that point. The standard deviation of the derivative // function can be adjusted by SetSigmaGradient(). The accumulator is // filled by drawing a line along the normal and the length of this line // is defined by the minimum radius (SetMinimumRadius()) and the maximum // radius (SetMaximumRadius()). Moreover, a sweep angle can be defined by // SetSweepAngle() (default 0.0) to increase the accuracy of detection. // // The output of the filter is the accumulator. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet houghFilter->SetInput( reader->GetOutput() ); houghFilter->SetNumberOfCircles( atoi(argv[3]) ); houghFilter->SetMinimumRadius( atof(argv[4]) ); houghFilter->SetMaximumRadius( atof(argv[5]) ); if( argc > 6 ) { houghFilter->SetSweepAngle( atof(argv[6]) ); } if( argc > 7 ) { houghFilter->SetSigmaGradient( atoi(argv[7]) ); } if( argc > 8 ) { houghFilter->SetVariance( atof(argv[8]) ); } if( argc > 9 ) { houghFilter->SetDiscRadiusRatio( atof(argv[9]) ); } houghFilter->Update(); AccumulatorImageType::Pointer localAccumulator = houghFilter->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can also get the circles as \doxygen{EllipseSpatialObject}. The // \code{GetCircles()} function return a list of those. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet HoughTransformFilterType::CirclesListType circles; circles = houghFilter->GetCircles(); std::cout << "Found " << circles.size() << " circle(s)." << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can then allocate an image to draw the resulting circles as binary // objects. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; OutputImageType::Pointer localOutputImage = OutputImageType::New(); OutputImageType::RegionType region; region.SetSize(localImage->GetLargestPossibleRegion().GetSize()); region.SetIndex(localImage->GetLargestPossibleRegion().GetIndex()); localOutputImage->SetRegions( region ); localOutputImage->SetOrigin(localImage->GetOrigin()); localOutputImage->SetSpacing(localImage->GetSpacing()); localOutputImage->Allocate(true); // initializes buffer to zero // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We iterate through the list of circles and we draw them. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef HoughTransformFilterType::CirclesListType CirclesListType; CirclesListType::const_iterator itCircles = circles.begin(); while( itCircles != circles.end() ) { std::cout << "Center: "; std::cout << (*itCircles)->GetObjectToParentTransform()->GetOffset() << std::endl; std::cout << "Radius: " << (*itCircles)->GetRadius()[0] << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We draw white pixels in the output image to represent each circle. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet for(double angle = 0;angle <= 2*itk::Math::pi; angle += itk::Math::pi/60.0 ) { localIndex[0] = itk::Math::Round<long int>((*itCircles)->GetObjectToParentTransform()->GetOffset()[0] + (*itCircles)->GetRadius()[0]*std::cos(angle)); localIndex[1] = itk::Math::Round<long int>((*itCircles)->GetObjectToParentTransform()->GetOffset()[1] + (*itCircles)->GetRadius()[0]*std::sin(angle)); OutputImageType::RegionType outputRegion = localOutputImage->GetLargestPossibleRegion(); if( outputRegion.IsInside( localIndex ) ) { localOutputImage->SetPixel( localIndex, 255 ); } } itCircles++; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We setup a writer to write out the binary image created. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput(localOutputImage ); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <commit_msg>COMP: HoughTransform2DCirclesImageFilter lines too long for Software Guide<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{HoughTransform2DCirclesImageFilter} to find circles in a // 2-dimensional image. // // First, we include the header files of the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkHoughTransform2DCirclesImageFilter.h" // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageRegionIterator.h" #include "itkThresholdImageFilter.h" #include "itkMinimumMaximumImageCalculator.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include <list> #include "itkCastImageFilter.h" #include "itkMath.h" int main( int argc, char *argv[] ) { if( argc < 6 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0] << std::endl; std::cerr << " inputImage " << std::endl; std::cerr << " outputImage" << std::endl; std::cerr << " numberOfCircles " << std::endl; std::cerr << " radius Min " << std::endl; std::cerr << " radius Max " << std::endl; std::cerr << " sweep Angle (default = 0)" << std::endl; std::cerr << " SigmaGradient (default = 1) " << std::endl; std::cerr << " variance of the accumulator blurring (default = 5) " << std::endl; std::cerr << " radius of the disk to remove from the accumulator (default = 10) "<< std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Next, we declare the pixel type and image dimension and specify the // image type to be used as input. We also specify the image type of the // accumulator used in the Hough transform filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef unsigned char PixelType; typedef float AccumulatorPixelType; const unsigned int Dimension = 2; typedef itk::Image< PixelType, Dimension > ImageType; ImageType::IndexType localIndex; typedef itk::Image< AccumulatorPixelType, Dimension > AccumulatorImageType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We setup a reader to load the input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } ImageType::Pointer localImage = reader->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We create the HoughTransform2DCirclesImageFilter based on the pixel // type of the input image (the resulting image from the // ThresholdImageFilter). // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet std::cout << "Computing Hough Map" << std::endl; typedef itk::HoughTransform2DCirclesImageFilter<PixelType, AccumulatorPixelType> HoughTransformFilterType; HoughTransformFilterType::Pointer houghFilter = HoughTransformFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We set the input of the filter to be the output of the // ImageFileReader. We set also the number of circles we are looking for. // Basically, the filter computes the Hough map, blurs it using a certain // variance and finds maxima in the Hough map. After a maximum is found, // the local neighborhood, a circle, is removed from the Hough map. // SetDiscRadiusRatio() defines the radius of this disc proportional to // the radius of the disc found. The Hough map is computed by looking at // the points above a certain threshold in the input image. Then, for each // point, a Gaussian derivative function is computed to find the direction // of the normal at that point. The standard deviation of the derivative // function can be adjusted by SetSigmaGradient(). The accumulator is // filled by drawing a line along the normal and the length of this line // is defined by the minimum radius (SetMinimumRadius()) and the maximum // radius (SetMaximumRadius()). Moreover, a sweep angle can be defined by // SetSweepAngle() (default 0.0) to increase the accuracy of detection. // // The output of the filter is the accumulator. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet houghFilter->SetInput( reader->GetOutput() ); houghFilter->SetNumberOfCircles( atoi(argv[3]) ); houghFilter->SetMinimumRadius( atof(argv[4]) ); houghFilter->SetMaximumRadius( atof(argv[5]) ); if( argc > 6 ) { houghFilter->SetSweepAngle( atof(argv[6]) ); } if( argc > 7 ) { houghFilter->SetSigmaGradient( atoi(argv[7]) ); } if( argc > 8 ) { houghFilter->SetVariance( atof(argv[8]) ); } if( argc > 9 ) { houghFilter->SetDiscRadiusRatio( atof(argv[9]) ); } houghFilter->Update(); AccumulatorImageType::Pointer localAccumulator = houghFilter->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can also get the circles as \doxygen{EllipseSpatialObject}. The // \code{GetCircles()} function return a list of those. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet HoughTransformFilterType::CirclesListType circles; circles = houghFilter->GetCircles(); std::cout << "Found " << circles.size() << " circle(s)." << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can then allocate an image to draw the resulting circles as binary // objects. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef unsigned char OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; OutputImageType::Pointer localOutputImage = OutputImageType::New(); OutputImageType::RegionType region; region.SetSize(localImage->GetLargestPossibleRegion().GetSize()); region.SetIndex(localImage->GetLargestPossibleRegion().GetIndex()); localOutputImage->SetRegions( region ); localOutputImage->SetOrigin(localImage->GetOrigin()); localOutputImage->SetSpacing(localImage->GetSpacing()); localOutputImage->Allocate(true); // initializes buffer to zero // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We iterate through the list of circles and we draw them. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef HoughTransformFilterType::CirclesListType CirclesListType; CirclesListType::const_iterator itCircles = circles.begin(); while( itCircles != circles.end() ) { std::cout << "Center: "; std::cout << (*itCircles)->GetObjectToParentTransform()->GetOffset() << std::endl; std::cout << "Radius: " << (*itCircles)->GetRadius()[0] << std::endl; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We draw white pixels in the output image to represent each circle. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet for( double angle = 0; angle <= itk::Math::twopi; angle += itk::Math::pi/60.0 ) { typedef HoughTransformFilterType::CircleType::TransformType TransformType; typedef TransformType::OutputVectorType OffsetType; const OffsetType offset = (*itCircles)->GetObjectToParentTransform()->GetOffset(); localIndex[0] = itk::Math::Round<long int>(offset[0] + (*itCircles)->GetRadius()[0]*std::cos(angle)); localIndex[1] = itk::Math::Round<long int>(offset[1] + (*itCircles)->GetRadius()[0]*std::sin(angle)); OutputImageType::RegionType outputRegion = localOutputImage->GetLargestPossibleRegion(); if( outputRegion.IsInside( localIndex ) ) { localOutputImage->SetPixel( localIndex, 255 ); } } itCircles++; } // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We setup a writer to write out the binary image created. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput(localOutputImage ); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } // Software Guide : EndCodeSnippet return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "platform/local_country_file_utils.hpp" #include "platform/platform.hpp" #include "coding/file_name_utils.hpp" #include "coding/file_writer.hpp" #include "base/string_utils.hpp" #include "base/logging.hpp" #include "std/algorithm.hpp" #include "std/cctype.hpp" namespace platform { namespace { size_t const kMaxTimestampLength = 18; bool IsSpecialFile(string const & file) { return file == "." || file == ".."; } } // namespace void CleanupMapsDirectory() { Platform & platform = GetPlatform(); string const mapsDir = platform.WritableDir(); // Remove partially downloaded maps. { Platform::FilesList files; string const regexp = "\\" DATA_FILE_EXTENSION "\\.(downloading2?$|resume2?$)"; platform.GetFilesByRegExp(mapsDir, regexp, files); for (string const & file : files) FileWriter::DeleteFileX(file); } // Find and remove Brazil and Japan maps. vector<LocalCountryFile> localFiles; FindAllLocalMaps(localFiles); for (LocalCountryFile & localFile : localFiles) { CountryFile const countryFile = localFile.GetCountryFile(); if (countryFile.GetNameWithoutExt() == "Japan" || countryFile.GetNameWithoutExt() == "Brazil") { localFile.SyncWithDisk(); localFile.DeleteFromDisk(); } } // Try to delete empty folders. Platform::FilesList subdirs; Platform::GetFilesByType(mapsDir, Platform::FILE_TYPE_DIRECTORY, subdirs); for (string const & subdir : subdirs) { int64_t version; if (ParseVersion(subdir, version)) { vector<string> files; string const subdirPath = my::JoinFoldersToPath(mapsDir, subdir); platform.GetFilesByType(subdirPath, Platform::FILE_TYPE_REGULAR | Platform::FILE_TYPE_DIRECTORY, files); if (all_of(files.begin(), files.end(), &IsSpecialFile)) VERIFY(Platform::ERR_OK == Platform::RmDir(subdirPath), ("Can't remove empty directory:", subdirPath, "error:", ret)); } } } void FindAllLocalMapsInDirectory(string const & directory, int64_t version, vector<LocalCountryFile> & localFiles) { vector<string> files; Platform & platform = GetPlatform(); platform.GetFilesByRegExp(directory, ".*\\" DATA_FILE_EXTENSION "$", files); for (string const & file : files) { // Remove DATA_FILE_EXTENSION and use base name as a country file name. string name = file; my::GetNameWithoutExt(name); localFiles.emplace_back(directory, CountryFile(name), version); } } void FindAllLocalMaps(vector<LocalCountryFile> & localFiles) { vector<LocalCountryFile> allFiles; Platform & platform = GetPlatform(); vector<string> baseDirectories = { platform.ResourcesDir(), platform.WritableDir(), }; sort(baseDirectories.begin(), baseDirectories.end()); baseDirectories.erase(unique(baseDirectories.begin(), baseDirectories.end()), baseDirectories.end()); for (string const & directory : baseDirectories) { FindAllLocalMapsInDirectory(directory, 0 /* version */, allFiles); Platform::FilesList subdirs; Platform::GetFilesByType(directory, Platform::FILE_TYPE_DIRECTORY, subdirs); for (string const & subdir : subdirs) { int64_t version; if (ParseVersion(subdir, version)) FindAllLocalMapsInDirectory(my::JoinFoldersToPath(directory, subdir), version, allFiles); } } #if defined(OMIM_OS_ANDROID) // On Android World and WorldCoasts can be stored in alternative /Android/obb/ path. for (string const & file : {WORLD_FILE_NAME, WORLD_COASTS_FILE_NAME}) { bool found = false; for (LocalCountryFile const & localFile : allFiles) { if (localFile.GetCountryFile().GetNameWithoutExt() == file) { found = true; break; } } if (!found) { try { ModelReaderPtr reader = platform.GetReader(file + DATA_FILE_EXTENSION); allFiles.emplace_back(my::GetDirectory(reader.GetName()), CountryFile(file), 0 /* version */); } catch (FileAbsentException const & e) { LOG(LERROR, ("Can't find map file for", file, ".")); } } } #endif // defined(OMIM_OS_ANDROID) localFiles.insert(localFiles.end(), allFiles.begin(), allFiles.end()); } bool ParseVersion(string const & s, int64_t & version) { if (s.empty() || s.size() > kMaxTimestampLength) return false; int64_t v = 0; for (char const c : s) { if (!isdigit(c)) return false; v = v * 10 + c - '0'; } version = v; return true; } shared_ptr<LocalCountryFile> PreparePlaceForCountryFiles(CountryFile const & countryFile, int64_t version) { Platform & platform = GetPlatform(); if (version == 0) return make_shared<LocalCountryFile>(platform.WritableDir(), countryFile, version); string const directory = my::JoinFoldersToPath(platform.WritableDir(), strings::to_string(version)); switch (platform.MkDir(directory)) { case Platform::ERR_OK: return make_shared<LocalCountryFile>(directory, countryFile, version); case Platform::ERR_FILE_ALREADY_EXISTS: { Platform::EFileType type; if (Platform::GetFileType(directory, type) != Platform::ERR_OK || type != Platform::FILE_TYPE_DIRECTORY) { return shared_ptr<LocalCountryFile>(); } return make_shared<LocalCountryFile>(directory, countryFile, version); } default: return shared_ptr<LocalCountryFile>(); }; } } // namespace platform <commit_msg>Compilation error fix in DEBUG.<commit_after>#include "platform/local_country_file_utils.hpp" #include "platform/platform.hpp" #include "coding/file_name_utils.hpp" #include "coding/file_writer.hpp" #include "base/string_utils.hpp" #include "base/logging.hpp" #include "std/algorithm.hpp" #include "std/cctype.hpp" namespace platform { namespace { size_t const kMaxTimestampLength = 18; bool IsSpecialFile(string const & file) { return file == "." || file == ".."; } } // namespace void CleanupMapsDirectory() { Platform & platform = GetPlatform(); string const mapsDir = platform.WritableDir(); // Remove partially downloaded maps. { Platform::FilesList files; string const regexp = "\\" DATA_FILE_EXTENSION "\\.(downloading2?$|resume2?$)"; platform.GetFilesByRegExp(mapsDir, regexp, files); for (string const & file : files) FileWriter::DeleteFileX(file); } // Find and remove Brazil and Japan maps. vector<LocalCountryFile> localFiles; FindAllLocalMaps(localFiles); for (LocalCountryFile & localFile : localFiles) { CountryFile const countryFile = localFile.GetCountryFile(); if (countryFile.GetNameWithoutExt() == "Japan" || countryFile.GetNameWithoutExt() == "Brazil") { localFile.SyncWithDisk(); localFile.DeleteFromDisk(); } } // Try to delete empty folders. Platform::FilesList subdirs; Platform::GetFilesByType(mapsDir, Platform::FILE_TYPE_DIRECTORY, subdirs); for (string const & subdir : subdirs) { int64_t version; if (ParseVersion(subdir, version)) { vector<string> files; string const subdirPath = my::JoinFoldersToPath(mapsDir, subdir); platform.GetFilesByType(subdirPath, Platform::FILE_TYPE_REGULAR | Platform::FILE_TYPE_DIRECTORY, files); if (all_of(files.begin(), files.end(), &IsSpecialFile)) { Platform::EError const ret = Platform::RmDir(subdirPath); ASSERT_EQUAL(Platform::ERR_OK, ret, ("Can't remove empty directory:", subdirPath, "error:", ret)); UNUSED_VALUE(ret); } } } } void FindAllLocalMapsInDirectory(string const & directory, int64_t version, vector<LocalCountryFile> & localFiles) { vector<string> files; Platform & platform = GetPlatform(); platform.GetFilesByRegExp(directory, ".*\\" DATA_FILE_EXTENSION "$", files); for (string const & file : files) { // Remove DATA_FILE_EXTENSION and use base name as a country file name. string name = file; my::GetNameWithoutExt(name); localFiles.emplace_back(directory, CountryFile(name), version); } } void FindAllLocalMaps(vector<LocalCountryFile> & localFiles) { vector<LocalCountryFile> allFiles; Platform & platform = GetPlatform(); vector<string> baseDirectories = { platform.ResourcesDir(), platform.WritableDir(), }; sort(baseDirectories.begin(), baseDirectories.end()); baseDirectories.erase(unique(baseDirectories.begin(), baseDirectories.end()), baseDirectories.end()); for (string const & directory : baseDirectories) { FindAllLocalMapsInDirectory(directory, 0 /* version */, allFiles); Platform::FilesList subdirs; Platform::GetFilesByType(directory, Platform::FILE_TYPE_DIRECTORY, subdirs); for (string const & subdir : subdirs) { int64_t version; if (ParseVersion(subdir, version)) FindAllLocalMapsInDirectory(my::JoinFoldersToPath(directory, subdir), version, allFiles); } } #if defined(OMIM_OS_ANDROID) // On Android World and WorldCoasts can be stored in alternative /Android/obb/ path. for (string const & file : {WORLD_FILE_NAME, WORLD_COASTS_FILE_NAME}) { bool found = false; for (LocalCountryFile const & localFile : allFiles) { if (localFile.GetCountryFile().GetNameWithoutExt() == file) { found = true; break; } } if (!found) { try { ModelReaderPtr reader = platform.GetReader(file + DATA_FILE_EXTENSION); allFiles.emplace_back(my::GetDirectory(reader.GetName()), CountryFile(file), 0 /* version */); } catch (FileAbsentException const & e) { LOG(LERROR, ("Can't find map file for", file, ".")); } } } #endif // defined(OMIM_OS_ANDROID) localFiles.insert(localFiles.end(), allFiles.begin(), allFiles.end()); } bool ParseVersion(string const & s, int64_t & version) { if (s.empty() || s.size() > kMaxTimestampLength) return false; int64_t v = 0; for (char const c : s) { if (!isdigit(c)) return false; v = v * 10 + c - '0'; } version = v; return true; } shared_ptr<LocalCountryFile> PreparePlaceForCountryFiles(CountryFile const & countryFile, int64_t version) { Platform & platform = GetPlatform(); if (version == 0) return make_shared<LocalCountryFile>(platform.WritableDir(), countryFile, version); string const directory = my::JoinFoldersToPath(platform.WritableDir(), strings::to_string(version)); switch (platform.MkDir(directory)) { case Platform::ERR_OK: return make_shared<LocalCountryFile>(directory, countryFile, version); case Platform::ERR_FILE_ALREADY_EXISTS: { Platform::EFileType type; if (Platform::GetFileType(directory, type) != Platform::ERR_OK || type != Platform::FILE_TYPE_DIRECTORY) { return shared_ptr<LocalCountryFile>(); } return make_shared<LocalCountryFile>(directory, countryFile, version); } default: return shared_ptr<LocalCountryFile>(); }; } } // namespace platform <|endoftext|>
<commit_before>/* * Copyright 2008-2010 Arsen Chaloyan * * 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. * * $Id$ */ #include "verifiersession.h" #include "verifierscenario.h" #include "mrcp_message.h" #include "mrcp_generic_header.h" #include "mrcp_verifier_header.h" #include "mrcp_verifier_resource.h" #include "apt_nlsml_doc.h" #include "apt_log.h" struct VerifierChannel { /** MRCP control channel */ mrcp_channel_t* m_pMrcpChannel; /** IN-PROGRESS VERIFY request */ mrcp_message_t* m_pVerificationRequest; /** Streaming is in-progress */ bool m_Streaming; /** File to read audio stream from */ FILE* m_pAudioIn; /** Estimated time to complete (used if no audio_in available) */ apr_size_t m_TimeToComplete; VerifierChannel() : m_pMrcpChannel(NULL), m_pVerificationRequest(NULL), m_Streaming(false), m_pAudioIn(NULL), m_TimeToComplete(0) {} }; VerifierSession::VerifierSession(const VerifierScenario* pScenario) : UmcSession(pScenario), m_pVerifierChannel(NULL), m_ContentId("request1@form-level") { } VerifierSession::~VerifierSession() { } bool VerifierSession::Start() { /* create channel and associate all the required data */ m_pVerifierChannel = CreateVerifierChannel(); if(!m_pVerifierChannel) return false; /* add channel to session (send asynchronous request) */ if(!AddMrcpChannel(m_pVerifierChannel->m_pMrcpChannel)) { delete m_pVerifierChannel; m_pVerifierChannel = NULL; return false; } return true; } bool VerifierSession::Stop() { if(!UmcSession::Stop()) return false; if(!m_pVerifierChannel) return false; mrcp_message_t* pStopMessage = CreateMrcpMessage(m_pVerifierChannel->m_pMrcpChannel,VERIFIER_STOP); if(!pStopMessage) return false; if(m_pVerifierChannel->m_pVerificationRequest) { mrcp_generic_header_t* pGenericHeader; /* get/allocate generic header */ pGenericHeader = (mrcp_generic_header_t*) mrcp_generic_header_prepare(pStopMessage); if(pGenericHeader) { pGenericHeader->active_request_id_list.count = 1; pGenericHeader->active_request_id_list.ids[0] = m_pVerifierChannel->m_pVerificationRequest->start_line.request_id; mrcp_generic_header_property_add(pStopMessage,GENERIC_HEADER_ACTIVE_REQUEST_ID_LIST); } m_pVerifierChannel->m_pVerificationRequest = NULL; } return SendMrcpRequest(m_pVerifierChannel->m_pMrcpChannel,pStopMessage); } bool VerifierSession::OnSessionTerminate(mrcp_sig_status_code_e status) { if(m_pVerifierChannel) { FILE* pAudioIn = m_pVerifierChannel->m_pAudioIn; if(pAudioIn) { m_pVerifierChannel->m_pAudioIn = NULL; fclose(pAudioIn); } delete m_pVerifierChannel; m_pVerifierChannel = NULL; } return UmcSession::OnSessionTerminate(status); } static apt_bool_t ReadStream(mpf_audio_stream_t* pStream, mpf_frame_t* pFrame) { VerifierChannel* pVerifierChannel = (VerifierChannel*) pStream->obj; if(pVerifierChannel && pVerifierChannel->m_Streaming) { if(pVerifierChannel->m_pAudioIn) { if(fread(pFrame->codec_frame.buffer,1,pFrame->codec_frame.size,pVerifierChannel->m_pAudioIn) == pFrame->codec_frame.size) { /* normal read */ pFrame->type |= MEDIA_FRAME_TYPE_AUDIO; } else { /* file is over */ pVerifierChannel->m_Streaming = false; } } else { /* fill with silence in case no file available */ if(pVerifierChannel->m_TimeToComplete >= CODEC_FRAME_TIME_BASE) { pFrame->type |= MEDIA_FRAME_TYPE_AUDIO; memset(pFrame->codec_frame.buffer,0,pFrame->codec_frame.size); pVerifierChannel->m_TimeToComplete -= CODEC_FRAME_TIME_BASE; } else { pVerifierChannel->m_Streaming = false; } } } return TRUE; } VerifierChannel* VerifierSession::CreateVerifierChannel() { mrcp_channel_t* pChannel; mpf_termination_t* pTermination; mpf_stream_capabilities_t* pCapabilities; apr_pool_t* pool = GetSessionPool(); /* create channel */ VerifierChannel* pVerifierChannel = new VerifierChannel; /* create source stream capabilities */ pCapabilities = mpf_source_stream_capabilities_create(pool); GetScenario()->InitCapabilities(pCapabilities); static const mpf_audio_stream_vtable_t audio_stream_vtable = { NULL, NULL, NULL, ReadStream, NULL, NULL, NULL }; pTermination = CreateAudioTermination( &audio_stream_vtable, /* virtual methods table of audio stream */ pCapabilities, /* capabilities of audio stream */ pVerifierChannel); /* object to associate */ pChannel = CreateMrcpChannel( MRCP_VERIFIER_RESOURCE, /* MRCP resource identifier */ pTermination, /* media termination, used to terminate audio stream */ NULL, /* RTP descriptor, used to create RTP termination (NULL by default) */ pVerifierChannel); /* object to associate */ if(!pChannel) { delete pVerifierChannel; return NULL; } pVerifierChannel->m_pMrcpChannel = pChannel; return pVerifierChannel; } bool VerifierSession::OnChannelAdd(mrcp_channel_t* pMrcpChannel, mrcp_sig_status_code_e status) { if(!UmcSession::OnChannelAdd(pMrcpChannel,status)) return false; if(status != MRCP_SIG_STATUS_CODE_SUCCESS) { /* error case, just terminate the demo */ return Terminate(); } return StartVerification(pMrcpChannel); } bool VerifierSession::OnMessageReceive(mrcp_channel_t* pMrcpChannel, mrcp_message_t* pMrcpMessage) { if(!UmcSession::OnMessageReceive(pMrcpChannel,pMrcpMessage)) return false; VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); if(pMrcpMessage->start_line.message_type == MRCP_MESSAGE_TYPE_RESPONSE) { /* received MRCP response */ if(pMrcpMessage->start_line.method_id == VERIFIER_START_SESSION) { /* received the response to START-SESSION request */ /* create and send VERIFY request */ mrcp_message_t* pMrcpMessage = CreateVerificationRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } } else if(pMrcpMessage->start_line.method_id == VERIFIER_END_SESSION) { /* received the response to END-SESSION request */ Terminate(); } else if(pMrcpMessage->start_line.method_id == VERIFIER_VERIFY) { /* received the response to VERIFY request */ if(pMrcpMessage->start_line.request_state == MRCP_REQUEST_STATE_INPROGRESS) { VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); if(pVerifierChannel) pVerifierChannel->m_pVerificationRequest = GetMrcpMessage(); /* start to stream the speech to Verifiernize */ if(pVerifierChannel) pVerifierChannel->m_Streaming = true; } else { /* create and send END-SESSION request */ mrcp_message_t* pMrcpMessage = CreateEndSessionRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } } } else { /* received unexpected response */ } } else if(pMrcpMessage->start_line.message_type == MRCP_MESSAGE_TYPE_EVENT) { if(pMrcpMessage->start_line.method_id == VERIFIER_VERIFICATION_COMPLETE) { if(pVerifierChannel) pVerifierChannel->m_Streaming = false; VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); if(pVerifierChannel) pVerifierChannel->m_pVerificationRequest = NULL; /* create and send END-SESSION request */ mrcp_message_t* pMrcpMessage = CreateEndSessionRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } } else if(pMrcpMessage->start_line.method_id == VERIFIER_START_OF_INPUT) { /* received start-of-input, do whatever you need here */ } } return true; } bool VerifierSession::StartVerification(mrcp_channel_t* pMrcpChannel) { VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); /* create and send Verification request */ mrcp_message_t* pMrcpMessage = CreateStartSessionRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } const mpf_codec_descriptor_t* pDescriptor = mrcp_application_source_descriptor_get(pMrcpChannel); pVerifierChannel->m_pAudioIn = GetAudioIn(pDescriptor,GetSessionPool()); if(!pVerifierChannel->m_pAudioIn) { /* no audio input availble, set some estimated time to complete instead */ pVerifierChannel->m_TimeToComplete = 5000; // 5 sec } return true; } mrcp_message_t* VerifierSession::CreateStartSessionRequest(mrcp_channel_t* pMrcpChannel) { mrcp_message_t* pMrcpMessage = CreateMrcpMessage(pMrcpChannel,VERIFIER_START_SESSION); if(!pMrcpMessage) return NULL; mrcp_verifier_header_t* pVerifierHeader; /* get/allocate verifier header */ pVerifierHeader = (mrcp_verifier_header_t*) mrcp_resource_header_prepare(pMrcpMessage); if(pVerifierHeader) { const VerifierScenario* pScenario = GetScenario(); const char* pRepositoryURI = pScenario->GetRepositoryURI(); if(pRepositoryURI) { apt_string_set(&pVerifierHeader->repository_uri,pRepositoryURI); mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_REPOSITORY_URI); } const char* pVoiceprintIdentifier = pScenario->GetVoiceprintIdentifier(); if(pVoiceprintIdentifier) { apt_string_set(&pVerifierHeader->voiceprint_identifier,pVoiceprintIdentifier); mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_VOICEPRINT_IDENTIFIER); } const char* pVerificationMode = pScenario->GetVerificationMode(); if(pVerificationMode) { apt_string_set(&pVerifierHeader->verification_mode,pVerificationMode); mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_VERIFICATION_MODE); } } return pMrcpMessage; } mrcp_message_t* VerifierSession::CreateEndSessionRequest(mrcp_channel_t* pMrcpChannel) { return CreateMrcpMessage(pMrcpChannel,VERIFIER_END_SESSION); } mrcp_message_t* VerifierSession::CreateVerificationRequest(mrcp_channel_t* pMrcpChannel) { mrcp_message_t* pMrcpMessage = CreateMrcpMessage(pMrcpChannel,VERIFIER_VERIFY); if(!pMrcpMessage) return NULL; mrcp_verifier_header_t* pVerifierHeader; /* get/allocate verifier header */ pVerifierHeader = (mrcp_verifier_header_t*) mrcp_resource_header_prepare(pMrcpMessage); if(pVerifierHeader) { pVerifierHeader->no_input_timeout = 5000; mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_NO_INPUT_TIMEOUT); pVerifierHeader->start_input_timers = TRUE; mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_START_INPUT_TIMERS); } return pMrcpMessage; } FILE* VerifierSession::GetAudioIn(const mpf_codec_descriptor_t* pDescriptor, apr_pool_t* pool) const { const VerifierScenario* pScenario = GetScenario(); const char* pVoiceprintIdentifier = pScenario->GetVoiceprintIdentifier(); if(!pVoiceprintIdentifier) { apt_log(APT_LOG_MARK,APT_PRIO_WARNING,"No Voiceprint Specified"); return NULL; } const char* pFileName = apr_psprintf(pool,"%s-%dkHz.pcm", pVoiceprintIdentifier, pDescriptor ? pDescriptor->sampling_rate/1000 : 8); apt_dir_layout_t* pDirLayout = pScenario->GetDirLayout(); const char* pFilePath = apt_datadir_filepath_get(pDirLayout,pFileName,pool); if(!pFilePath) return NULL; FILE* pFile = fopen(pFilePath,"rb"); if(!pFile) { apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Cannot Find [%s]",pFilePath); return NULL; } apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Set [%s] as Speech Source",pFilePath); return pFile; } <commit_msg>STOP request for the verifier resource should contain no active-request-id list<commit_after>/* * Copyright 2008-2010 Arsen Chaloyan * * 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. * * $Id$ */ #include "verifiersession.h" #include "verifierscenario.h" #include "mrcp_message.h" #include "mrcp_generic_header.h" #include "mrcp_verifier_header.h" #include "mrcp_verifier_resource.h" #include "apt_nlsml_doc.h" #include "apt_log.h" struct VerifierChannel { /** MRCP control channel */ mrcp_channel_t* m_pMrcpChannel; /** IN-PROGRESS VERIFY request */ mrcp_message_t* m_pVerificationRequest; /** Streaming is in-progress */ bool m_Streaming; /** File to read audio stream from */ FILE* m_pAudioIn; /** Estimated time to complete (used if no audio_in available) */ apr_size_t m_TimeToComplete; VerifierChannel() : m_pMrcpChannel(NULL), m_pVerificationRequest(NULL), m_Streaming(false), m_pAudioIn(NULL), m_TimeToComplete(0) {} }; VerifierSession::VerifierSession(const VerifierScenario* pScenario) : UmcSession(pScenario), m_pVerifierChannel(NULL), m_ContentId("request1@form-level") { } VerifierSession::~VerifierSession() { } bool VerifierSession::Start() { /* create channel and associate all the required data */ m_pVerifierChannel = CreateVerifierChannel(); if(!m_pVerifierChannel) return false; /* add channel to session (send asynchronous request) */ if(!AddMrcpChannel(m_pVerifierChannel->m_pMrcpChannel)) { delete m_pVerifierChannel; m_pVerifierChannel = NULL; return false; } return true; } bool VerifierSession::Stop() { if(!UmcSession::Stop()) return false; if(!m_pVerifierChannel) return false; mrcp_message_t* pStopMessage = CreateMrcpMessage(m_pVerifierChannel->m_pMrcpChannel,VERIFIER_STOP); if(!pStopMessage) return false; return SendMrcpRequest(m_pVerifierChannel->m_pMrcpChannel,pStopMessage); } bool VerifierSession::OnSessionTerminate(mrcp_sig_status_code_e status) { if(m_pVerifierChannel) { FILE* pAudioIn = m_pVerifierChannel->m_pAudioIn; if(pAudioIn) { m_pVerifierChannel->m_pAudioIn = NULL; fclose(pAudioIn); } delete m_pVerifierChannel; m_pVerifierChannel = NULL; } return UmcSession::OnSessionTerminate(status); } static apt_bool_t ReadStream(mpf_audio_stream_t* pStream, mpf_frame_t* pFrame) { VerifierChannel* pVerifierChannel = (VerifierChannel*) pStream->obj; if(pVerifierChannel && pVerifierChannel->m_Streaming) { if(pVerifierChannel->m_pAudioIn) { if(fread(pFrame->codec_frame.buffer,1,pFrame->codec_frame.size,pVerifierChannel->m_pAudioIn) == pFrame->codec_frame.size) { /* normal read */ pFrame->type |= MEDIA_FRAME_TYPE_AUDIO; } else { /* file is over */ pVerifierChannel->m_Streaming = false; } } else { /* fill with silence in case no file available */ if(pVerifierChannel->m_TimeToComplete >= CODEC_FRAME_TIME_BASE) { pFrame->type |= MEDIA_FRAME_TYPE_AUDIO; memset(pFrame->codec_frame.buffer,0,pFrame->codec_frame.size); pVerifierChannel->m_TimeToComplete -= CODEC_FRAME_TIME_BASE; } else { pVerifierChannel->m_Streaming = false; } } } return TRUE; } VerifierChannel* VerifierSession::CreateVerifierChannel() { mrcp_channel_t* pChannel; mpf_termination_t* pTermination; mpf_stream_capabilities_t* pCapabilities; apr_pool_t* pool = GetSessionPool(); /* create channel */ VerifierChannel* pVerifierChannel = new VerifierChannel; /* create source stream capabilities */ pCapabilities = mpf_source_stream_capabilities_create(pool); GetScenario()->InitCapabilities(pCapabilities); static const mpf_audio_stream_vtable_t audio_stream_vtable = { NULL, NULL, NULL, ReadStream, NULL, NULL, NULL }; pTermination = CreateAudioTermination( &audio_stream_vtable, /* virtual methods table of audio stream */ pCapabilities, /* capabilities of audio stream */ pVerifierChannel); /* object to associate */ pChannel = CreateMrcpChannel( MRCP_VERIFIER_RESOURCE, /* MRCP resource identifier */ pTermination, /* media termination, used to terminate audio stream */ NULL, /* RTP descriptor, used to create RTP termination (NULL by default) */ pVerifierChannel); /* object to associate */ if(!pChannel) { delete pVerifierChannel; return NULL; } pVerifierChannel->m_pMrcpChannel = pChannel; return pVerifierChannel; } bool VerifierSession::OnChannelAdd(mrcp_channel_t* pMrcpChannel, mrcp_sig_status_code_e status) { if(!UmcSession::OnChannelAdd(pMrcpChannel,status)) return false; if(status != MRCP_SIG_STATUS_CODE_SUCCESS) { /* error case, just terminate the demo */ return Terminate(); } return StartVerification(pMrcpChannel); } bool VerifierSession::OnMessageReceive(mrcp_channel_t* pMrcpChannel, mrcp_message_t* pMrcpMessage) { if(!UmcSession::OnMessageReceive(pMrcpChannel,pMrcpMessage)) return false; VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); if(pMrcpMessage->start_line.message_type == MRCP_MESSAGE_TYPE_RESPONSE) { /* received MRCP response */ if(pMrcpMessage->start_line.method_id == VERIFIER_START_SESSION) { /* received the response to START-SESSION request */ /* create and send VERIFY request */ mrcp_message_t* pMrcpMessage = CreateVerificationRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } } else if(pMrcpMessage->start_line.method_id == VERIFIER_END_SESSION) { /* received the response to END-SESSION request */ Terminate(); } else if(pMrcpMessage->start_line.method_id == VERIFIER_VERIFY) { /* received the response to VERIFY request */ if(pMrcpMessage->start_line.request_state == MRCP_REQUEST_STATE_INPROGRESS) { VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); if(pVerifierChannel) pVerifierChannel->m_pVerificationRequest = GetMrcpMessage(); /* start to stream the speech to Verify */ if(pVerifierChannel) pVerifierChannel->m_Streaming = true; } else { /* create and send END-SESSION request */ mrcp_message_t* pMrcpMessage = CreateEndSessionRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } } } else { /* received unexpected response */ } } else if(pMrcpMessage->start_line.message_type == MRCP_MESSAGE_TYPE_EVENT) { if(pMrcpMessage->start_line.method_id == VERIFIER_VERIFICATION_COMPLETE) { if(pVerifierChannel) pVerifierChannel->m_Streaming = false; VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); if(pVerifierChannel) pVerifierChannel->m_pVerificationRequest = NULL; /* create and send END-SESSION request */ mrcp_message_t* pMrcpMessage = CreateEndSessionRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } } else if(pMrcpMessage->start_line.method_id == VERIFIER_START_OF_INPUT) { /* received start-of-input, do whatever you need here */ } } return true; } bool VerifierSession::StartVerification(mrcp_channel_t* pMrcpChannel) { VerifierChannel* pVerifierChannel = (VerifierChannel*) mrcp_application_channel_object_get(pMrcpChannel); /* create and send Verification request */ mrcp_message_t* pMrcpMessage = CreateStartSessionRequest(pMrcpChannel); if(pMrcpMessage) { SendMrcpRequest(pVerifierChannel->m_pMrcpChannel,pMrcpMessage); } const mpf_codec_descriptor_t* pDescriptor = mrcp_application_source_descriptor_get(pMrcpChannel); pVerifierChannel->m_pAudioIn = GetAudioIn(pDescriptor,GetSessionPool()); if(!pVerifierChannel->m_pAudioIn) { /* no audio input availble, set some estimated time to complete instead */ pVerifierChannel->m_TimeToComplete = 5000; // 5 sec } return true; } mrcp_message_t* VerifierSession::CreateStartSessionRequest(mrcp_channel_t* pMrcpChannel) { mrcp_message_t* pMrcpMessage = CreateMrcpMessage(pMrcpChannel,VERIFIER_START_SESSION); if(!pMrcpMessage) return NULL; mrcp_verifier_header_t* pVerifierHeader; /* get/allocate verifier header */ pVerifierHeader = (mrcp_verifier_header_t*) mrcp_resource_header_prepare(pMrcpMessage); if(pVerifierHeader) { const VerifierScenario* pScenario = GetScenario(); const char* pRepositoryURI = pScenario->GetRepositoryURI(); if(pRepositoryURI) { apt_string_set(&pVerifierHeader->repository_uri,pRepositoryURI); mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_REPOSITORY_URI); } const char* pVoiceprintIdentifier = pScenario->GetVoiceprintIdentifier(); if(pVoiceprintIdentifier) { apt_string_set(&pVerifierHeader->voiceprint_identifier,pVoiceprintIdentifier); mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_VOICEPRINT_IDENTIFIER); } const char* pVerificationMode = pScenario->GetVerificationMode(); if(pVerificationMode) { apt_string_set(&pVerifierHeader->verification_mode,pVerificationMode); mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_VERIFICATION_MODE); } } return pMrcpMessage; } mrcp_message_t* VerifierSession::CreateEndSessionRequest(mrcp_channel_t* pMrcpChannel) { return CreateMrcpMessage(pMrcpChannel,VERIFIER_END_SESSION); } mrcp_message_t* VerifierSession::CreateVerificationRequest(mrcp_channel_t* pMrcpChannel) { mrcp_message_t* pMrcpMessage = CreateMrcpMessage(pMrcpChannel,VERIFIER_VERIFY); if(!pMrcpMessage) return NULL; mrcp_verifier_header_t* pVerifierHeader; /* get/allocate verifier header */ pVerifierHeader = (mrcp_verifier_header_t*) mrcp_resource_header_prepare(pMrcpMessage); if(pVerifierHeader) { pVerifierHeader->no_input_timeout = 5000; mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_NO_INPUT_TIMEOUT); pVerifierHeader->start_input_timers = TRUE; mrcp_resource_header_property_add(pMrcpMessage,VERIFIER_HEADER_START_INPUT_TIMERS); } return pMrcpMessage; } FILE* VerifierSession::GetAudioIn(const mpf_codec_descriptor_t* pDescriptor, apr_pool_t* pool) const { const VerifierScenario* pScenario = GetScenario(); const char* pVoiceprintIdentifier = pScenario->GetVoiceprintIdentifier(); if(!pVoiceprintIdentifier) { apt_log(APT_LOG_MARK,APT_PRIO_WARNING,"No Voiceprint Specified"); return NULL; } const char* pFileName = apr_psprintf(pool,"%s-%dkHz.pcm", pVoiceprintIdentifier, pDescriptor ? pDescriptor->sampling_rate/1000 : 8); apt_dir_layout_t* pDirLayout = pScenario->GetDirLayout(); const char* pFilePath = apt_datadir_filepath_get(pDirLayout,pFileName,pool); if(!pFilePath) return NULL; FILE* pFile = fopen(pFilePath,"rb"); if(!pFile) { apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Cannot Find [%s]",pFilePath); return NULL; } apt_log(APT_LOG_MARK,APT_PRIO_INFO,"Set [%s] as Speech Source",pFilePath); return pFile; } <|endoftext|>
<commit_before>#include <errno.h> // errno #include <pthread.h> #include <stdio.h> // TODO - Remove #include <string.h> // strerror #include <sys/epoll.h> #include <unistd.h> #include <map> #include <list> #include <uv.h> #include <v8.h> #include <node.h> #include <node_object_wrap.h> #include <nan.h> #include "epoll.h" using namespace v8; // TODO - strerror isn't threadsafe, use strerror_r instead // TODO - use uv_strerror rather than strerror_t for libuv errors // TODO - Tidy up thread stuff and global vars /* * Watcher thread */ // TODO - The variable names here look terrible static int watcher_epfd_g; static uv_sem_t watcher_sem_g; static uv_async_t watcher_async_g; static struct epoll_event watcher_event_g; static int watcher_errno_g; static void *watcher(void *arg) { while (true) { // Wait till the event loop says it's ok to poll. uv_sem_wait(&watcher_sem_g); int count = epoll_wait(watcher_epfd_g, &watcher_event_g, 1, -1); watcher_errno_g = count == -1 ? errno : 0; // Errors returned from uv_async_send are silently ignored. uv_async_send(&watcher_async_g); } return 0; } // TODO - start_watcher looks terrible. static void start_watcher() { pthread_t theread_id; // TODO - Create a method callable from JS for starting the thread so that // it's possible to pass arguments to epoll_create1 and pass errors back to // JS. watcher_epfd_g = epoll_create1(0); if (watcher_epfd_g == -1) { printf("%s\n", strerror(errno)); return; } int err = uv_sem_init(&watcher_sem_g, 1); if (err < 0) { close(watcher_epfd_g); printf("%s\n", strerror(-err)); return; } err = uv_async_init(uv_default_loop(), &watcher_async_g, Epoll::DispatchEvent); if (err < 0) { close(watcher_epfd_g); uv_sem_destroy(&watcher_sem_g); printf("%s\n", strerror(-err)); return; } // Prevent watcher_async_g from keeping the event loop alive. uv_unref((uv_handle_t *) &watcher_async_g); err = pthread_create(&theread_id, 0, watcher, 0); if (err != 0) { close(watcher_epfd_g); uv_sem_destroy(&watcher_sem_g); uv_close((uv_handle_t *) &watcher_async_g, 0); printf("%s\n", strerror(err)); return; } } /* * Epoll */ Persistent<FunctionTemplate> Epoll::constructor; std::map<int, Epoll*> Epoll::fd2epoll; Epoll::Epoll(NanCallback *callback) : callback_(callback), closed_(false) { }; Epoll::~Epoll() { // v8 decides when and if destructors are called. In particular, if the // process is about to terminate, it's highly likely that destructors will // not be called. This is therefore not the place for calling the likes of // uv_unref, which, in general, must be called to terminate a process // gracefully! NanScope(); if (callback_) delete callback_; }; void Epoll::Init(Handle<Object> exports) { NanScope(); // Constructor Local<FunctionTemplate> ctor = FunctionTemplate::New(Epoll::New); NanAssignPersistent(FunctionTemplate, constructor, ctor); ctor->SetClassName(NanSymbol("Epoll")); ctor->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(ctor, "add", Add); NODE_SET_PROTOTYPE_METHOD(ctor, "modify", Modify); NODE_SET_PROTOTYPE_METHOD(ctor, "remove", Remove); NODE_SET_PROTOTYPE_METHOD(ctor, "close", Close); NODE_DEFINE_CONSTANT(ctor, EPOLLIN); NODE_DEFINE_CONSTANT(ctor, EPOLLOUT); NODE_DEFINE_CONSTANT(ctor, EPOLLRDHUP); NODE_DEFINE_CONSTANT(ctor, EPOLLPRI); // The reason this addon exists! NODE_DEFINE_CONSTANT(ctor, EPOLLERR); NODE_DEFINE_CONSTANT(ctor, EPOLLHUP); NODE_DEFINE_CONSTANT(ctor, EPOLLET); NODE_DEFINE_CONSTANT(ctor, EPOLLONESHOT); exports->Set(NanSymbol("Epoll"), ctor->GetFunction()); } NAN_METHOD(Epoll::New) { NanScope(); // TODO - Can throw be avoided here? Maybe with a default empty handler? if (args.Length() < 1 || !args[0]->IsFunction()) return NanThrowError("First argument to construtor must be a callback"); NanCallback *callback = new NanCallback(Local<Function>::Cast(args[0])); Epoll *epoll = new Epoll(callback); epoll->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Add) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("add can't be called after close has been called"); if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsUint32()) return NanThrowError("incorrect arguments passed to add(int fd, uint32_t events)"); int err = epoll->Add(args[0]->Int32Value(), args[1]->Uint32Value()); if (err != 0) return NanThrowError(strerror(err), err); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Modify) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("modify can't be called after close has been called"); if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsUint32()) return NanThrowError("incorrect arguments passed to maodify(int fd, uint32_t events)"); int err = epoll->Modify(args[0]->Int32Value(), args[1]->Uint32Value()); if (err != 0) return NanThrowError(strerror(err), err); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Remove) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("remove can't be called after close has been called"); if (args.Length() < 1 || !args[0]->IsInt32()) return NanThrowError("incorrect arguments passed to remove(int fd)"); int err = epoll->Remove(args[0]->Int32Value()); if (err != 0) return NanThrowError(strerror(err), err); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Close) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("close can't be called more than once"); int err = epoll->Close(); if (err != 0) return NanThrowError(strerror(err), err); NanReturnNull(); } int Epoll::Add(int fd, uint32_t events) { struct epoll_event event; event.events = events; // EPOLLIN; // EPOLLPRI; event.data.fd = fd; if (epoll_ctl(watcher_epfd_g, EPOLL_CTL_ADD, fd, &event) == -1) return errno; fd2epoll.insert(std::pair<int, Epoll*>(fd, this)); // TODO - Error handling, fd may not be there. fds_.push_back(fd); // TODO - Error handling, fd may not be there. // Keep event loop alive. uv_unref called in Remove. uv_ref((uv_handle_t *) &watcher_async_g); return 0; } int Epoll::Modify(int fd, uint32_t events) { struct epoll_event event; event.events = events; event.data.fd = fd; if (epoll_ctl(watcher_epfd_g, EPOLL_CTL_MOD, fd, &event) == -1) return errno; fd2epoll.insert(std::pair<int, Epoll*>(fd, this)); // TODO - Error handling, fd may not be there. fds_.push_back(fd); // TODO - Error handling, fd may not be there. // Keep event loop alive. uv_unref called in Remove. uv_ref((uv_handle_t *) &watcher_async_g); return 0; } int Epoll::Remove(int fd) { if (epoll_ctl(watcher_epfd_g, EPOLL_CTL_DEL, fd, 0) == -1) return errno; fd2epoll.erase(fd); // TODO - Error handling, fd may not be there. fds_.remove(fd); // TODO - Error handling, fd may not be there. if (fd2epoll.empty()) uv_unref((uv_handle_t *) &watcher_async_g); return 0; } int Epoll::Close() { closed_ = true; delete callback_; callback_ = 0; std::list<int>::iterator it = fds_.begin(); while (it != fds_.end()) { int err = Remove(*it); if (err != 0) return err; // TODO - Returning here leaves things messed up. it = fds_.begin(); } return 0; } void Epoll::DispatchEvent(uv_async_t* handle, int status) { // This method is executed in the event loop thread. // By the time flow of control arrives here the original Epoll instance that // registered interest in the event may no longer have this interest. If // this is the case, the event will silently be ignored. std::map<int, Epoll*>::iterator it = fd2epoll.find(watcher_event_g.data.fd); if (it != fd2epoll.end()) { it->second->DispatchEvent(watcher_errno_g, &watcher_event_g); } else { printf("lost interest in %d\n", watcher_event_g.data.fd); // TODO - Remove printf. } uv_sem_post(&watcher_sem_g); } void Epoll::DispatchEvent(int err, struct epoll_event *event) { NanScope(); if (err) { Local<Value> args[1] = { Exception::Error(String::New(strerror(err))) }; callback_->Call(1, args); } else { Local<Value> args[3] = { Local<Value>::New(Null()), Integer::New(event->data.fd), Integer::New(event->events) }; callback_->Call(3, args); } } extern "C" void Init(Handle<Object> exports) { NanScope(); Epoll::Init(exports); // TODO - Allow JavaScript to start the thread start_watcher(); } NODE_MODULE(epoll, Init) <commit_msg>allow installation on non-Linux systems but provide no functionality (needed for firmata-pi tests)<commit_after>#ifdef __linux__ #include <errno.h> // errno #include <pthread.h> #include <stdio.h> // TODO - Remove #include <string.h> // strerror #include <sys/epoll.h> #include <unistd.h> #include <map> #include <list> #include <uv.h> #include <v8.h> #include <node.h> #include <node_object_wrap.h> #include <nan.h> #include "epoll.h" using namespace v8; // TODO - strerror isn't threadsafe, use strerror_r instead // TODO - use uv_strerror rather than strerror_t for libuv errors // TODO - Tidy up thread stuff and global vars /* * Watcher thread */ // TODO - The variable names here look terrible static int watcher_epfd_g; static uv_sem_t watcher_sem_g; static uv_async_t watcher_async_g; static struct epoll_event watcher_event_g; static int watcher_errno_g; static void *watcher(void *arg) { while (true) { // Wait till the event loop says it's ok to poll. uv_sem_wait(&watcher_sem_g); int count = epoll_wait(watcher_epfd_g, &watcher_event_g, 1, -1); watcher_errno_g = count == -1 ? errno : 0; // Errors returned from uv_async_send are silently ignored. uv_async_send(&watcher_async_g); } return 0; } // TODO - start_watcher looks terrible. static void start_watcher() { pthread_t theread_id; // TODO - Create a method callable from JS for starting the thread so that // it's possible to pass arguments to epoll_create1 and pass errors back to // JS. watcher_epfd_g = epoll_create1(0); if (watcher_epfd_g == -1) { printf("%s\n", strerror(errno)); return; } int err = uv_sem_init(&watcher_sem_g, 1); if (err < 0) { close(watcher_epfd_g); printf("%s\n", strerror(-err)); return; } err = uv_async_init(uv_default_loop(), &watcher_async_g, Epoll::DispatchEvent); if (err < 0) { close(watcher_epfd_g); uv_sem_destroy(&watcher_sem_g); printf("%s\n", strerror(-err)); return; } // Prevent watcher_async_g from keeping the event loop alive. uv_unref((uv_handle_t *) &watcher_async_g); err = pthread_create(&theread_id, 0, watcher, 0); if (err != 0) { close(watcher_epfd_g); uv_sem_destroy(&watcher_sem_g); uv_close((uv_handle_t *) &watcher_async_g, 0); printf("%s\n", strerror(err)); return; } } /* * Epoll */ Persistent<FunctionTemplate> Epoll::constructor; std::map<int, Epoll*> Epoll::fd2epoll; Epoll::Epoll(NanCallback *callback) : callback_(callback), closed_(false) { }; Epoll::~Epoll() { // v8 decides when and if destructors are called. In particular, if the // process is about to terminate, it's highly likely that destructors will // not be called. This is therefore not the place for calling the likes of // uv_unref, which, in general, must be called to terminate a process // gracefully! NanScope(); if (callback_) delete callback_; }; void Epoll::Init(Handle<Object> exports) { NanScope(); // Constructor Local<FunctionTemplate> ctor = FunctionTemplate::New(Epoll::New); NanAssignPersistent(FunctionTemplate, constructor, ctor); ctor->SetClassName(NanSymbol("Epoll")); ctor->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(ctor, "add", Add); NODE_SET_PROTOTYPE_METHOD(ctor, "modify", Modify); NODE_SET_PROTOTYPE_METHOD(ctor, "remove", Remove); NODE_SET_PROTOTYPE_METHOD(ctor, "close", Close); NODE_DEFINE_CONSTANT(ctor, EPOLLIN); NODE_DEFINE_CONSTANT(ctor, EPOLLOUT); NODE_DEFINE_CONSTANT(ctor, EPOLLRDHUP); NODE_DEFINE_CONSTANT(ctor, EPOLLPRI); // The reason this addon exists! NODE_DEFINE_CONSTANT(ctor, EPOLLERR); NODE_DEFINE_CONSTANT(ctor, EPOLLHUP); NODE_DEFINE_CONSTANT(ctor, EPOLLET); NODE_DEFINE_CONSTANT(ctor, EPOLLONESHOT); exports->Set(NanSymbol("Epoll"), ctor->GetFunction()); } NAN_METHOD(Epoll::New) { NanScope(); // TODO - Can throw be avoided here? Maybe with a default empty handler? if (args.Length() < 1 || !args[0]->IsFunction()) return NanThrowError("First argument to construtor must be a callback"); NanCallback *callback = new NanCallback(Local<Function>::Cast(args[0])); Epoll *epoll = new Epoll(callback); epoll->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Add) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("add can't be called after close has been called"); if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsUint32()) return NanThrowError("incorrect arguments passed to add(int fd, uint32_t events)"); int err = epoll->Add(args[0]->Int32Value(), args[1]->Uint32Value()); if (err != 0) return NanThrowError(strerror(err), err); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Modify) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("modify can't be called after close has been called"); if (args.Length() < 2 || !args[0]->IsInt32() || !args[1]->IsUint32()) return NanThrowError("incorrect arguments passed to maodify(int fd, uint32_t events)"); int err = epoll->Modify(args[0]->Int32Value(), args[1]->Uint32Value()); if (err != 0) return NanThrowError(strerror(err), err); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Remove) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("remove can't be called after close has been called"); if (args.Length() < 1 || !args[0]->IsInt32()) return NanThrowError("incorrect arguments passed to remove(int fd)"); int err = epoll->Remove(args[0]->Int32Value()); if (err != 0) return NanThrowError(strerror(err), err); NanReturnValue(args.This()); } NAN_METHOD(Epoll::Close) { NanScope(); Epoll *epoll = ObjectWrap::Unwrap<Epoll>(args.This()); if (epoll->closed_) return NanThrowError("close can't be called more than once"); int err = epoll->Close(); if (err != 0) return NanThrowError(strerror(err), err); NanReturnNull(); } int Epoll::Add(int fd, uint32_t events) { struct epoll_event event; event.events = events; // EPOLLIN; // EPOLLPRI; event.data.fd = fd; if (epoll_ctl(watcher_epfd_g, EPOLL_CTL_ADD, fd, &event) == -1) return errno; fd2epoll.insert(std::pair<int, Epoll*>(fd, this)); // TODO - Error handling, fd may not be there. fds_.push_back(fd); // TODO - Error handling, fd may not be there. // Keep event loop alive. uv_unref called in Remove. uv_ref((uv_handle_t *) &watcher_async_g); return 0; } int Epoll::Modify(int fd, uint32_t events) { struct epoll_event event; event.events = events; event.data.fd = fd; if (epoll_ctl(watcher_epfd_g, EPOLL_CTL_MOD, fd, &event) == -1) return errno; fd2epoll.insert(std::pair<int, Epoll*>(fd, this)); // TODO - Error handling, fd may not be there. fds_.push_back(fd); // TODO - Error handling, fd may not be there. // Keep event loop alive. uv_unref called in Remove. uv_ref((uv_handle_t *) &watcher_async_g); return 0; } int Epoll::Remove(int fd) { if (epoll_ctl(watcher_epfd_g, EPOLL_CTL_DEL, fd, 0) == -1) return errno; fd2epoll.erase(fd); // TODO - Error handling, fd may not be there. fds_.remove(fd); // TODO - Error handling, fd may not be there. if (fd2epoll.empty()) uv_unref((uv_handle_t *) &watcher_async_g); return 0; } int Epoll::Close() { closed_ = true; delete callback_; callback_ = 0; std::list<int>::iterator it = fds_.begin(); while (it != fds_.end()) { int err = Remove(*it); if (err != 0) return err; // TODO - Returning here leaves things messed up. it = fds_.begin(); } return 0; } void Epoll::DispatchEvent(uv_async_t* handle, int status) { // This method is executed in the event loop thread. // By the time flow of control arrives here the original Epoll instance that // registered interest in the event may no longer have this interest. If // this is the case, the event will silently be ignored. std::map<int, Epoll*>::iterator it = fd2epoll.find(watcher_event_g.data.fd); if (it != fd2epoll.end()) { it->second->DispatchEvent(watcher_errno_g, &watcher_event_g); } else { printf("lost interest in %d\n", watcher_event_g.data.fd); // TODO - Remove printf. } uv_sem_post(&watcher_sem_g); } void Epoll::DispatchEvent(int err, struct epoll_event *event) { NanScope(); if (err) { Local<Value> args[1] = { Exception::Error(String::New(strerror(err))) }; callback_->Call(1, args); } else { Local<Value> args[3] = { Local<Value>::New(Null()), Integer::New(event->data.fd), Integer::New(event->events) }; callback_->Call(3, args); } } extern "C" void Init(Handle<Object> exports) { NanScope(); Epoll::Init(exports); // TODO - Allow JavaScript to start the thread start_watcher(); } NODE_MODULE(epoll, Init) #endif <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cstring> using namespace std; int main(int argc, char* argv[]){ bool isOn = true; //Keeps track of whether rshell is still running string usrInput; while(isOn){ cout << "$ "; //Prints prompt getline(cin, usrInput); char* inputCpy = new char[usrInput.length() + 1]; //pointer for input string strcpy(inputCpy, usrInput.c_str()); //token now holds c-string copy of input unsigned cnt = 0; //counter for slots in argv[] char* token = strtok(inputCpy, " ;"); //removes semicolons //argv[cnt] = token; //strcat(argv[cnt], "\0"); //cnt++; //incrememnts once to account for initial strok call //FIXME - How to separate different commands from each other? "ls -a; echo" shouldn't be // "ls -a echo", it should be "ls -a" and then "echo" while(token != NULL){ if(*token == '#'){ //Handles comments token = NULL; // }else if(token == "||"){ //Will Handle OR // }else if(token == "&&"){ //Will Handle AND }else{ //Default scenario //if(token == "exit") //Will handle exit cout << "Token: " << token << endl; argv[cnt] = token; strcat(argv[cnt], "\0"); //Null terminates the string token = strtok(NULL, " ;"); cnt++; } } argv[cnt] = token; strcat(argv[cnt], "\0"); cnt++; strcpy(argv[cnt], "\0"); //Null terminates argv[] for(unsigned i = 0; i < 10; i++){ cout << "Argv[" << i << "]: " << argv[i] << endl; //Fixme - remove later } int pid = fork(); //Forks the process if(pid == -1){ perror("fork() failed"); exit(1); }else if(pid == 0){ //Child process cout << "I'm a kid again!"; //Fixme - remove later if(execvp(argv[0], argv) == -1){ //Fixme - argv[0]=a.out; argv 1 or 0? perror("execvp() failed"); } exit(1); }else if(pid > 0){ //Parent function cout << "Get off my lawn!"; //Fixeme - remove later if(-1 == wait(0)){ //waits for child to finish before continuing perror("wait() failed"); } } } return 0; } //---------------------OLD CODE BELOW THIS LINE--------------------- //___ERROR LIST___ //test exit after commands //test semi-colons before/after commands //Prompt multi-prints when space-separated garbage is entered //Test with whitespace before/inbetween/after commands //Test touch with large, small, and symbol commands //Must work with &&'s and ||'s as connectors /* int main(int argc, char*argv[]){ bool isRunning = true; while(isRunning){ cout << "$"; //Prints the Prompt string input; getline(cin, input); if(input == "exit"){ //Exit Check cout << "Exiting rshell..." << endl; return 0; } int cnt = 0; char * tokInput = new char[input.size() + 1]; copy(input.begin(), input.end(), tokInput);//tokInput now = input tokInput[input.size()] = '\0'; //Null terminates array char* token = strtok(tokInput, ";"); //parses rawInput char* arr[] = strtok(tokInput, ";"); while(token != NULL){//Tokenization cout << "token: " << token << endl;//output - FIXME //if(*token == '#'){ //strcpy(argv[cnt], "\0"); //null terminates argv //token = NULL; } argv[cnt] = token;//places tokenized strings into argv strcat(argv[cnt], "\0");//adds null char to strings in argv token = strtok(NULL, " "); //looks for connectors cnt++; //increment count } //strcat(argv[cnt], "\0");//Null terminates argv[] for(int i = 0; i < cnt; i++){ //prints all values of argv[] - FIXME cout << "argv[" << i << "]: " << argv[i] << endl; } int pid = fork();//forks the process if(pid == 0){ //child process //if(execvp(argv[0], &argv[0]) == -1){ - Old if(execvp(argv[0], argv) == -1){ perror("execvp failure"); } exit(1); }else{ //parent if(-1 == wait(NULL)){ perror("wait() failure"); } } }//end isRunning loop return 0; } */ <commit_msg>Problem still exists with commands being strung together; backing up before I try some new things<commit_after>#include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cstring> using namespace std; int main(int argc, char* argv[]){ bool isOn = true; //Keeps track of whether rshell is still running string usrInput; while(isOn){ cout << "$ "; //Prints prompt getline(cin, usrInput); char* inputCpy = new char[usrInput.length() + 1]; //pointer for input string strcpy(inputCpy, usrInput.c_str()); //token now holds c-string copy of input unsigned cnt = 0; //counter for slots in argv[] char* token = strtok(inputCpy, " ;"); //removes semicolons //argv[cnt] = token; //strcat(argv[cnt], "\0"); //cnt++; //incrememnts once to account for initial strok call //FIXME - How to separate different commands from each other? "ls -a; echo" shouldn't be // "ls -a echo", it should be "ls -a" and then "echo" // It needs to null terminate argv[] after tokens are inserted while(token != NULL){ if(*token == '#'){ //Handles comments token = NULL; // }else if(token == "||"){ //Will Handle OR // }else if(token == "&&"){ //Will Handle AND }else{ //Default scenario //if(token == "exit") //Will handle exit cout << "Token: " << token << endl; argv[cnt] = token; strcat(argv[cnt], "\0"); //Null terminates the string token = strtok(NULL, " ;"); //Should it also remove ';'? cnt++; } } strcat(argv[cnt - 1], "\0"); argv[cnt] = token; //Should null term argv[], as token will equal NULL /* for(unsigned i = 0; i < 10; i++){ cout << "Argv[" << i << "]: " << argv[i] << endl; //Fixme - remove later } */ int pid = fork(); //Forks the process if(pid == -1){ perror("fork() failed"); exit(1); }else if(pid == 0){ //Child process cout << "I'm a kid again!"; //Fixme - remove later if(execvp(argv[0], argv) == -1){ //Fixme - argv[0]=a.out; argv 1 or 0? perror("execvp() failed"); } exit(1); }else if(pid > 0){ //Parent function cout << "Get off my lawn!"; //Fixeme - remove later if(-1 == wait(0)){ //waits for child to finish before continuing perror("wait() failed"); } } } return 0; } //---------------------OLD CODE BELOW THIS LINE--------------------- //___ERROR LIST___ //test exit after commands //test semi-colons before/after commands //Prompt multi-prints when space-separated garbage is entered //Test with whitespace before/inbetween/after commands //Test touch with large, small, and symbol commands //Must work with &&'s and ||'s as connectors /* int main(int argc, char*argv[]){ bool isRunning = true; while(isRunning){ cout << "$"; //Prints the Prompt string input; getline(cin, input); if(input == "exit"){ //Exit Check cout << "Exiting rshell..." << endl; return 0; } int cnt = 0; char * tokInput = new char[input.size() + 1]; copy(input.begin(), input.end(), tokInput);//tokInput now = input tokInput[input.size()] = '\0'; //Null terminates array char* token = strtok(tokInput, ";"); //parses rawInput char* arr[] = strtok(tokInput, ";"); while(token != NULL){//Tokenization cout << "token: " << token << endl;//output - FIXME //if(*token == '#'){ //strcpy(argv[cnt], "\0"); //null terminates argv //token = NULL; } argv[cnt] = token;//places tokenized strings into argv strcat(argv[cnt], "\0");//adds null char to strings in argv token = strtok(NULL, " "); //looks for connectors cnt++; //increment count } //strcat(argv[cnt], "\0");//Null terminates argv[] for(int i = 0; i < cnt; i++){ //prints all values of argv[] - FIXME cout << "argv[" << i << "]: " << argv[i] << endl; } int pid = fork();//forks the process if(pid == 0){ //child process //if(execvp(argv[0], &argv[0]) == -1){ - Old if(execvp(argv[0], argv) == -1){ perror("execvp failure"); } exit(1); }else{ //parent if(-1 == wait(NULL)){ perror("wait() failure"); } } }//end isRunning loop return 0; } */ <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <unistd.h> #include <cstring> #include <stdio.h> #include <cstdlib> using namespace std; //this function splits string into separate words and places into an array char* splitter(char* input) { char * result;//resulting storage array int currcount=0;//counter of current word //there are a few cases we need to consider //Cases include " ", ";", "#" for(int i=0; input[i]!='\0'; i++) { if(input[i]=='#') { break; } else if(input[i] == ';') { } else if(input[i] == ' ') { } } return result; } int main() { string username=getlogin(); char hostname[999]; gethostname(hostname, 999); string stringinput; char resultstring[999]; char input[999]; int counter=0; while(1) { cout << username << "@" << hostname << "$ "; getline(cin, stringinput); strcpy(input, stringinput.c_str()); strcpy(resultstring, stringinput.c_str()); char *storage=strtok(input," "); if(strcmp(storage,"exit")==0) exit(1); for(int i=0; input!='\0'; i++) { cout << storage[i]; int pid =fork(); if(pid==-1) { perror("This is an error with fork()"); exit(1); } else if(pid==0) { } else if(pid==1) { } counter++; } /*if(words[i]=="exit" || words[i]=="Exit") { exit(1); }*/ } return 0; } <commit_msg>added some important comments and started working on operators like ;<commit_after>#include <iostream> #include <string> #include <vector> #include <unistd.h> #include <cstring> #include <stdio.h> #include <cstdlib> #include <sys/wait.h> using namespace std; //this function splits string into separate words and places into an array char* splitter(char* input) { char * result;//resulting storage array int currcount=0;//counter of current word //there are a few cases we need to consider //cases include " ", ";", "#" for(int i=0; input[i]!='\0'; i++) { if(input[i]=='#') { break; } else if(input[i] == ';') { } else if(input[i] == ' ') { } } return result; } int main() { bool semicolon=0; bool doubleand=0; bool doubleor=0; string username=getlogin(); char hostname[999]; gethostname(hostname, 999); string stringinput; while(1) { //if the user name and hostname both exists, then the program displays it before the dollar sign. if(getlogin() != '\0' && gethostname(hostname,999) != -1) cout << username << "@" << hostname << "$ "; else{ perror("your hostname or username couldn't be found!"); cout << "$ "; } //takes in a string input getline(cin, stringinput); //this checks for exit and Exit command if(stringinput.find("exit")==0||stringinput.find("Exit")==0) exit(1); //this checks for comments. Basically, everything after the hash symbol is useless if(stringinput.find("#") != string::npos) { stringinput=stringinput.substr(0,stringinput.find("#")); } for(int i=0; i<stringinput.size(); i++) { int status=0; pid_t pid = fork(); if(pid==-1) { perror("this is an error with fork()"); exit(1); } else if(pid==0) { int good=execvp(input[0],input); if(good==-1) { perror("Command is bad and not good!"); exit(1); } else{ cout << "Good!" << execvp(input[0],input) << endl; } } else if(pid>=1) { if(waitpid(-1,&status,0)==-1) { perror("Please take care of your child!"); exit(1); } if(input[i]=="&&") { if(status>0) break; } if(input[i]=="||") if(status<=0) break; } } /*if(words[i]=="exit" || words[i]=="exit") { exit(1); }*/ } return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif namespace fs = boost::filesystem; namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; assert(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { assert(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { assert(m_open_mode & mode_in); assert(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { assert(m_open_mode & mode_out); assert(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type seek(size_type offset, int m) { assert(m_open_mode); assert(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { assert(m_open_mode); assert(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(boost::filesystem::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(boost::filesystem::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <commit_msg>file did not throw exception properly when file was trunkated and read<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/pch.hpp" #ifdef _WIN32 // windows part #include "libtorrent/utf8.hpp" #include <io.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #ifndef _MODE_T_ typedef int mode_t; #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif #else // unix part #define _FILE_OFFSET_BITS 64 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <boost/static_assert.hpp> // make sure the _FILE_OFFSET_BITS define worked // on this platform BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8); #endif #include <boost/filesystem/operations.hpp> #include "libtorrent/file.hpp" #include <sstream> #ifndef O_BINARY #define O_BINARY 0 #endif #ifndef O_RANDOM #define O_RANDOM 0 #endif #ifdef UNICODE #include "libtorrent/storage.hpp" #endif namespace fs = boost::filesystem; namespace { enum { mode_in = 1, mode_out = 2 }; mode_t map_open_mode(int m) { if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM; if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM; assert(false); return 0; } #ifdef WIN32 std::string utf8_native(std::string const& s) { try { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); if (size == wchar_t(-1)) return s; ret.resize(size); return ret; } catch(std::exception) { return s; } } #else std::string utf8_native(std::string const& s) { return s; } #endif } namespace libtorrent { const file::open_mode file::in(mode_in); const file::open_mode file::out(mode_out); const file::seek_mode file::begin(1); const file::seek_mode file::end(2); struct file::impl { impl() : m_fd(-1) , m_open_mode(0) {} impl(fs::path const& path, int mode) : m_fd(-1) , m_open_mode(0) { open(path, mode); } ~impl() { close(); } void open(fs::path const& path, int mode) { assert(path.is_complete()); close(); #if defined(_WIN32) && defined(UNICODE) std::wstring wpath(safe_convert(path.native_file_string())); m_fd = ::_wopen( wpath.c_str() , map_open_mode(mode) , S_IREAD | S_IWRITE); #else #ifdef _WIN32 m_fd = ::_open( #else m_fd = ::open( #endif utf8_native(path.native_file_string()).c_str() , map_open_mode(mode) #ifdef _WIN32 , S_IREAD | S_IWRITE); #else , S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); #endif #endif if (m_fd == -1) { std::stringstream msg; msg << "open failed: '" << path.native_file_string() << "'. " << strerror(errno); throw file_error(msg.str()); } m_open_mode = mode; } void close() { if (m_fd == -1) return; #ifdef _WIN32 ::_close(m_fd); #else ::close(m_fd); #endif m_fd = -1; m_open_mode = 0; } size_type read(char* buf, size_type num_bytes) { assert(num_bytes > 0); assert(m_open_mode & mode_in); assert(m_fd != -1); #ifdef _WIN32 size_type ret = ::_read(m_fd, buf, num_bytes); #else size_type ret = ::read(m_fd, buf, num_bytes); #endif if (ret == -1 || ret == 0) { std::stringstream msg; msg << "read failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type write(const char* buf, size_type num_bytes) { assert(m_open_mode & mode_out); assert(m_fd != -1); // TODO: Test this a bit more, what happens with random failures in // the files? // if ((rand() % 100) > 80) // throw file_error("debug"); #ifdef _WIN32 size_type ret = ::_write(m_fd, buf, num_bytes); #else size_type ret = ::write(m_fd, buf, num_bytes); #endif if (ret == -1) { std::stringstream msg; msg << "write failed: " << strerror(errno); throw file_error(msg.str()); } return ret; } size_type seek(size_type offset, int m) { assert(m_open_mode); assert(m_fd != -1); int seekdir = (m == 1)?SEEK_SET:SEEK_END; #ifdef _WIN32 size_type ret = _lseeki64(m_fd, offset, seekdir); #else size_type ret = lseek(m_fd, offset, seekdir); #endif // For some strange reason this fails // on win32. Use windows specific file // wrapper instead. if (ret == -1) { std::stringstream msg; msg << "seek failed: '" << strerror(errno) << "' fd: " << m_fd << " offset: " << offset << " seekdir: " << seekdir; throw file_error(msg.str()); } return ret; } size_type tell() { assert(m_open_mode); assert(m_fd != -1); #ifdef _WIN32 return _telli64(m_fd); #else return lseek(m_fd, 0, SEEK_CUR); #endif } int m_fd; int m_open_mode; }; // pimpl forwardings file::file() : m_impl(new impl()) {} file::file(boost::filesystem::path const& p, file::open_mode m) : m_impl(new impl(p, m.m_mask)) {} file::~file() {} void file::open(boost::filesystem::path const& p, file::open_mode m) { m_impl->open(p, m.m_mask); } void file::close() { m_impl->close(); } size_type file::write(const char* buf, size_type num_bytes) { return m_impl->write(buf, num_bytes); } size_type file::read(char* buf, size_type num_bytes) { return m_impl->read(buf, num_bytes); } size_type file::seek(size_type pos, file::seek_mode m) { return m_impl->seek(pos, m.m_val); } size_type file::tell() { return m_impl->tell(); } } <|endoftext|>
<commit_before>/* © 2010 David Given. * LBW is licensed under the MIT open source license. See the COPYING * file in this distribution for the full text. */ #include "globals.h" #include "exec/ElfLoader.h" #include "filesystem/FD.h" #include "filesystem/VFS.h" #include "filesystem/InterixVFSNode.h" enum { UNKNOWN_EXECUTABLE, ELF_EXECUTABLE, INTERIX_EXECUTABLE }; static int probe_executable(const string& filename) { Ref<FD> ref = VFS::OpenFile(NULL, filename); int fd = ref->GetRealFD(); char buffer[4]; if (pread(fd, buffer, sizeof(buffer), 0) == -1) return UNKNOWN_EXECUTABLE; if (memcmp(buffer, "\x7F" "ELF", 4) == 0) return ELF_EXECUTABLE; if (memcmp(buffer, "MZ", 2) == 0) return INTERIX_EXECUTABLE; return UNKNOWN_EXECUTABLE; } static void linux_exec(const string& pathname, const char* argv[], const char* environ[]) { /* Count options. */ int envc = 1; while (environ[envc]) envc++; const char* newenviron[envc + 7]; memset(newenviron, 0, sizeof(newenviron)); int index = 0; /* Set LBW-specific options. */ newenviron[index++] = "LBW_CHILD=1"; if (Options.FakeRoot) newenviron[index++] = "LBW_FAKEROOT=1"; if (Options.Warnings) newenviron[index++] = "LBW_WARNINGS=1"; if (!Options.Chroot.empty()) { string s = cprintf("LBW_CHROOT=%s", Options.Chroot.c_str()); newenviron[index++] = strdup(s.c_str()); } { string s = cprintf("LBW_CWD=%s", VFS::GetCWD().c_str()); newenviron[index++] = strdup(s.c_str()); } { string s = cprintf("LBW_LBWEXE=%s", Options.LBW.c_str()); newenviron[index++] = strdup(s.c_str()); } { string s = cprintf("LBW_LINUXEXE=%s", pathname.c_str()); newenviron[index++] = strdup(s.c_str()); } memcpy(newenviron + index, environ, envc * sizeof(char*)); /* Invoke child lwb instance. */ //log("exec <%s> into pid %d", pathname.c_str(), getpid()); execve(Options.LBW.c_str(), (char* const*) argv, (char* const*) newenviron); } void Exec(const string& pathname, const char* argv[], const char* environ[]) { //log("opening %s", argv[0]); int type = probe_executable(pathname); if (type == UNKNOWN_EXECUTABLE) throw ENOEXEC; /* Beyond this point we cannot recover. */ try { /* Change the Interix directory. */ Ref<VFSNode> node = VFS::GetCWDNode(); InterixVFSNode* inode = dynamic_cast<InterixVFSNode*>((VFSNode*) node); if (inode) fchdir(inode->GetRealFD()); else chdir("/"); /* Adjust the fd map so that Interix sees the same mappings that Linux * is. */ FD::Flush(); // free cloexec file descriptors map<int, int> fdmap = FD::GetFDMap(); map<int, int>::const_iterator i = fdmap.begin(); while (i != fdmap.end()) { //log("linuxfd %d maps to realfd %d", i->first, i->second); if (i->first != i->second) { if (fdmap.find(i->second) != fdmap.end()) { int newfd = dup(i->first); //log("copying realfd %d -> %d", i->first, newfd); fdmap[i->second] = newfd; } //log("copying realfd %d -> %d", i->second, i->first); int fd = dup2(i->second, i->first); assert(fd != -1); } i++; } /* Now actually perform the exec. */ switch (type) { case ELF_EXECUTABLE: linux_exec(pathname, argv, environ); break; case INTERIX_EXECUTABLE: execve(pathname.c_str(), (char* const*) argv, (char* const*) environ); break; } throw errno; } catch (int e) { error("Failed to exec with errno %d!", e); } } <commit_msg>Added first draft shell script support.<commit_after>/* © 2010 David Given. * LBW is licensed under the MIT open source license. See the COPYING * file in this distribution for the full text. */ #include "globals.h" #include "exec/ElfLoader.h" #include "exec/exec.h" #include "filesystem/FD.h" #include "filesystem/VFS.h" #include "filesystem/InterixVFSNode.h" enum { UNKNOWN_EXECUTABLE, ELF_EXECUTABLE, INTERIX_EXECUTABLE, SHELL_EXECUTABLE }; static int probe_executable(const string& filename) { Ref<FD> ref = VFS::OpenFile(NULL, filename); int fd = ref->GetRealFD(); char buffer[4]; if (pread(fd, buffer, sizeof(buffer), 0) == -1) return UNKNOWN_EXECUTABLE; if (memcmp(buffer, "\x7F" "ELF", 4) == 0) return ELF_EXECUTABLE; if (memcmp(buffer, "MZ", 2) == 0) return INTERIX_EXECUTABLE; if (memcmp(buffer, "#!", 2) == 0) return SHELL_EXECUTABLE; return UNKNOWN_EXECUTABLE; } static void linux_exec(const string& pathname, const char* argv[], const char* environ[]) { /* Count options. */ int envc = 1; while (environ[envc]) envc++; const char* newenviron[envc + 7]; memset(newenviron, 0, sizeof(newenviron)); int index = 0; /* Set LBW-specific options. */ newenviron[index++] = "LBW_CHILD=1"; if (Options.FakeRoot) newenviron[index++] = "LBW_FAKEROOT=1"; if (Options.Warnings) newenviron[index++] = "LBW_WARNINGS=1"; if (!Options.Chroot.empty()) { string s = cprintf("LBW_CHROOT=%s", Options.Chroot.c_str()); newenviron[index++] = strdup(s.c_str()); } { string s = cprintf("LBW_CWD=%s", VFS::GetCWD().c_str()); newenviron[index++] = strdup(s.c_str()); } { string s = cprintf("LBW_LBWEXE=%s", Options.LBW.c_str()); newenviron[index++] = strdup(s.c_str()); } { string s = cprintf("LBW_LINUXEXE=%s", pathname.c_str()); newenviron[index++] = strdup(s.c_str()); } memcpy(newenviron + index, environ, envc * sizeof(char*)); /* Invoke child lwb instance. */ //log("exec <%s> into pid %d", pathname.c_str(), getpid()); execve(Options.LBW.c_str(), (char* const*) argv, (char* const*) newenviron); } static bool isterm(int c) { return (c == '\0') || (c == '\n') || (c == '\r'); } static bool issep(int c) { return isterm(c) || (c == ' ') || (c == '\t'); } static void shell_exec(const string& pathname, const char* argv[], const char* environ[]) { Ref<FD> ref = VFS::OpenFile(NULL, pathname); int fd = ref->GetRealFD(); /* We know this will work, because we've just tried it when probing the * file. */ char buffer[128]; if (pread(fd, buffer, sizeof(buffer), 0) == -1) throw EIO; buffer[sizeof(buffer)-1] = '\0'; /* Messy code to parse the #! line. */ char* interpreter_start = buffer + 2; while (issep(*interpreter_start)) interpreter_start++; if (!*interpreter_start) throw EINVAL; char* interpreter_end = interpreter_start + 1; while (!issep(*interpreter_end)) interpreter_end++; char* arg_start = NULL; if (!isterm(*interpreter_end)) { arg_start = interpreter_end + 1; while (issep(*arg_start)) arg_start++; if (isterm(*arg_start)) arg_start = NULL; char* arg_end = arg_start + 1; while (!issep(*arg_end)) arg_end++; *arg_end = '\0'; } *interpreter_end = '\0'; /* Create a new argument array with this new arguments on the front. */ int argc = 0; while (argv[argc]) argc++; const char* newargv[argc+3]; int index = 0; newargv[index++] = interpreter_start; if (arg_start) newargv[index++] = arg_start; memcpy(newargv+index, argv, (argc+1) * sizeof(char*)); newargv[index] = pathname.c_str(); /* Retry the exec. */ Exec(newargv[0], newargv, environ); } void Exec(const string& pathname, const char* argv[], const char* environ[]) { //log("opening %s", argv[0]); int type = probe_executable(pathname); if (type == UNKNOWN_EXECUTABLE) throw ENOEXEC; /* Beyond this point we cannot recover. */ try { /* Change the Interix directory. */ Ref<VFSNode> node = VFS::GetCWDNode(); InterixVFSNode* inode = dynamic_cast<InterixVFSNode*>((VFSNode*) node); if (inode) fchdir(inode->GetRealFD()); else chdir("/"); /* Adjust the fd map so that Interix sees the same mappings that Linux * is. */ FD::Flush(); // free cloexec file descriptors map<int, int> fdmap = FD::GetFDMap(); map<int, int>::const_iterator i = fdmap.begin(); while (i != fdmap.end()) { //log("linuxfd %d maps to realfd %d", i->first, i->second); if (i->first != i->second) { if (fdmap.find(i->second) != fdmap.end()) { int newfd = dup(i->first); //log("copying realfd %d -> %d", i->first, newfd); fdmap[i->second] = newfd; } //log("copying realfd %d -> %d", i->second, i->first); int fd = dup2(i->second, i->first); assert(fd != -1); } i++; } /* Now actually perform the exec. */ switch (type) { case ELF_EXECUTABLE: linux_exec(pathname, argv, environ); break; case INTERIX_EXECUTABLE: execve(pathname.c_str(), (char* const*) argv, (char* const*) environ); break; case SHELL_EXECUTABLE: shell_exec(pathname, argv, environ); } throw errno; } catch (int e) { error("Failed to exec with errno %d!", e); } } <|endoftext|>
<commit_before>#include "features.h" #include <fstream> // Variables for features computation #define HIST_SIZE 100 size_t reconstructHashcode(const float *array) { float castValue; // Avoid warning errors (cast a const) castValue = array[0]; unsigned int leastSignificantBits = reinterpret_cast<unsigned int&>(castValue); castValue = array[1]; unsigned int mostSignificantBits = reinterpret_cast<unsigned int&>(castValue); size_t reconstructValue = mostSignificantBits; reconstructValue <<= 32; reconstructValue |= leastSignificantBits; return reconstructValue; } Features &Features::getInstance() { static Features instance; return instance; } Features::Features() : sizeElementArray(0) { sizeElementArray += 3*HIST_SIZE; // Histogram size sizeElementArray += NB_MAJOR_COLORS_EXTRACT*3; // Major colors loadMachineLearning(); } float Features::predict(const FeaturesElement &elem1, const FeaturesElement &elem2) const { Mat rowFeatureVector; computeDistance(elem1, elem2, rowFeatureVector); return predictRow(rowFeatureVector); // Scale and predict } float Features::predictRow(Mat rowFeatureVector) const { // Scale scaleRow(rowFeatureVector); return svm.predict(rowFeatureVector); } void Features::scaleRow(Mat rowFeatureVector) const { // Simple scale by dividing by maxValue for(size_t i = 0 ; i < static_cast<unsigned>(rowFeatureVector.cols) ; ++i) { rowFeatureVector.at<float>(i) /= scaleFactors.at<float>(0,i); } } void Features::computeDistance(const FeaturesElement &elem1, const FeaturesElement &elem2, Mat &rowFeatureVector) const { const int dimentionFeatureVector = 3 // Histogram + NB_MAJOR_COLORS_KEEP; // Major colors rowFeatureVector = cv::Mat::ones(1, dimentionFeatureVector, CV_32FC1); int currentIndexFeature = 0;// Usefull if I change the order or remove a feature (don't need to change all the index) // Histogram rowFeatureVector.at<float>(0, currentIndexFeature+0) = compareHist(elem1.histogramChannels.at(0), elem2.histogramChannels.at(0), CV_COMP_BHATTACHARYYA); rowFeatureVector.at<float>(0, currentIndexFeature+1) = compareHist(elem1.histogramChannels.at(1), elem2.histogramChannels.at(1), CV_COMP_BHATTACHARYYA); rowFeatureVector.at<float>(0, currentIndexFeature+2) = compareHist(elem1.histogramChannels.at(2), elem2.histogramChannels.at(2), CV_COMP_BHATTACHARYYA); currentIndexFeature += 3; // Major Colors // Compute only with the most weigthed on for (size_t i = 0; i < NB_MAJOR_COLORS_KEEP; ++i) { float minDist = norm(elem1.majorColors.at(i).color - elem2.majorColors.front().color); float dist = 0.0; for (size_t j = 0; j < NB_MAJOR_COLORS_KEEP; ++j) { dist = norm(elem1.majorColors.at(i).color - elem2.majorColors.at(j).color); if(dist < minDist) { minDist = dist; } } rowFeatureVector.at<float>(0,currentIndexFeature) = minDist; currentIndexFeature++; } // TODO: Add feature: camera id ; Add feature: time // The feature scaling is not made in this function } void Features::extractArray(const float *array, size_t sizeArray, vector<FeaturesElement> &listFeatures) const { // Test the validity if(array == nullptr) { return; } // Offset values (Global attributes) size_t hashCodeCameraId = reconstructHashcode(&array[0]); float castValue; castValue = array[2]; int beginDate = reinterpret_cast<int&>(castValue); castValue = array[3]; int endDate = reinterpret_cast<int&>(castValue); cv::Vec2f entranceVector(array[4], array[5]); cv::Vec2f exitVector(array[6], array[7]); // Shift the origin to remove the offset size_t offset = 8; array = &array[offset]; sizeArray -= offset; size_t currentId = 0; // No offset anymore for(size_t numberElem = (sizeArray - currentId) / sizeElementArray; // Number of frame's feature send numberElem > 0 ; --numberElem) { listFeatures.push_back(FeaturesElement()); FeaturesElement &currentElem = listFeatures.back(); // Copy the global attributes currentElem.hashCodeCameraId = hashCodeCameraId; currentElem.beginDate = beginDate; currentElem.endDate = endDate; currentElem.entranceVector = entranceVector; currentElem.exitVector = exitVector; // Histogram for(size_t channelId = 0 ; channelId < 3 ; ++channelId) { currentElem.histogramChannels.at(channelId).create(1,100,CV_32F); // TODO: Check order x,y !!!!!!! for(size_t i = 0 ; i < HIST_SIZE ; ++i) { currentElem.histogramChannels.at(channelId).at<float>(i) = array[currentId]; ++currentId; } } // Major colors for(size_t i = 0 ; i < NB_MAJOR_COLORS_EXTRACT ; ++i) { for(size_t j = 0 ; j < 3 ; ++j)// Channel number { currentElem.majorColors.at(i).color[j] = array[currentId]; ++currentId; } } } } void Features::checkCamera(const FeaturesElement &elem) { bool newCam = true; // Does the camera already exist ? for(pair<int, size_t> currentElem : cameraMap) { if(elem.hashCodeCameraId == currentElem.second) { newCam = false; } } // Otherwise, we simply add it if(newCam) { cameraMap.insert(pair<int, size_t>(cameraMap.size(), elem.hashCodeCameraId)); } } void Features::saveCameraMap(FileStorage &fileTraining) const { // Record the map of the camera if(!fileTraining.isOpened()) { cout << "Error: Cannot record the cameras on the training file (folder does not exist ?)" << endl; return; } fileTraining << "cameraMap" << "["; for(pair<int, size_t> currentElem : cameraMap) // For each camera { fileTraining << std::to_string(currentElem.second); } fileTraining << "]"; } void Features::clearCameraMap() { cameraMap.clear(); } void Features::setScaleFactors(const Mat &newValue) { scaleFactors = newValue; } void Features::loadMachineLearning() { // Loading file FileStorage fileTraining("../../Data/Training/training.yml", FileStorage::READ); if(!fileTraining.isOpened()) { cout << "Error: cannot open the training file" << endl; return; // No exit: we could be in training mode } // Loading the scales factors fileTraining["scaleFactors"] >> scaleFactors; // Loading the scale training set Mat trainingData; Mat trainingClasses; fileTraining["trainingData"] >> trainingData; fileTraining["trainingClasses"] >> trainingClasses; // Load the cameraMap cameraMap.clear(); FileNode nodeCameraMap = fileTraining["cameraMap"]; for(string currentCam : nodeCameraMap) { cameraMap.insert(pair<int, size_t>(cameraMap.size(), stoull(currentCam))); } fileTraining.release(); // Training CvSVMParams param = CvSVMParams(); param.svm_type = CvSVM::C_SVC; param.kernel_type = CvSVM::RBF; //CvSVM::RBF, CvSVM::LINEAR ... param.degree = 0; // for poly param.gamma = 20; // for poly/rbf/sigmoid param.coef0 = 0; // for poly/sigmoid param.C = 7; // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR param.nu = 0.0; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR param.p = 0.0; // for CV_SVM_EPS_SVR param.class_weights = NULL; // for CV_SVM_C_SVC param.term_crit.type = CV_TERMCRIT_ITER + CV_TERMCRIT_EPS; param.term_crit.max_iter = 1000; param.term_crit.epsilon = 1e-6; svm.train_auto(trainingData, trainingClasses, cv::Mat(), cv::Mat(), param); cout << "Training complete." << endl; } <commit_msg>Add features dimentions (camera, time, direction vector)<commit_after>#include "features.h" #include <fstream> // Variables for features computation const int HIST_SIZE = 100; const bool CAMERA_FEATURES = true; size_t reconstructHashcode(const float *array) { float castValue; // Avoid warning errors (cast a const) castValue = array[0]; unsigned int leastSignificantBits = reinterpret_cast<unsigned int&>(castValue); castValue = array[1]; unsigned int mostSignificantBits = reinterpret_cast<unsigned int&>(castValue); size_t reconstructValue = mostSignificantBits; reconstructValue <<= 32; reconstructValue |= leastSignificantBits; return reconstructValue; } Features &Features::getInstance() { static Features instance; return instance; } Features::Features() : sizeElementArray(0) { sizeElementArray += 3*HIST_SIZE; // Histogram size sizeElementArray += NB_MAJOR_COLORS_EXTRACT*3; // Major colors loadMachineLearning(); } float Features::predict(const FeaturesElement &elem1, const FeaturesElement &elem2) const { Mat rowFeatureVector; computeDistance(elem1, elem2, rowFeatureVector); return predictRow(rowFeatureVector); // Scale and predict } float Features::predictRow(Mat rowFeatureVector) const { // Scale scaleRow(rowFeatureVector); return svm.predict(rowFeatureVector); } void Features::scaleRow(Mat rowFeatureVector) const { // Simple scale by dividing by maxValue for(size_t i = 0 ; i < static_cast<unsigned>(rowFeatureVector.cols) ; ++i) { rowFeatureVector.at<float>(i) /= scaleFactors.at<float>(0,i); } } void Features::computeDistance(const FeaturesElement &elem1, const FeaturesElement &elem2, Mat &rowFeatureVector) const { int dimentionFeatureVector = 3 // Histogram + NB_MAJOR_COLORS_KEEP; // Major colors // Additionnal feature = additionnal dimention if(CAMERA_FEATURES) { // We add the categorical feature. For instance (0,0,1,0) for cam3 or (1,0,0,0) for cam1 dimentionFeatureVector += cameraMap.size()*2; // Factor 2 is for entrance camera and exit camera dimentionFeatureVector += 1; // For the duration between entrance and exit time dimentionFeatureVector += 2; // For the entrance and exit vector (dim 1 because converted to angle) } rowFeatureVector = cv::Mat::zeros(1, dimentionFeatureVector, CV_32FC1); int currentIndexFeature = 0;// Usefull if I change the order or remove a feature (don't need to change all the index) // Histogram rowFeatureVector.at<float>(0, currentIndexFeature+0) = compareHist(elem1.histogramChannels.at(0), elem2.histogramChannels.at(0), CV_COMP_BHATTACHARYYA); rowFeatureVector.at<float>(0, currentIndexFeature+1) = compareHist(elem1.histogramChannels.at(1), elem2.histogramChannels.at(1), CV_COMP_BHATTACHARYYA); rowFeatureVector.at<float>(0, currentIndexFeature+2) = compareHist(elem1.histogramChannels.at(2), elem2.histogramChannels.at(2), CV_COMP_BHATTACHARYYA); currentIndexFeature += 3; // Major Colors // Compute only with the most weigthed on for (size_t i = 0; i < NB_MAJOR_COLORS_KEEP; ++i) { float minDist = norm(elem1.majorColors.at(i).color - elem2.majorColors.front().color); float dist = 0.0; for (size_t j = 0; j < NB_MAJOR_COLORS_KEEP; ++j) { dist = norm(elem1.majorColors.at(i).color - elem2.majorColors.at(j).color); if(dist < minDist) { minDist = dist; } } rowFeatureVector.at<float>(0,currentIndexFeature) = minDist; currentIndexFeature++; } // TODO: Add feature: camera id ; Add feature: time if(CAMERA_FEATURES) { const FeaturesElement *firstElem = 0; const FeaturesElement *lastElem = 0; // Check who came first if(elem1.endDate < elem2.beginDate) // Elem1 > Elem2 { firstElem = &elem1; lastElem = &elem2; } else if(elem2.endDate < elem1.beginDate) // Elem2 > Elem1 { firstElem = &elem2; lastElem = &elem1; } else { // TODO firstElem = &elem1; lastElem = &elem2; } // Entrance and exit cam for(pair<int, size_t> currentElem : cameraMap) // For each camera { if(currentElem.second == firstElem->hashCodeCameraId) // 1 for the camera { rowFeatureVector.at<float>(0, currentIndexFeature) = 1.0; } else // 0 for the other { rowFeatureVector.at<float>(0, currentIndexFeature) = 0.0; } currentIndexFeature++; } for(pair<int, size_t> currentElem : cameraMap) // For each camera { if(currentElem.second == lastElem->hashCodeCameraId) // 1 for the camera { rowFeatureVector.at<float>(0, currentIndexFeature) = 1.0; } else // 0 for the other { rowFeatureVector.at<float>(0, currentIndexFeature) = 0.0; } currentIndexFeature++; } // Entrance and exit time rowFeatureVector.at<float>(0, currentIndexFeature) = lastElem->beginDate - firstElem->endDate; currentIndexFeature++; // Entrance and exit vector Vec2f cartX(firstElem->exitVector[0], lastElem->exitVector[0]); Vec2f cartY(firstElem->exitVector[1], lastElem->exitVector[1]); Vec2f polAngle; cv::cartToPolar(cartX, cartY, Vec2f(), polAngle); rowFeatureVector.at<float>(0, currentIndexFeature+0) = polAngle[0]; rowFeatureVector.at<float>(0, currentIndexFeature+1) = polAngle[1]; currentIndexFeature += 2; } // The feature scaling is not made in this function } void Features::extractArray(const float *array, size_t sizeArray, vector<FeaturesElement> &listFeatures) const { // Test the validity if(array == nullptr) { return; } // Offset values (Global attributes) size_t hashCodeCameraId = reconstructHashcode(&array[0]); float castValue; castValue = array[2]; int beginDate = reinterpret_cast<int&>(castValue); castValue = array[3]; int endDate = reinterpret_cast<int&>(castValue); cv::Vec2f entranceVector(array[4], array[5]); cv::Vec2f exitVector(array[6], array[7]); // Shift the origin to remove the offset size_t offset = 8; array = &array[offset]; sizeArray -= offset; size_t currentId = 0; // No offset anymore for(size_t numberElem = (sizeArray - currentId) / sizeElementArray; // Number of frame's feature send numberElem > 0 ; --numberElem) { listFeatures.push_back(FeaturesElement()); FeaturesElement &currentElem = listFeatures.back(); // Copy the global attributes currentElem.hashCodeCameraId = hashCodeCameraId; currentElem.beginDate = beginDate; currentElem.endDate = endDate; currentElem.entranceVector = entranceVector; currentElem.exitVector = exitVector; // Histogram for(size_t channelId = 0 ; channelId < 3 ; ++channelId) { currentElem.histogramChannels.at(channelId).create(1,100,CV_32F); // TODO: Check order x,y !!!!!!! for(size_t i = 0 ; i < HIST_SIZE ; ++i) { currentElem.histogramChannels.at(channelId).at<float>(i) = array[currentId]; ++currentId; } } // Major colors for(size_t i = 0 ; i < NB_MAJOR_COLORS_EXTRACT ; ++i) { for(size_t j = 0 ; j < 3 ; ++j)// Channel number { currentElem.majorColors.at(i).color[j] = array[currentId]; ++currentId; } } } } void Features::checkCamera(const FeaturesElement &elem) { bool newCam = true; // Does the camera already exist ? for(pair<int, size_t> currentElem : cameraMap) { if(elem.hashCodeCameraId == currentElem.second) { newCam = false; } } // Otherwise, we simply add it if(newCam) { cameraMap.insert(pair<int, size_t>(cameraMap.size(), elem.hashCodeCameraId)); } } void Features::saveCameraMap(FileStorage &fileTraining) const { // Record the map of the camera if(!fileTraining.isOpened()) { cout << "Error: Cannot record the cameras on the training file (folder does not exist ?)" << endl; return; } fileTraining << "cameraMap" << "["; for(pair<int, size_t> currentElem : cameraMap) // For each camera { fileTraining << std::to_string(currentElem.second); } fileTraining << "]"; } void Features::clearCameraMap() { cameraMap.clear(); } void Features::setScaleFactors(const Mat &newValue) { scaleFactors = newValue; } void Features::loadMachineLearning() { // Loading file FileStorage fileTraining("../../Data/Training/training.yml", FileStorage::READ); if(!fileTraining.isOpened()) { cout << "Error: cannot open the training file" << endl; return; // No exit: we could be in training mode } // Loading the scales factors fileTraining["scaleFactors"] >> scaleFactors; // Loading the scale training set Mat trainingData; Mat trainingClasses; fileTraining["trainingData"] >> trainingData; fileTraining["trainingClasses"] >> trainingClasses; // Load the cameraMap cameraMap.clear(); FileNode nodeCameraMap = fileTraining["cameraMap"]; for(string currentCam : nodeCameraMap) { cameraMap.insert(pair<int, size_t>(cameraMap.size(), stoull(currentCam))); } fileTraining.release(); // Training CvSVMParams param = CvSVMParams(); param.svm_type = CvSVM::C_SVC; param.kernel_type = CvSVM::RBF; //CvSVM::RBF, CvSVM::LINEAR ... param.degree = 0; // for poly param.gamma = 20; // for poly/rbf/sigmoid param.coef0 = 0; // for poly/sigmoid param.C = 7; // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR param.nu = 0.0; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR param.p = 0.0; // for CV_SVM_EPS_SVR param.class_weights = NULL; // for CV_SVM_C_SVC param.term_crit.type = CV_TERMCRIT_ITER + CV_TERMCRIT_EPS; param.term_crit.max_iter = 1000; param.term_crit.epsilon = 1e-6; svm.train_auto(trainingData, trainingClasses, cv::Mat(), cv::Mat(), param); cout << "Training complete." << endl; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativegeomapobject_p.h" #include "qdeclarativegeomapmousearea_p.h" #include <qdeclarativelandmark_p.h> #include <QDeclarativeParserStatus> #include <QAbstractItemModel> #include <QDeclarativeContext> #include <QGeoMapData> QTM_BEGIN_NAMESPACE QDeclarativeGeoMapObject::QDeclarativeGeoMapObject(QDeclarativeItem *parent) : QDeclarativeItem(parent), object_(0), visible_(true) {} QDeclarativeGeoMapObject::~QDeclarativeGeoMapObject() {} void QDeclarativeGeoMapObject::componentComplete() { QDeclarativeItem::componentComplete(); QList<QGraphicsItem*> children = childItems(); for (int i = 0; i < children.size(); ++i) { QDeclarativeGeoMapMouseArea *mouseArea = qobject_cast<QDeclarativeGeoMapMouseArea*>(children.at(i)); if (mouseArea) mouseAreas_.append(mouseArea); } } void QDeclarativeGeoMapObject::clickEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->clickEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::doubleClickEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->doubleClickEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::pressEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->pressEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::releaseEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->releaseEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::enterEvent() { for (int i = 0; i < mouseAreas_.size(); ++i) mouseAreas_.at(i)->enterEvent(); } void QDeclarativeGeoMapObject::exitEvent() { for (int i = 0; i < mouseAreas_.size(); ++i) mouseAreas_.at(i)->exitEvent(); } void QDeclarativeGeoMapObject::moveEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->moveEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::setMapObject(QGeoMapObject *object) { if (!object) return; object_ = object; object_->setVisible(visible_); connect(this, SIGNAL(zChanged()), this, SLOT(parentZChanged())); object_->setZValue(zValue()); } QGeoMapObject* QDeclarativeGeoMapObject::mapObject() { return object_; } void QDeclarativeGeoMapObject::parentZChanged() { object_->setZValue(zValue()); } void QDeclarativeGeoMapObject::setVisible(bool visible) { if (visible_ == visible) return; visible_ = visible; if (object_) object_->setVisible(visible); emit visibleChanged(visible_); } bool QDeclarativeGeoMapObject::isVisible() const { return visible_; } /*! \qmlclass MapObjectView \brief The MapObjectView is used to populate Map from a model. \inherits QDeclarativeItem \ingroup qml-location-maps The MapObjectView is used to populate Map with MapObjects from a model. The MapObjectView element only makes sense when contained in a Map object, meaning that it has no standalone presentation. Note: For model data, currently only LandmarkModel is supported. Using other types of models results in undefined behavior. The MapObjectView element is part of the \bold{QtMobility.location 1.2} module. */ QDeclarativeGeoMapObjectView::QDeclarativeGeoMapObjectView(QDeclarativeItem *parent) : QObject(parent), componentCompleted_(false), delegate_(0), model_(0), mapData_(0) { } QDeclarativeGeoMapObjectView::~QDeclarativeGeoMapObjectView() { if (!mapObjects_.isEmpty()) { for (int i = 0; i < mapObjects_.size(); ++i) { mapData_->removeMapObject(mapObjects_.at(i)->mapObject()); } // Model owns the data, do not delete the pointers. mapObjects_.clear(); } } void QDeclarativeGeoMapObjectView::componentComplete() { componentCompleted_ = true; } QVariant QDeclarativeGeoMapObjectView::model() const { return modelVariant_; } /*! \qmlproperty Component MapObjectView::model This property holds the model that provides data for populating data with delegates. Note: Currently only LandmarkModel is supported. Using other models results in undefined behavior. */ void QDeclarativeGeoMapObjectView::setModel(const QVariant &model) { if (!model.isValid() || model == modelVariant_) return; QObject *object = qvariant_cast<QObject*>(model); QAbstractItemModel* itemModel; if (!object || !(itemModel = qobject_cast<QAbstractItemModel*>(object))) { return; } modelVariant_ = model; model_ = itemModel; // At the moment maps only works with landmark model. Because of this tight // restriction, connecting to model resets is adequate. This must be changed // if and when the model support is leveraged. QObject::connect(model_, SIGNAL(modelReset()), this, SLOT(modelReset())); emit modelChanged(); } void QDeclarativeGeoMapObjectView::modelReset() { repopulate(); } QDeclarativeComponent* QDeclarativeGeoMapObjectView::delegate() const { return delegate_; } /*! \qmlproperty Component MapObjectView::delegate This property holds the delegate which defines how each item in the model should be displayed. The Component must contain exactly one MapObject -derived element as the root element. */ void QDeclarativeGeoMapObjectView::setDelegate(QDeclarativeComponent *delegate) { if (!delegate) return; delegate_ = delegate; if (componentCompleted_) repopulate(); emit delegateChanged(); } void QDeclarativeGeoMapObjectView::setMapData(QGeoMapData *data) { if (!data || mapData_) // changing mapData_ on the fly not supported return; mapData_ = data; } // Removes and repopulates all items. void QDeclarativeGeoMapObjectView::repopulate() { if (!componentCompleted_ || !mapData_ || !delegate_ || !model_) return; if (!mapObjects_.isEmpty()) { for (int i = 0; i < mapObjects_.size(); ++i) { mapData_->removeMapObject(mapObjects_.at(i)->mapObject()); } // Model owns the data, do not delete the pointers. mapObjects_.clear(); } // Iterate model data and instantiate delegates. // We could use more specialized landmark model calls here too, // but hopefully the support will be leveraged to a general model // level. QDeclarativeGeoMapObject* mapObject; for (int i = 0; i < model_->rowCount(); ++i) { mapObject = createItem(i); if (!mapObject) break; mapObjects_.append(mapObject); mapData_->addMapObject(mapObject->mapObject()); } } // Currently item creation is tightly bound to landmark model. Some day // this may be leveraged to any user defined model or e.g. XML model. QDeclarativeGeoMapObject* QDeclarativeGeoMapObjectView::createItem(int modelRow) { if (!delegate_ || !model_) return NULL; QModelIndex index = model_->index(modelRow, 0); // column 0 if (!index.isValid()) { qWarning() << "QDeclarativeGeoMapObject Index is not valid: " << modelRow; return NULL; } QHashIterator<int, QByteArray> iterator(model_->roleNames()); QDeclarativeContext *itemContext = new QDeclarativeContext(qmlContext(this)); while (iterator.hasNext()) { iterator.next(); QVariant modelData = model_->data(index, iterator.key()); if (!modelData.isValid()) continue; // This call would fail for <QObject*> Need to be figured out why // if the model support is leveraged. QObject *data_ptr = modelData.value<QDeclarativeLandmark*>(); if (!data_ptr) continue; itemContext->setContextProperty(QLatin1String(iterator.value().data()), data_ptr); // To avoid name collisions (delegate has same named attribute as model's role) // one can add here that the data is accessible also e.g. via 'model'. // In case of landmarks, two of the following are then equivalent: // latitude : landmark.coordinate.latitude // latitude : model.landmark.coordinate.latitude // itemContext->setContextProperty(QLatin1String("model."), data_ptr); // At the time being, it is however uncertain how to make it from a // QtMobility project (QDeclarativeVisualDataModel not available). // This however needs to be figured out if model support is generalized. } QObject* obj = delegate_->create(itemContext); if (!obj) { qWarning() << "QDeclarativeGeoMapObject map object creation failed."; delete itemContext; return NULL; } QDeclarativeGeoMapObject *declMapObj = qobject_cast<QDeclarativeGeoMapObject*>(obj); if (!declMapObj) { qWarning() << "QDeclarativeGeoMapObject map object delegate is of unsupported type."; delete itemContext; return NULL; } delete itemContext; return declMapObj; } #include "moc_qdeclarativegeomapobject_p.cpp" QTM_END_NAMESPACE <commit_msg>Attempt to fix compilation error.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativegeomapobject_p.h" #include "qdeclarativegeomapmousearea_p.h" #include "qdeclarativelandmark_p.h" #include "qgeomapdata.h" #include <QDeclarativeParserStatus> #include <QAbstractItemModel> #include <QDeclarativeContext> QTM_BEGIN_NAMESPACE QDeclarativeGeoMapObject::QDeclarativeGeoMapObject(QDeclarativeItem *parent) : QDeclarativeItem(parent), object_(0), visible_(true) {} QDeclarativeGeoMapObject::~QDeclarativeGeoMapObject() {} void QDeclarativeGeoMapObject::componentComplete() { QDeclarativeItem::componentComplete(); QList<QGraphicsItem*> children = childItems(); for (int i = 0; i < children.size(); ++i) { QDeclarativeGeoMapMouseArea *mouseArea = qobject_cast<QDeclarativeGeoMapMouseArea*>(children.at(i)); if (mouseArea) mouseAreas_.append(mouseArea); } } void QDeclarativeGeoMapObject::clickEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->clickEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::doubleClickEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->doubleClickEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::pressEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->pressEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::releaseEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->releaseEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::enterEvent() { for (int i = 0; i < mouseAreas_.size(); ++i) mouseAreas_.at(i)->enterEvent(); } void QDeclarativeGeoMapObject::exitEvent() { for (int i = 0; i < mouseAreas_.size(); ++i) mouseAreas_.at(i)->exitEvent(); } void QDeclarativeGeoMapObject::moveEvent(QDeclarativeGeoMapMouseEvent *event) { if (event->accepted()) return; for (int i = 0; i < mouseAreas_.size(); ++i) { mouseAreas_.at(i)->moveEvent(event); if (event->accepted()) return; } } void QDeclarativeGeoMapObject::setMapObject(QGeoMapObject *object) { if (!object) return; object_ = object; object_->setVisible(visible_); connect(this, SIGNAL(zChanged()), this, SLOT(parentZChanged())); object_->setZValue(zValue()); } QGeoMapObject* QDeclarativeGeoMapObject::mapObject() { return object_; } void QDeclarativeGeoMapObject::parentZChanged() { object_->setZValue(zValue()); } void QDeclarativeGeoMapObject::setVisible(bool visible) { if (visible_ == visible) return; visible_ = visible; if (object_) object_->setVisible(visible); emit visibleChanged(visible_); } bool QDeclarativeGeoMapObject::isVisible() const { return visible_; } /*! \qmlclass MapObjectView \brief The MapObjectView is used to populate Map from a model. \inherits QDeclarativeItem \ingroup qml-location-maps The MapObjectView is used to populate Map with MapObjects from a model. The MapObjectView element only makes sense when contained in a Map object, meaning that it has no standalone presentation. Note: For model data, currently only LandmarkModel is supported. Using other types of models results in undefined behavior. The MapObjectView element is part of the \bold{QtMobility.location 1.2} module. */ QDeclarativeGeoMapObjectView::QDeclarativeGeoMapObjectView(QDeclarativeItem *parent) : QObject(parent), componentCompleted_(false), delegate_(0), model_(0), mapData_(0) { } QDeclarativeGeoMapObjectView::~QDeclarativeGeoMapObjectView() { if (!mapObjects_.isEmpty()) { for (int i = 0; i < mapObjects_.size(); ++i) { mapData_->removeMapObject(mapObjects_.at(i)->mapObject()); } // Model owns the data, do not delete the pointers. mapObjects_.clear(); } } void QDeclarativeGeoMapObjectView::componentComplete() { componentCompleted_ = true; } QVariant QDeclarativeGeoMapObjectView::model() const { return modelVariant_; } /*! \qmlproperty Component MapObjectView::model This property holds the model that provides data for populating data with delegates. Note: Currently only LandmarkModel is supported. Using other models results in undefined behavior. */ void QDeclarativeGeoMapObjectView::setModel(const QVariant &model) { if (!model.isValid() || model == modelVariant_) return; QObject *object = qvariant_cast<QObject*>(model); QAbstractItemModel* itemModel; if (!object || !(itemModel = qobject_cast<QAbstractItemModel*>(object))) { return; } modelVariant_ = model; model_ = itemModel; // At the moment maps only works with landmark model. Because of this tight // restriction, connecting to model resets is adequate. This must be changed // if and when the model support is leveraged. QObject::connect(model_, SIGNAL(modelReset()), this, SLOT(modelReset())); emit modelChanged(); } void QDeclarativeGeoMapObjectView::modelReset() { repopulate(); } QDeclarativeComponent* QDeclarativeGeoMapObjectView::delegate() const { return delegate_; } /*! \qmlproperty Component MapObjectView::delegate This property holds the delegate which defines how each item in the model should be displayed. The Component must contain exactly one MapObject -derived element as the root element. */ void QDeclarativeGeoMapObjectView::setDelegate(QDeclarativeComponent *delegate) { if (!delegate) return; delegate_ = delegate; if (componentCompleted_) repopulate(); emit delegateChanged(); } void QDeclarativeGeoMapObjectView::setMapData(QGeoMapData *data) { if (!data || mapData_) // changing mapData_ on the fly not supported return; mapData_ = data; } // Removes and repopulates all items. void QDeclarativeGeoMapObjectView::repopulate() { if (!componentCompleted_ || !mapData_ || !delegate_ || !model_) return; if (!mapObjects_.isEmpty()) { for (int i = 0; i < mapObjects_.size(); ++i) { mapData_->removeMapObject(mapObjects_.at(i)->mapObject()); } // Model owns the data, do not delete the pointers. mapObjects_.clear(); } // Iterate model data and instantiate delegates. // We could use more specialized landmark model calls here too, // but hopefully the support will be leveraged to a general model // level. QDeclarativeGeoMapObject* mapObject; for (int i = 0; i < model_->rowCount(); ++i) { mapObject = createItem(i); if (!mapObject) break; mapObjects_.append(mapObject); mapData_->addMapObject(mapObject->mapObject()); } } // Currently item creation is tightly bound to landmark model. Some day // this may be leveraged to any user defined model or e.g. XML model. QDeclarativeGeoMapObject* QDeclarativeGeoMapObjectView::createItem(int modelRow) { if (!delegate_ || !model_) return NULL; QModelIndex index = model_->index(modelRow, 0); // column 0 if (!index.isValid()) { qWarning() << "QDeclarativeGeoMapObject Index is not valid: " << modelRow; return NULL; } QHashIterator<int, QByteArray> iterator(model_->roleNames()); QDeclarativeContext *itemContext = new QDeclarativeContext(qmlContext(this)); while (iterator.hasNext()) { iterator.next(); QVariant modelData = model_->data(index, iterator.key()); if (!modelData.isValid()) continue; // This call would fail for <QObject*> Need to be figured out why // if the model support is leveraged. QObject *data_ptr = modelData.value<QDeclarativeLandmark*>(); if (!data_ptr) continue; itemContext->setContextProperty(QLatin1String(iterator.value().data()), data_ptr); // To avoid name collisions (delegate has same named attribute as model's role) // one can add here that the data is accessible also e.g. via 'model'. // In case of landmarks, two of the following are then equivalent: // latitude : landmark.coordinate.latitude // latitude : model.landmark.coordinate.latitude // itemContext->setContextProperty(QLatin1String("model."), data_ptr); // At the time being, it is however uncertain how to make it from a // QtMobility project (QDeclarativeVisualDataModel not available). // This however needs to be figured out if model support is generalized. } QObject* obj = delegate_->create(itemContext); if (!obj) { qWarning() << "QDeclarativeGeoMapObject map object creation failed."; delete itemContext; return NULL; } QDeclarativeGeoMapObject *declMapObj = qobject_cast<QDeclarativeGeoMapObject*>(obj); if (!declMapObj) { qWarning() << "QDeclarativeGeoMapObject map object delegate is of unsupported type."; delete itemContext; return NULL; } delete itemContext; return declMapObj; } #include "moc_qdeclarativegeomapobject_p.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////////////////////// // header_normalize:: // // ATS plugin to convert headers into camel-case. It may be useful to solve // interworking issues with legacy origins not supporting lower case headers // required by protocols such as spdy/http2 etc. // // Note that the plugin currently uses READ_REQUEST_HDR_HOOK to camel-case // the headers. As an optimization, it can be changed to SEND_REQUEST_HDR_HOOK // so that it only converts, if/when the request is being sent to the origin // // To use this plugin, configure a remap.config rule like // // map http://foo.com http://bar.com @plugin=header_normalize.so // // // The list of of all available parameters is in the README. // // // Note that the path to the plugin itself must be absolute, and by default it is // // /home/y/libexec/trafficserver/header_normalize.so // // #define UNUSED __attribute__ ((unused)) static char UNUSED rcsId__header_normalize_cc[] = "@(#) $Id: header_normalize.cc 218 2014-11-11 01:29:16Z sudheerv $ built on " __DATE__ " " __TIME__; #include <sys/time.h> #include <ts/ts.h> #include <ts/remap.h> #include <set> #include <string> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <netdb.h> #include <map> using namespace std; /////////////////////////////////////////////////////////////////////////////// // Some constants. // const char* PLUGIN_NAME = "header_normalize"; std::map<std::string, std::string, std::less<std::string> > hdrMap; static void buildHdrMap() { hdrMap["accept"] = "Accept"; hdrMap["accept-charset"] = "Accept-Charset"; hdrMap["accept-encoding"] = "Accept-Encoding"; hdrMap["accept-language"] = "Accept-Language"; hdrMap["accept-ranges"] = "Accept-Ranges"; hdrMap["age"] = "Age"; hdrMap["allow"] = "Allow"; hdrMap["approved"] = "Approved"; hdrMap["bytes"] = "Bytes"; hdrMap["cache-control"] = "Cache-Control"; hdrMap["client-ip"] = "Client-Ip"; hdrMap["connection"] = "Connection"; hdrMap["content-base"] = "Content-Base"; hdrMap["content-encoding"] = "Content-Encoding"; hdrMap["content-language"] = "Content-Language"; hdrMap["content-length"] = "Content-Length"; hdrMap["content-location"] = "Content-Location"; hdrMap["content-md5"] = "Content-MD5"; hdrMap["content-range"] = "Content-Range"; hdrMap["content-type"] = "Content-Type"; hdrMap["control"] = "Control"; hdrMap["cookie"] = "Cookie"; hdrMap["date"] = "Date"; hdrMap["distribution"] = "Distribution"; hdrMap["etag"] = "Etag"; hdrMap["expect"] = "Expect"; hdrMap["expires"] = "Expires"; hdrMap["followup-to"] = "Followup-To"; hdrMap["from"] = "From"; hdrMap["host"] = "Host"; hdrMap["if-match"] = "If-Match"; hdrMap["if-modified-since"] = "If-Modified-Since"; hdrMap["if-none-match"] = "If-None-Match"; hdrMap["if-range"] = "If-Range"; hdrMap["if-unmodified-since"] = "If-Unmodified-Since"; hdrMap["keep-alive"] = "Keep-Alive"; hdrMap["keywords"] = "Keywords"; hdrMap["last-modified"] = "Last-Modified"; hdrMap["lines"] = "Lines"; hdrMap["location"] = "Location"; hdrMap["max-forwards"] = "Max-Forwards"; hdrMap["message-id"] = "Message-Id"; hdrMap["newsgroups"] = "Newsgroups"; hdrMap["organization"] = "Organization"; hdrMap["path"] = "Path"; hdrMap["pragma"] = "Pragma"; hdrMap["proxy-authenticate"] = "Proxy-Authenticate"; hdrMap["proxy-authorization"] = "Proxy-Authorization"; hdrMap["proxy-connection"] = "Proxy-Connection"; hdrMap["public"] = "Public"; hdrMap["range"] = "Range"; hdrMap["references"] = "References"; hdrMap["referer"] = "Referer"; hdrMap["reply-to"] = "Reply-To"; hdrMap["retry-after"] = "Retry-After"; hdrMap["sender"] = "Sender"; hdrMap["server"] = "Server"; hdrMap["set-cookie"] = "Set-Cookie"; hdrMap["strict-transport-security"] = "Strict-Transport-Security"; hdrMap["subject"] = "Subject"; hdrMap["summary"] = "Summary"; hdrMap["te"] = "Te"; hdrMap["transfer-encoding"] = "Transfer-Encoding"; hdrMap["upgrade"] = "Upgrade"; hdrMap["user-agent"] = "User-Agent"; hdrMap["vary"] = "Vary"; hdrMap["via"] = "Via"; hdrMap["warning"] = "Warning"; hdrMap["www-authenticate"] = "Www-Authenticate"; hdrMap["xref"] = "Xref"; hdrMap["@datainfo"] = "@DataInfo"; hdrMap["x-id"] = "X-ID"; hdrMap["x-forwarded-for"] = "X-Forwarded-For"; hdrMap["sec-websocket-key"] = "Sec-WebSocket-Key"; hdrMap["sec-websocket-version"] = "Sec-WebSocket-Version"; } /////////////////////////////////////////////////////////////////////////////// // Initialize the plugin. // // // TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { if (!api_info) { strncpy(errbuf, "[tsremap_init] - Invalid TSREMAP_INTERFACE argument", errbuf_size - 1); return TS_ERROR; } if (api_info->tsremap_version < TSREMAP_VERSION) { snprintf(errbuf, errbuf_size - 1, "[tsremap_init] - Incorrect API version %ld.%ld", api_info->tsremap_version >> 16, (api_info->tsremap_version & 0xffff)); return TS_ERROR; } buildHdrMap(); TSDebug(PLUGIN_NAME, "plugin is succesfully initialized"); return TS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // One instance per remap.config invocation. // TSReturnCode TSRemapNewInstance(int /* argc */, char * /* argv[] */, void ** /* ih */, char * /* errbuf */, int /* errbuf_size */) { return TS_SUCCESS; } void TSRemapDelteInstance(void * /* ih */) { } static int read_request_hook(TSCont /* contp */, TSEvent /* event */, void *edata) { TSHttpTxn rh = (TSHttpTxn) edata; TSMLoc hdr, next_hdr; TSMBuffer hdr_bufp; TSMLoc req_hdrs; if (TSHttpTxnClientReqGet(rh, &hdr_bufp, &req_hdrs) == TS_SUCCESS) { hdr = TSMimeHdrFieldGet(hdr_bufp, req_hdrs, 0); int n_mime_headers = TSMimeHdrFieldsCount(hdr_bufp, req_hdrs); TSDebug(PLUGIN_NAME, "*** Camel Casing %u hdrs in the request", n_mime_headers); for (int i = 0; i < n_mime_headers; ++i) { if (hdr == NULL) break; next_hdr = TSMimeHdrFieldNext(hdr_bufp, req_hdrs, hdr); int old_hdr_len; const char* old_hdr_name = TSMimeHdrFieldNameGet(hdr_bufp, req_hdrs, hdr, &old_hdr_len); // TSMimeHdrFieldNameGet returns the MIME_FIELD_NAME // for all MIME hdrs, which is always in Camel Case if (islower(old_hdr_name[0])) { TSDebug(PLUGIN_NAME, "*** non MIME Hdr %s, leaving it for now", old_hdr_name); TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; continue; } int hdr_value_len = 0; const char *hdr_value = TSMimeHdrFieldValueStringGet(hdr_bufp, req_hdrs, hdr, 0, &hdr_value_len); // hdr returned by TSMimeHdrFieldNameGet is already // in camel case, just destroy the lowercase spdy header // and replace it with TSMimeHdrFieldNameGet char* new_hdr_name = (char*)old_hdr_name; if (new_hdr_name) { TSMLoc new_hdr_loc; TSReturnCode rval = TSMimeHdrFieldCreateNamed(hdr_bufp, req_hdrs, new_hdr_name, old_hdr_len, &new_hdr_loc); if (rval == TS_SUCCESS) { TSDebug(PLUGIN_NAME, "*** hdr convert %s to %s", old_hdr_name, new_hdr_name); TSMimeHdrFieldValueStringSet(hdr_bufp, req_hdrs, new_hdr_loc, -1, hdr_value, hdr_value_len); TSMimeHdrFieldAppend(hdr_bufp, req_hdrs, new_hdr_loc); TSHandleMLocRelease(hdr_bufp, req_hdrs, new_hdr_loc); } TSMimeHdrFieldDestroy(hdr_bufp, req_hdrs, hdr); } else { TSDebug(PLUGIN_NAME, "*** can't find hdr %s in hdrMap", old_hdr_name); } TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; } TSHandleMLocRelease(hdr_bufp, TS_NULL_MLOC, req_hdrs); } TSHttpTxnReenable(rh, TS_EVENT_HTTP_CONTINUE); return 0; } void TSPluginInit(int /* argc */, const char * /* argv[] */) { TSDebug(PLUGIN_NAME, "initializing plugin"); TSCont contp; buildHdrMap(); contp = TSContCreate(read_request_hook, NULL); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp); } /////////////////////////////////////////////////////////////////////////////// // This is the main "entry" point for the plugin, called for every request. // TSRemapStatus TSRemapDoRemap (void * /* ih */, TSHttpTxn rh, TSRemapRequestInfo * /* rri */) { read_request_hook(NULL, TS_EVENT_HTTP_READ_REQUEST_HDR, rh); return TSREMAP_DID_REMAP; } <commit_msg>Adding AL2 license blurb for the new file<commit_after>/** @file Plugin to perform background fetches of certain content that would otherwise not be cached. For example, Range: requests / responses. @section license License 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. */ //////////////////////////////////////////////////////////////////////////////// // header_normalize:: // // ATS plugin to convert headers into camel-case. It may be useful to solve // interworking issues with legacy origins not supporting lower case headers // required by protocols such as spdy/http2 etc. // // Note that the plugin currently uses READ_REQUEST_HDR_HOOK to camel-case // the headers. As an optimization, it can be changed to SEND_REQUEST_HDR_HOOK // so that it only converts, if/when the request is being sent to the origin. // // This plugin supports both global mode as well as per-remap mode activation ////////////////////////////////////////////////////////////////////////////////// #define UNUSED __attribute__ ((unused)) static char UNUSED rcsId__header_normalize_cc[] = "@(#) $Id: header_normalize.cc 218 2014-11-11 01:29:16Z sudheerv $ built on " __DATE__ " " __TIME__; #include <sys/time.h> #include <ts/ts.h> #include <ts/remap.h> #include <set> #include <string> #include <string.h> #include <stdlib.h> #include <stdint.h> #include <stdio.h> #include <netdb.h> #include <map> using namespace std; /////////////////////////////////////////////////////////////////////////////// // Some constants. // const char* PLUGIN_NAME = "header_normalize"; std::map<std::string, std::string, std::less<std::string> > hdrMap; static void buildHdrMap() { hdrMap["accept"] = "Accept"; hdrMap["accept-charset"] = "Accept-Charset"; hdrMap["accept-encoding"] = "Accept-Encoding"; hdrMap["accept-language"] = "Accept-Language"; hdrMap["accept-ranges"] = "Accept-Ranges"; hdrMap["age"] = "Age"; hdrMap["allow"] = "Allow"; hdrMap["approved"] = "Approved"; hdrMap["bytes"] = "Bytes"; hdrMap["cache-control"] = "Cache-Control"; hdrMap["client-ip"] = "Client-Ip"; hdrMap["connection"] = "Connection"; hdrMap["content-base"] = "Content-Base"; hdrMap["content-encoding"] = "Content-Encoding"; hdrMap["content-language"] = "Content-Language"; hdrMap["content-length"] = "Content-Length"; hdrMap["content-location"] = "Content-Location"; hdrMap["content-md5"] = "Content-MD5"; hdrMap["content-range"] = "Content-Range"; hdrMap["content-type"] = "Content-Type"; hdrMap["control"] = "Control"; hdrMap["cookie"] = "Cookie"; hdrMap["date"] = "Date"; hdrMap["distribution"] = "Distribution"; hdrMap["etag"] = "Etag"; hdrMap["expect"] = "Expect"; hdrMap["expires"] = "Expires"; hdrMap["followup-to"] = "Followup-To"; hdrMap["from"] = "From"; hdrMap["host"] = "Host"; hdrMap["if-match"] = "If-Match"; hdrMap["if-modified-since"] = "If-Modified-Since"; hdrMap["if-none-match"] = "If-None-Match"; hdrMap["if-range"] = "If-Range"; hdrMap["if-unmodified-since"] = "If-Unmodified-Since"; hdrMap["keep-alive"] = "Keep-Alive"; hdrMap["keywords"] = "Keywords"; hdrMap["last-modified"] = "Last-Modified"; hdrMap["lines"] = "Lines"; hdrMap["location"] = "Location"; hdrMap["max-forwards"] = "Max-Forwards"; hdrMap["message-id"] = "Message-Id"; hdrMap["newsgroups"] = "Newsgroups"; hdrMap["organization"] = "Organization"; hdrMap["path"] = "Path"; hdrMap["pragma"] = "Pragma"; hdrMap["proxy-authenticate"] = "Proxy-Authenticate"; hdrMap["proxy-authorization"] = "Proxy-Authorization"; hdrMap["proxy-connection"] = "Proxy-Connection"; hdrMap["public"] = "Public"; hdrMap["range"] = "Range"; hdrMap["references"] = "References"; hdrMap["referer"] = "Referer"; hdrMap["reply-to"] = "Reply-To"; hdrMap["retry-after"] = "Retry-After"; hdrMap["sender"] = "Sender"; hdrMap["server"] = "Server"; hdrMap["set-cookie"] = "Set-Cookie"; hdrMap["strict-transport-security"] = "Strict-Transport-Security"; hdrMap["subject"] = "Subject"; hdrMap["summary"] = "Summary"; hdrMap["te"] = "Te"; hdrMap["transfer-encoding"] = "Transfer-Encoding"; hdrMap["upgrade"] = "Upgrade"; hdrMap["user-agent"] = "User-Agent"; hdrMap["vary"] = "Vary"; hdrMap["via"] = "Via"; hdrMap["warning"] = "Warning"; hdrMap["www-authenticate"] = "Www-Authenticate"; hdrMap["xref"] = "Xref"; hdrMap["@datainfo"] = "@DataInfo"; hdrMap["x-id"] = "X-ID"; hdrMap["x-forwarded-for"] = "X-Forwarded-For"; hdrMap["sec-websocket-key"] = "Sec-WebSocket-Key"; hdrMap["sec-websocket-version"] = "Sec-WebSocket-Version"; } /////////////////////////////////////////////////////////////////////////////// // Initialize the plugin. // // // TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { if (!api_info) { strncpy(errbuf, "[tsremap_init] - Invalid TSREMAP_INTERFACE argument", errbuf_size - 1); return TS_ERROR; } if (api_info->tsremap_version < TSREMAP_VERSION) { snprintf(errbuf, errbuf_size - 1, "[tsremap_init] - Incorrect API version %ld.%ld", api_info->tsremap_version >> 16, (api_info->tsremap_version & 0xffff)); return TS_ERROR; } buildHdrMap(); TSDebug(PLUGIN_NAME, "plugin is succesfully initialized"); return TS_SUCCESS; } /////////////////////////////////////////////////////////////////////////////// // One instance per remap.config invocation. // TSReturnCode TSRemapNewInstance(int /* argc */, char * /* argv[] */, void ** /* ih */, char * /* errbuf */, int /* errbuf_size */) { return TS_SUCCESS; } void TSRemapDelteInstance(void * /* ih */) { } static int read_request_hook(TSCont /* contp */, TSEvent /* event */, void *edata) { TSHttpTxn rh = (TSHttpTxn) edata; TSMLoc hdr, next_hdr; TSMBuffer hdr_bufp; TSMLoc req_hdrs; if (TSHttpTxnClientReqGet(rh, &hdr_bufp, &req_hdrs) == TS_SUCCESS) { hdr = TSMimeHdrFieldGet(hdr_bufp, req_hdrs, 0); int n_mime_headers = TSMimeHdrFieldsCount(hdr_bufp, req_hdrs); TSDebug(PLUGIN_NAME, "*** Camel Casing %u hdrs in the request", n_mime_headers); for (int i = 0; i < n_mime_headers; ++i) { if (hdr == NULL) break; next_hdr = TSMimeHdrFieldNext(hdr_bufp, req_hdrs, hdr); int old_hdr_len; const char* old_hdr_name = TSMimeHdrFieldNameGet(hdr_bufp, req_hdrs, hdr, &old_hdr_len); // TSMimeHdrFieldNameGet returns the MIME_FIELD_NAME // for all MIME hdrs, which is always in Camel Case if (islower(old_hdr_name[0])) { TSDebug(PLUGIN_NAME, "*** non MIME Hdr %s, leaving it for now", old_hdr_name); TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; continue; } int hdr_value_len = 0; const char *hdr_value = TSMimeHdrFieldValueStringGet(hdr_bufp, req_hdrs, hdr, 0, &hdr_value_len); // hdr returned by TSMimeHdrFieldNameGet is already // in camel case, just destroy the lowercase spdy header // and replace it with TSMimeHdrFieldNameGet char* new_hdr_name = (char*)old_hdr_name; if (new_hdr_name) { TSMLoc new_hdr_loc; TSReturnCode rval = TSMimeHdrFieldCreateNamed(hdr_bufp, req_hdrs, new_hdr_name, old_hdr_len, &new_hdr_loc); if (rval == TS_SUCCESS) { TSDebug(PLUGIN_NAME, "*** hdr convert %s to %s", old_hdr_name, new_hdr_name); TSMimeHdrFieldValueStringSet(hdr_bufp, req_hdrs, new_hdr_loc, -1, hdr_value, hdr_value_len); TSMimeHdrFieldAppend(hdr_bufp, req_hdrs, new_hdr_loc); TSHandleMLocRelease(hdr_bufp, req_hdrs, new_hdr_loc); } TSMimeHdrFieldDestroy(hdr_bufp, req_hdrs, hdr); } else { TSDebug(PLUGIN_NAME, "*** can't find hdr %s in hdrMap", old_hdr_name); } TSHandleMLocRelease(hdr_bufp, req_hdrs, hdr); hdr = next_hdr; } TSHandleMLocRelease(hdr_bufp, TS_NULL_MLOC, req_hdrs); } TSHttpTxnReenable(rh, TS_EVENT_HTTP_CONTINUE); return 0; } void TSPluginInit(int /* argc */, const char * /* argv[] */) { TSDebug(PLUGIN_NAME, "initializing plugin"); TSCont contp; buildHdrMap(); contp = TSContCreate(read_request_hook, NULL); TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp); } /////////////////////////////////////////////////////////////////////////////// // This is the main "entry" point for the plugin, called for every request. // TSRemapStatus TSRemapDoRemap (void * /* ih */, TSHttpTxn rh, TSRemapRequestInfo * /* rri */) { read_request_hook(NULL, TS_EVENT_HTTP_READ_REQUEST_HDR, rh); return TSREMAP_DID_REMAP; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Magnus Jonsson & Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/file.hpp" #include "libtorrent/utf8.hpp" #include <sstream> #include <windows.h> namespace { // must be used to not leak memory in case something would throw class auto_localfree { public: auto_localfree(HLOCAL memory) : m_memory(memory) { } ~auto_localfree() { if (m_memory) LocalFree(m_memory); } private: HLOCAL m_memory; }; std::string utf8_native(std::string const& s) { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); ret.resize(size); return ret; } void throw_exception(const char* thrower) { DWORD err = GetLastError(); #ifdef UNICODE wchar_t *wbuffer = 0; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ALLOCATE_BUFFER , 0, err, 0, (LPWSTR)&wbuffer, 0, 0); auto_localfree auto_free(wbuffer); std::string tmp_utf8; libtorrent::wchar_utf8(wbuffer, tmp_utf8); char const* buffer = tmp_utf8.c_str(); #else char* buffer = 0; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ALLOCATE_BUFFER , 0, err, 0, (LPSTR)&buffer, 0, 0); auto_localfree auto_free(buffer); #endif std::stringstream s; s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL"); throw libtorrent::file_error(s.str()); } } namespace libtorrent { struct file::impl : boost::noncopyable { enum open_flags { read_flag = 1, write_flag = 2 }; enum seek_mode { seek_begin = FILE_BEGIN, seek_from_here = FILE_CURRENT, seek_end = FILE_END }; impl() { m_file_handle = INVALID_HANDLE_VALUE; } void open(const char *file_name, open_flags flags) { assert(file_name); assert(flags & (read_flag | write_flag)); DWORD access_mask = 0; if (flags & read_flag) access_mask |= GENERIC_READ; if (flags & write_flag) access_mask |= GENERIC_WRITE; assert(access_mask & (GENERIC_READ | GENERIC_WRITE)); #ifdef UNICODE std::wstring wfile_name(utf8_wchar(file_name)); HANDLE new_handle = CreateFile( (LPCWSTR)wfile_name.c_str() , access_mask , FILE_SHARE_READ , 0 , (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); #else HANDLE new_handle = CreateFile( utf8_native(file_name).c_str() , access_mask , FILE_SHARE_READ , 0 , (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); #endif if (new_handle == INVALID_HANDLE_VALUE) { std::stringstream s; throw_exception(file_name); } // will only close old file if the open succeeded close(); m_file_handle = new_handle; } void close() { if (m_file_handle != INVALID_HANDLE_VALUE) { CloseHandle(m_file_handle); m_file_handle = INVALID_HANDLE_VALUE; } } ~impl() { close(); } size_type write(const char* buffer, size_type num_bytes) { assert(buffer); assert(num_bytes > 0); assert((DWORD)num_bytes == num_bytes); DWORD bytes_written = 0; if (num_bytes != 0) { if (FALSE == WriteFile( m_file_handle , buffer , (DWORD)num_bytes , &bytes_written , 0)) { throw_exception("file::write"); } } return bytes_written; } size_type read(char* buffer, size_type num_bytes) { assert(buffer); assert(num_bytes > 0); assert((DWORD)num_bytes == num_bytes); DWORD bytes_read = 0; if (num_bytes != 0) { if (FALSE == ReadFile( m_file_handle , buffer , (DWORD)num_bytes , &bytes_read , 0)) { throw_exception("file::read"); } } return bytes_read; } void seek(size_type pos, seek_mode from_where) { assert(pos >= 0 || from_where != seek_begin); assert(pos <= 0 || from_where != seek_end); LARGE_INTEGER offs; offs.QuadPart = pos; if (FALSE == SetFilePointerEx( m_file_handle , offs , &offs , from_where)) { throw_exception("file::seek"); } } size_type tell() { LARGE_INTEGER offs; offs.QuadPart = 0; // is there any other way to get offset? if (FALSE == SetFilePointerEx( m_file_handle , offs , &offs , FILE_CURRENT)) { throw_exception("file::tell"); } size_type pos=offs.QuadPart; assert(pos>=0); return pos; } /* size_type size() { LARGE_INTEGER s; if (FALSE == GetFileSizeEx(m_file_handle, &s)) { throw_exception("file::size"); } size_type size = s.QuadPart; assert(size >= 0); return size; } */ private: HANDLE m_file_handle; }; } namespace libtorrent { const file::seek_mode file::begin(file::impl::seek_begin); const file::seek_mode file::end(file::impl::seek_end); const file::open_mode file::in(file::impl::read_flag); const file::open_mode file::out(file::impl::write_flag); file::file() : m_impl(new libtorrent::file::impl()) { } file::file(boost::filesystem::path const& p, open_mode m) : m_impl(new libtorrent::file::impl()) { open(p,m); } file::~file() { } void file::open(boost::filesystem::path const& p, open_mode m) { assert(p.is_complete()); m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask)); } void file::close() { m_impl->close(); } size_type file::write(const char* buffer, size_type num_bytes) { return m_impl->write(buffer, num_bytes); } size_type file::read(char* buffer, size_type num_bytes) { return m_impl->read(buffer, num_bytes); } void file::seek(size_type pos, seek_mode m) { m_impl->seek(pos,impl::seek_mode(m.m_val)); } size_type file::tell() { return m_impl->tell(); } } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, Magnus Jonsson & Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/file.hpp" #include "libtorrent/utf8.hpp" #include <sstream> #include <windows.h> namespace { // must be used to not leak memory in case something would throw class auto_localfree { public: auto_localfree(HLOCAL memory) : m_memory(memory) { } ~auto_localfree() { if (m_memory) LocalFree(m_memory); } private: HLOCAL m_memory; }; std::string utf8_native(std::string const& s) { std::wstring ws; libtorrent::utf8_wchar(s, ws); std::size_t size = wcstombs(0, ws.c_str(), 0); if (size == std::size_t(-1)) return s; std::string ret; ret.resize(size); size = wcstombs(&ret[0], ws.c_str(), size + 1); ret.resize(size-1); return ret; } void throw_exception(const char* thrower) { DWORD err = GetLastError(); #ifdef UNICODE wchar_t *wbuffer = 0; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ALLOCATE_BUFFER , 0, err, 0, (LPWSTR)&wbuffer, 0, 0); auto_localfree auto_free(wbuffer); std::string tmp_utf8; libtorrent::wchar_utf8(wbuffer, tmp_utf8); char const* buffer = tmp_utf8.c_str(); #else char* buffer = 0; FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_ALLOCATE_BUFFER , 0, err, 0, (LPSTR)&buffer, 0, 0); auto_localfree auto_free(buffer); #endif std::stringstream s; s << (thrower ? thrower : "NULL") << ": " << (buffer ? buffer : "NULL"); throw libtorrent::file_error(s.str()); } } namespace libtorrent { struct file::impl : boost::noncopyable { enum open_flags { read_flag = 1, write_flag = 2 }; enum seek_mode { seek_begin = FILE_BEGIN, seek_from_here = FILE_CURRENT, seek_end = FILE_END }; impl() { m_file_handle = INVALID_HANDLE_VALUE; } void open(const char *file_name, open_flags flags) { assert(file_name); assert(flags & (read_flag | write_flag)); DWORD access_mask = 0; if (flags & read_flag) access_mask |= GENERIC_READ; if (flags & write_flag) access_mask |= GENERIC_WRITE; assert(access_mask & (GENERIC_READ | GENERIC_WRITE)); #ifdef UNICODE std::wstring wfile_name(utf8_wchar(file_name)); HANDLE new_handle = CreateFile( (LPCWSTR)wfile_name.c_str() , access_mask , FILE_SHARE_READ , 0 , (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); #else HANDLE new_handle = CreateFile( utf8_native(file_name).c_str() , access_mask , FILE_SHARE_READ , 0 , (flags & write_flag)?OPEN_ALWAYS:OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); #endif if (new_handle == INVALID_HANDLE_VALUE) { std::stringstream s; throw_exception(file_name); } // will only close old file if the open succeeded close(); m_file_handle = new_handle; } void close() { if (m_file_handle != INVALID_HANDLE_VALUE) { CloseHandle(m_file_handle); m_file_handle = INVALID_HANDLE_VALUE; } } ~impl() { close(); } size_type write(const char* buffer, size_type num_bytes) { assert(buffer); assert(num_bytes > 0); assert((DWORD)num_bytes == num_bytes); DWORD bytes_written = 0; if (num_bytes != 0) { if (FALSE == WriteFile( m_file_handle , buffer , (DWORD)num_bytes , &bytes_written , 0)) { throw_exception("file::write"); } } return bytes_written; } size_type read(char* buffer, size_type num_bytes) { assert(buffer); assert(num_bytes > 0); assert((DWORD)num_bytes == num_bytes); DWORD bytes_read = 0; if (num_bytes != 0) { if (FALSE == ReadFile( m_file_handle , buffer , (DWORD)num_bytes , &bytes_read , 0)) { throw_exception("file::read"); } } return bytes_read; } void seek(size_type pos, seek_mode from_where) { assert(pos >= 0 || from_where != seek_begin); assert(pos <= 0 || from_where != seek_end); LARGE_INTEGER offs; offs.QuadPart = pos; if (FALSE == SetFilePointerEx( m_file_handle , offs , &offs , from_where)) { throw_exception("file::seek"); } } size_type tell() { LARGE_INTEGER offs; offs.QuadPart = 0; // is there any other way to get offset? if (FALSE == SetFilePointerEx( m_file_handle , offs , &offs , FILE_CURRENT)) { throw_exception("file::tell"); } size_type pos=offs.QuadPart; assert(pos>=0); return pos; } /* size_type size() { LARGE_INTEGER s; if (FALSE == GetFileSizeEx(m_file_handle, &s)) { throw_exception("file::size"); } size_type size = s.QuadPart; assert(size >= 0); return size; } */ private: HANDLE m_file_handle; }; } namespace libtorrent { const file::seek_mode file::begin(file::impl::seek_begin); const file::seek_mode file::end(file::impl::seek_end); const file::open_mode file::in(file::impl::read_flag); const file::open_mode file::out(file::impl::write_flag); file::file() : m_impl(new libtorrent::file::impl()) { } file::file(boost::filesystem::path const& p, open_mode m) : m_impl(new libtorrent::file::impl()) { open(p,m); } file::~file() { } void file::open(boost::filesystem::path const& p, open_mode m) { assert(p.is_complete()); m_impl->open(p.native_file_string().c_str(), impl::open_flags(m.m_mask)); } void file::close() { m_impl->close(); } size_type file::write(const char* buffer, size_type num_bytes) { return m_impl->write(buffer, num_bytes); } size_type file::read(char* buffer, size_type num_bytes) { return m_impl->read(buffer, num_bytes); } void file::seek(size_type pos, seek_mode m) { m_impl->seek(pos,impl::seek_mode(m.m_val)); } size_type file::tell() { return m_impl->tell(); } } <|endoftext|>
<commit_before>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "Lease.hxx" #include "fb_pool.hxx" #include "net/SocketProtocolError.hxx" FilteredSocketLease::FilteredSocketLease(FilteredSocket &_socket, Lease &lease, Event::Duration read_timeout, Event::Duration write_timeout, BufferedSocketHandler &_handler) noexcept :socket(&_socket), handler(_handler) { socket->Reinit(read_timeout, write_timeout, *this); lease_ref.Set(lease); } FilteredSocketLease::~FilteredSocketLease() noexcept { assert(IsReleased()); } void FilteredSocketLease::Release(bool reuse) noexcept { assert(!IsReleased()); assert(!lease_ref.released); // TODO: move buffers instead of copying the data size_t i = 0; while (true) { auto r = WritableBuffer<uint8_t>::FromVoid(socket->ReadBuffer()); if (r.empty()) break; auto &dest = input[i]; if (!dest.IsDefined()) dest.Allocate(fb_pool_get()); else if (dest.IsFull()) { ++i; assert(i < input.size()); continue; } auto w = dest.Write(); size_t n = std::min(r.size, w.size); assert(n > 0); std::move(r.data, r.data + n, w.data); socket->DisposeConsumed(n); dest.Append(n); } lease_ref.Release(reuse); socket = nullptr; } bool FilteredSocketLease::IsEmpty() const noexcept { if (IsReleased()) return IsReleasedEmpty(); else return socket->IsEmpty(); } size_t FilteredSocketLease::GetAvailable() const noexcept { if (IsReleased()) { size_t result = 0; for (const auto &i : input) result += i.GetAvailable(); return result; } else return socket->GetAvailable(); } WritableBuffer<void> FilteredSocketLease::ReadBuffer() const noexcept { return IsReleased() ? input.front().Read().ToVoid() : socket->ReadBuffer(); } void FilteredSocketLease::DisposeConsumed(size_t nbytes) noexcept { if (IsReleased()) { input.front().Consume(nbytes); MoveInput(); } else socket->DisposeConsumed(nbytes); } bool FilteredSocketLease::ReadReleased() noexcept { while (true) { if (IsReleasedEmpty()) return true; switch (handler.OnBufferedData()) { case BufferedResult::OK: if (IsReleasedEmpty() && !handler.OnBufferedEnd()) return false; break; case BufferedResult::BLOCKING: assert(!IsReleasedEmpty()); return true; case BufferedResult::MORE: case BufferedResult::AGAIN_OPTIONAL: case BufferedResult::AGAIN_EXPECT: break; case BufferedResult::CLOSED: return false; } } } bool FilteredSocketLease::Read(bool expect_more) noexcept { if (IsReleased()) return ReadReleased(); else return socket->Read(expect_more); } void FilteredSocketLease::MoveInput() noexcept { auto &dest = input.front(); for (size_t i = 1; !dest.IsFull() && i < input.size(); ++i) { auto &src = input[i]; dest.MoveFromAllowBothNull(src); src.FreeIfEmpty(); } } BufferedResult FilteredSocketLease::OnBufferedData() { while (true) { const auto result = handler.OnBufferedData(); if (result == BufferedResult::CLOSED) break; if (!IsReleased()) return result; /* since the BufferedSocket is gone already, we must handle the AGAIN result codes here */ if (result == BufferedResult::AGAIN_OPTIONAL && !IsEmpty()) continue; else if (result == BufferedResult::AGAIN_EXPECT) { if (IsEmpty()) { handler.OnBufferedError(std::make_exception_ptr(SocketClosedPrematurelyError())); break; } continue; } else break; } /* if the socket has been released, we must always report CLOSED to the released BufferedSocket instance, even if our handler still wants to consume the remaining buffer */ return BufferedResult::CLOSED; } DirectResult FilteredSocketLease::OnBufferedDirect(SocketDescriptor fd, FdType fd_type) { return handler.OnBufferedDirect(fd, fd_type); } bool FilteredSocketLease::OnBufferedClosed() noexcept { auto result = handler.OnBufferedClosed(); if (result && IsReleased()) { result = false; if (handler.OnBufferedRemaining(GetAvailable()) && IsEmpty() && !handler.OnBufferedEnd()) handler.OnBufferedError(std::make_exception_ptr(SocketClosedPrematurelyError())); } return result; } bool FilteredSocketLease::OnBufferedRemaining(size_t remaining) noexcept { auto result = handler.OnBufferedRemaining(remaining); if (result && IsReleased()) result = false; return result; } bool FilteredSocketLease::OnBufferedEnd() noexcept { return handler.OnBufferedEnd(); } bool FilteredSocketLease::OnBufferedWrite() { return handler.OnBufferedWrite(); } bool FilteredSocketLease::OnBufferedDrained() noexcept { return handler.OnBufferedDrained(); } bool FilteredSocketLease::OnBufferedTimeout() noexcept { return handler.OnBufferedTimeout(); } enum write_result FilteredSocketLease::OnBufferedBroken() noexcept { return handler.OnBufferedBroken(); } void FilteredSocketLease::OnBufferedError(std::exception_ptr e) noexcept { return handler.OnBufferedError(e); } <commit_msg>fs/Lease: move condition to `while`<commit_after>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION 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 "Lease.hxx" #include "fb_pool.hxx" #include "net/SocketProtocolError.hxx" FilteredSocketLease::FilteredSocketLease(FilteredSocket &_socket, Lease &lease, Event::Duration read_timeout, Event::Duration write_timeout, BufferedSocketHandler &_handler) noexcept :socket(&_socket), handler(_handler) { socket->Reinit(read_timeout, write_timeout, *this); lease_ref.Set(lease); } FilteredSocketLease::~FilteredSocketLease() noexcept { assert(IsReleased()); } void FilteredSocketLease::Release(bool reuse) noexcept { assert(!IsReleased()); assert(!lease_ref.released); // TODO: move buffers instead of copying the data size_t i = 0; while (true) { auto r = WritableBuffer<uint8_t>::FromVoid(socket->ReadBuffer()); if (r.empty()) break; auto &dest = input[i]; if (!dest.IsDefined()) dest.Allocate(fb_pool_get()); else if (dest.IsFull()) { ++i; assert(i < input.size()); continue; } auto w = dest.Write(); size_t n = std::min(r.size, w.size); assert(n > 0); std::move(r.data, r.data + n, w.data); socket->DisposeConsumed(n); dest.Append(n); } lease_ref.Release(reuse); socket = nullptr; } bool FilteredSocketLease::IsEmpty() const noexcept { if (IsReleased()) return IsReleasedEmpty(); else return socket->IsEmpty(); } size_t FilteredSocketLease::GetAvailable() const noexcept { if (IsReleased()) { size_t result = 0; for (const auto &i : input) result += i.GetAvailable(); return result; } else return socket->GetAvailable(); } WritableBuffer<void> FilteredSocketLease::ReadBuffer() const noexcept { return IsReleased() ? input.front().Read().ToVoid() : socket->ReadBuffer(); } void FilteredSocketLease::DisposeConsumed(size_t nbytes) noexcept { if (IsReleased()) { input.front().Consume(nbytes); MoveInput(); } else socket->DisposeConsumed(nbytes); } bool FilteredSocketLease::ReadReleased() noexcept { while (!IsReleasedEmpty()) { switch (handler.OnBufferedData()) { case BufferedResult::OK: if (IsReleasedEmpty() && !handler.OnBufferedEnd()) return false; break; case BufferedResult::BLOCKING: assert(!IsReleasedEmpty()); return true; case BufferedResult::MORE: case BufferedResult::AGAIN_OPTIONAL: case BufferedResult::AGAIN_EXPECT: break; case BufferedResult::CLOSED: return false; } } return true; } bool FilteredSocketLease::Read(bool expect_more) noexcept { if (IsReleased()) return ReadReleased(); else return socket->Read(expect_more); } void FilteredSocketLease::MoveInput() noexcept { auto &dest = input.front(); for (size_t i = 1; !dest.IsFull() && i < input.size(); ++i) { auto &src = input[i]; dest.MoveFromAllowBothNull(src); src.FreeIfEmpty(); } } BufferedResult FilteredSocketLease::OnBufferedData() { while (true) { const auto result = handler.OnBufferedData(); if (result == BufferedResult::CLOSED) break; if (!IsReleased()) return result; /* since the BufferedSocket is gone already, we must handle the AGAIN result codes here */ if (result == BufferedResult::AGAIN_OPTIONAL && !IsEmpty()) continue; else if (result == BufferedResult::AGAIN_EXPECT) { if (IsEmpty()) { handler.OnBufferedError(std::make_exception_ptr(SocketClosedPrematurelyError())); break; } continue; } else break; } /* if the socket has been released, we must always report CLOSED to the released BufferedSocket instance, even if our handler still wants to consume the remaining buffer */ return BufferedResult::CLOSED; } DirectResult FilteredSocketLease::OnBufferedDirect(SocketDescriptor fd, FdType fd_type) { return handler.OnBufferedDirect(fd, fd_type); } bool FilteredSocketLease::OnBufferedClosed() noexcept { auto result = handler.OnBufferedClosed(); if (result && IsReleased()) { result = false; if (handler.OnBufferedRemaining(GetAvailable()) && IsEmpty() && !handler.OnBufferedEnd()) handler.OnBufferedError(std::make_exception_ptr(SocketClosedPrematurelyError())); } return result; } bool FilteredSocketLease::OnBufferedRemaining(size_t remaining) noexcept { auto result = handler.OnBufferedRemaining(remaining); if (result && IsReleased()) result = false; return result; } bool FilteredSocketLease::OnBufferedEnd() noexcept { return handler.OnBufferedEnd(); } bool FilteredSocketLease::OnBufferedWrite() { return handler.OnBufferedWrite(); } bool FilteredSocketLease::OnBufferedDrained() noexcept { return handler.OnBufferedDrained(); } bool FilteredSocketLease::OnBufferedTimeout() noexcept { return handler.OnBufferedTimeout(); } enum write_result FilteredSocketLease::OnBufferedBroken() noexcept { return handler.OnBufferedBroken(); } void FilteredSocketLease::OnBufferedError(std::exception_ptr e) noexcept { return handler.OnBufferedError(e); } <|endoftext|>
<commit_before>extern "C" { #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <errno.h> } #include <cstring> #include <ios> #include <auss.hpp> #include "i3ipc++/ipc-util.hpp" namespace i3ipc { static std::string format_errno(const std::string& msg = std::string()) { auss_t a; if (msg.size() > 0) a << msg << ": "; a << "errno " << errno << " (" << strerror(errno) << ')'; return a; } errno_error::errno_error() : ipc_error(format_errno()) {} errno_error::errno_error(const std::string& msg) : ipc_error(format_errno(msg)) {} static const std::string g_i3_ipc_magic = "i3-ipc"; buf_t::buf_t(uint32_t payload_size) : size(sizeof(header_t) + payload_size) { data = new uint8_t[size]; header = (header_t*)data; payload = (char*)(data + sizeof(header_t)); strncpy(header->magic, g_i3_ipc_magic.c_str(), sizeof(header->magic)); header->size = payload_size; header->type = 0x0; } buf_t::~buf_t() { delete[] data; } void buf_t::realloc_payload_to_header() { uint8_t* new_data = new uint8_t[sizeof(header_t) + header->size]; memcpy(new_data, header, sizeof(header_t)); delete[] data; data = new_data; header = (header_t*)data; payload = (char*)(data + sizeof(header_t)); } int32_t i3_connect(const std::string& socket_path) { int32_t sockfd = socket(AF_LOCAL, SOCK_STREAM, 0); if (sockfd == -1) { throw errno_error("Could not create a socket"); } (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC); // What for? struct sockaddr_un addr; memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_LOCAL; strncpy(addr.sun_path, socket_path.c_str(), sizeof(addr.sun_path) - 1); if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) { throw errno_error("Failed to connect to i3"); } return sockfd; } void i3_disconnect(const int32_t sockfd) { close(sockfd); } std::shared_ptr<buf_t> i3_pack(const ClientMessageType type, const std::string& payload) { buf_t* buff = new buf_t(payload.length()); buff->header->type = static_cast<uint32_t>(type); strncpy(buff->payload, payload.c_str(), buff->header->size); return std::shared_ptr<buf_t>(buff); } ssize_t writeall(int fd, const uint8_t* buf, size_t count) { size_t written = 0; ssize_t n = 0; while (written < count) { n = write(fd, buf + written, count - written); if (n == -1) { if (errno == EINTR || errno == EAGAIN) continue; return n; } written += (size_t)n; } return written; } ssize_t swrite(int fd, const uint8_t* buf, size_t count) { ssize_t n; n = writeall(fd, buf, count); if (n == -1) throw errno_error(auss_t() << "Failed to write " << std::hex << fd); else return n; } void i3_send(const int32_t sockfd, const buf_t& buff) { swrite(sockfd, buff.data, buff.size); } std::shared_ptr<buf_t> i3_recv(const int32_t sockfd) throw (invalid_header_error, eof_error) { buf_t* buff = new buf_t(0); const uint32_t header_size = sizeof(header_t); { uint8_t* header = (uint8_t*)buff->header; uint32_t readed = 0; while (readed < header_size) { int n = read(sockfd, header + readed, header_size - readed); if (n == -1) { throw errno_error(auss_t() << "Failed to read header from socket 0x" << std::hex << sockfd); } if (n == 0) { throw eof_error("Unexpected EOF while reading header"); } readed += n; } } if (g_i3_ipc_magic != std::string(buff->header->magic, g_i3_ipc_magic.length())) { throw invalid_header_error("Invalid magic in reply"); } buff->realloc_payload_to_header(); { uint32_t readed = 0; int n; while (readed < buff->header->size) { if ((n = read(sockfd, buff->payload + readed, buff->header->size - readed)) == -1) { if (errno == EINTR || errno == EAGAIN) continue; throw errno_error(auss_t() << "Failed to read payload from socket 0x" << std::hex << sockfd); } readed += n; } } return std::shared_ptr<buf_t>(buff); } std::shared_ptr<buf_t> i3_msg(const int32_t sockfd, const ClientMessageType type, const std::string& payload) throw (invalid_header_error, eof_error) { auto send_buff = i3_pack(type, payload); i3_send(sockfd, *send_buff); auto recv_buff = i3_recv(sockfd); if (send_buff->header->type != recv_buff->header->type) { throw invalid_header_error(auss_t() << "Invalid reply type: Expected 0x" << std::hex << send_buff->header->type << ", got 0x" << recv_buff->header->type); } return recv_buff; } } <commit_msg>fix(ipc-util): Memory leak<commit_after>extern "C" { #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <errno.h> } #include <cstring> #include <ios> #include <auss.hpp> #include "i3ipc++/ipc-util.hpp" namespace i3ipc { static std::string format_errno(const std::string& msg = std::string()) { auss_t a; if (msg.size() > 0) a << msg << ": "; a << "errno " << errno << " (" << strerror(errno) << ')'; return a; } errno_error::errno_error() : ipc_error(format_errno()) {} errno_error::errno_error(const std::string& msg) : ipc_error(format_errno(msg)) {} static const std::string g_i3_ipc_magic = "i3-ipc"; buf_t::buf_t(uint32_t payload_size) : size(sizeof(header_t) + payload_size) { data = new uint8_t[size]; header = (header_t*)data; payload = (char*)(data + sizeof(header_t)); strncpy(header->magic, g_i3_ipc_magic.c_str(), sizeof(header->magic)); header->size = payload_size; header->type = 0x0; } buf_t::~buf_t() { delete[] data; } void buf_t::realloc_payload_to_header() { uint8_t* new_data = new uint8_t[sizeof(header_t) + header->size]; memcpy(new_data, header, sizeof(header_t)); delete[] data; data = new_data; header = (header_t*)data; payload = (char*)(data + sizeof(header_t)); } int32_t i3_connect(const std::string& socket_path) { int32_t sockfd = socket(AF_LOCAL, SOCK_STREAM, 0); if (sockfd == -1) { throw errno_error("Could not create a socket"); } (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC); // What for? struct sockaddr_un addr; memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_LOCAL; strncpy(addr.sun_path, socket_path.c_str(), sizeof(addr.sun_path) - 1); if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0) { throw errno_error("Failed to connect to i3"); } return sockfd; } void i3_disconnect(const int32_t sockfd) { close(sockfd); } std::shared_ptr<buf_t> i3_pack(const ClientMessageType type, const std::string& payload) { buf_t* buff = new buf_t(payload.length()); buff->header->type = static_cast<uint32_t>(type); strncpy(buff->payload, payload.c_str(), buff->header->size); return std::shared_ptr<buf_t>(buff); } ssize_t writeall(int fd, const uint8_t* buf, size_t count) { size_t written = 0; ssize_t n = 0; while (written < count) { n = write(fd, buf + written, count - written); if (n == -1) { if (errno == EINTR || errno == EAGAIN) continue; return n; } written += (size_t)n; } return written; } ssize_t swrite(int fd, const uint8_t* buf, size_t count) { ssize_t n; n = writeall(fd, buf, count); if (n == -1) throw errno_error(auss_t() << "Failed to write " << std::hex << fd); else return n; } void i3_send(const int32_t sockfd, const buf_t& buff) { swrite(sockfd, buff.data, buff.size); } std::shared_ptr<buf_t> i3_recv(const int32_t sockfd) throw (invalid_header_error, eof_error) { auto buff = std::make_shared<buf_t>(0); const uint32_t header_size = sizeof(header_t); { uint8_t* header = (uint8_t*)buff->header; uint32_t readed = 0; while (readed < header_size) { int n = read(sockfd, header + readed, header_size - readed); if (n == -1) { throw errno_error(auss_t() << "Failed to read header from socket 0x" << std::hex << sockfd); } if (n == 0) { throw eof_error("Unexpected EOF while reading header"); } readed += n; } } if (g_i3_ipc_magic != std::string(buff->header->magic, g_i3_ipc_magic.length())) { throw invalid_header_error("Invalid magic in reply"); } buff->realloc_payload_to_header(); { uint32_t readed = 0; int n; while (readed < buff->header->size) { if ((n = read(sockfd, buff->payload + readed, buff->header->size - readed)) == -1) { if (errno == EINTR || errno == EAGAIN) continue; throw errno_error(auss_t() << "Failed to read payload from socket 0x" << std::hex << sockfd); } readed += n; } } return buff; } std::shared_ptr<buf_t> i3_msg(const int32_t sockfd, const ClientMessageType type, const std::string& payload) throw (invalid_header_error, eof_error) { auto send_buff = i3_pack(type, payload); i3_send(sockfd, *send_buff); auto recv_buff = i3_recv(sockfd); if (send_buff->header->type != recv_buff->header->type) { throw invalid_header_error(auss_t() << "Invalid reply type: Expected 0x" << std::hex << send_buff->header->type << ", got 0x" << recv_buff->header->type); } return recv_buff; } } <|endoftext|>
<commit_before>/* Source file for the R3 surfel object property class */ //////////////////////////////////////////////////////////////////////// // INCLUDE FILES //////////////////////////////////////////////////////////////////////// #include "R3Surfels.h" //////////////////////////////////////////////////////////////////////// // Namespace //////////////////////////////////////////////////////////////////////// namespace gaps { //////////////////////////////////////////////////////////////////////// // CONSTRUCTORS/DESTRUCTORS //////////////////////////////////////////////////////////////////////// R3SurfelObjectProperty:: R3SurfelObjectProperty(int type, R3SurfelObject *object, RNScalar *operands, int noperands) : scene(NULL), scene_index(-1), object(object), operands(NULL), noperands(0), type(type) { // Check if operands were provided if ((noperands > 0) && (operands)) { // Copy operands this->noperands = noperands; this->operands = new RNScalar [ this->noperands ]; for (int i = 0; i < this->noperands; i++) { this->operands[i] = operands[i]; } } else { // Compute operands UpdateOperands(); } } R3SurfelObjectProperty:: R3SurfelObjectProperty(const R3SurfelObjectProperty& property) : scene(NULL), scene_index(-1), object(property.object), operands(NULL), noperands(0), type(property.type) { // Initialize operands if ((property.noperands > 0) && (property.operands)) { this->noperands = property.noperands; this->operands = new RNScalar [ this->noperands ]; for (int i = 0; i < this->noperands; i++) { this->operands[i] = property.operands[i]; } } } R3SurfelObjectProperty:: ~R3SurfelObjectProperty(void) { // Remove from scene (removes from everything) if (scene) scene->RemoveObjectProperty(this); // Delete operands if (operands) delete [] operands; } //////////////////////////////////////////////////////////////////////// // DISPLAY FUNCDTIONS //////////////////////////////////////////////////////////////////////// void R3SurfelObjectProperty:: Draw(RNFlags flags) const { // Draw property based on type switch (type) { case R3_SURFEL_OBJECT_PCA_PROPERTY: if (noperands == 21) { R3Point centroid(operands[0], operands[1], operands[2]); R3Vector axis1(operands[3], operands[4], operands[5]); R3Vector axis2(operands[6], operands[7], operands[8]); R3Vector axis3(operands[9], operands[10], operands[11]); RNScalar stddev1 = sqrt(operands[12]); RNScalar stddev2 = sqrt(operands[13]); RNScalar stddev3 = sqrt(operands[14]); RNScalar extent01 = operands[15]; RNScalar extent02 = operands[16]; RNScalar extent03 = operands[17]; RNScalar extent11 = operands[18]; RNScalar extent12 = operands[19]; RNScalar extent13 = operands[20]; // Draw normal glLineWidth(5); glBegin(GL_LINES); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 0, 1); R3LoadPoint(centroid); R3LoadPoint(centroid + extent13*axis3); glEnd(); // Draw stddevs glLineWidth(2); glBegin(GL_LINES); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(1, 0, 0); R3LoadPoint(centroid - stddev1 * axis1); R3LoadPoint(centroid + stddev1 * axis1); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 1, 0); R3LoadPoint(centroid - stddev2 * axis2); R3LoadPoint(centroid + stddev2 * axis2); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 0, 1); R3LoadPoint(centroid - stddev3 * axis3); R3LoadPoint(centroid + stddev3 * axis3); glEnd(); // Draw extents glLineWidth(1); glBegin(GL_LINES); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(1, 0, 0); R3LoadPoint(centroid + extent01 * axis1); R3LoadPoint(centroid + extent11 * axis1); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 1, 0); R3LoadPoint(centroid + extent02 * axis2); R3LoadPoint(centroid + extent12 * axis2); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 0, 1); R3LoadPoint(centroid + extent03 * axis3); R3LoadPoint(centroid + extent13 * axis3); glEnd(); } break; } } //////////////////////////////////////////////////////////////////////// // INTERNAL FUNCDTIONS //////////////////////////////////////////////////////////////////////// void R3SurfelObjectProperty:: UpdateOperands(void) { // Check if already uptodate if (noperands > 0) return; // Check property type switch(type) { case R3_SURFEL_OBJECT_PCA_PROPERTY: { // PCA Properties // noperands = 21 // operands[0-2]: centroid // operands[3-5]: xyz of axis1 // operands[6-8]: xyz of axis2 // operands[9-11]: xyz of axis3 // operands[12-14]: variances // operands[15-20]: extents // Allocate operands noperands = 21; operands = new RNScalar [ noperands ]; for (int i = 0; i < noperands; i++) operands[i] = 0; // Create pointset R3SurfelPointSet *pointset = object->PointSet(); if (!pointset) return; if (pointset->NPoints() < 3) { delete pointset; return; } // Compute principle axes RNScalar variances[3]; R3Point centroid = pointset->Centroid(); R3Triad triad = pointset->PrincipleAxes(&centroid, variances); // Check if positive z of triad is facing away from viewpoint(s) int npositive = 0, nnegative = 0; R3Plane plane(centroid, triad.Axis(2)); for (int i = 0; i < pointset->NPoints(); i++) { R3SurfelPoint *point = pointset->Point(i); R3SurfelBlock *block = point->Block(); if (!block) continue; R3SurfelNode *node = block->Node(); if (!node) continue; R3SurfelScan *scan = node->Scan(); if (!scan) continue; RNScalar d = R3SignedDistance(plane, scan->Viewpoint()); if (d < 0) nnegative++; else if (d > 0) npositive++; } // Rotate triad so that z is not backfacing to viewpoints if (nnegative > npositive) triad = R3Triad(triad[0], -triad[1], -triad[2]); // Find extents R3Box extent = R3null_box; for (int i = 0; i < pointset->NPoints(); i++) { R3SurfelPoint *point = pointset->Point(i); R3Point position = point->Position(); R3Vector vector = position - centroid; RNScalar x = triad.Axis(0).Dot(vector); RNScalar y = triad.Axis(1).Dot(vector); RNScalar z = triad.Axis(2).Dot(vector); extent.Union(R3Point(x, y, z)); } // Fill operands operands[0] = centroid.X(); operands[1] = centroid.Y(); operands[2] = centroid.Z(); operands[3] = triad.Axis(0).X(); operands[4] = triad.Axis(0).Y(); operands[5] = triad.Axis(0).Z(); operands[6] = triad.Axis(1).X(); operands[7] = triad.Axis(1).Y(); operands[8] = triad.Axis(1).Z(); operands[9] = triad.Axis(2).X(); operands[10] = triad.Axis(2).Y(); operands[11] = triad.Axis(2).Z(); operands[12] = variances[0]; operands[13] = variances[1]; operands[14] = variances[2]; operands[15] = extent[0][0]; operands[16] = extent[0][1]; operands[17] = extent[0][2]; operands[18] = extent[1][0]; operands[19] = extent[1][1]; operands[20] = extent[1][2]; // Delete pointset delete pointset; break; } } } } // namespace gaps <commit_msg>sfl2conf<commit_after>/* Source file for the R3 surfel object property class */ //////////////////////////////////////////////////////////////////////// // INCLUDE FILES //////////////////////////////////////////////////////////////////////// #include "R3Surfels.h" //////////////////////////////////////////////////////////////////////// // Namespace //////////////////////////////////////////////////////////////////////// namespace gaps { //////////////////////////////////////////////////////////////////////// // CONSTRUCTORS/DESTRUCTORS //////////////////////////////////////////////////////////////////////// R3SurfelObjectProperty:: R3SurfelObjectProperty(int type, R3SurfelObject *object, RNScalar *operands, int noperands) : scene(NULL), scene_index(-1), object(object), operands(NULL), noperands(0), type(type) { // Check if operands were provided if ((noperands > 0) && (operands)) { // Copy operands this->noperands = noperands; this->operands = new RNScalar [ this->noperands ]; for (int i = 0; i < this->noperands; i++) { this->operands[i] = operands[i]; } } else { // Compute operands UpdateOperands(); } } R3SurfelObjectProperty:: R3SurfelObjectProperty(const R3SurfelObjectProperty& property) : scene(NULL), scene_index(-1), object(property.object), operands(NULL), noperands(0), type(property.type) { // Initialize operands if ((property.noperands > 0) && (property.operands)) { this->noperands = property.noperands; this->operands = new RNScalar [ this->noperands ]; for (int i = 0; i < this->noperands; i++) { this->operands[i] = property.operands[i]; } } } R3SurfelObjectProperty:: ~R3SurfelObjectProperty(void) { // Remove from scene (removes from everything) if (scene) scene->RemoveObjectProperty(this); // Delete operands if (operands) delete [] operands; } //////////////////////////////////////////////////////////////////////// // DISPLAY FUNCDTIONS //////////////////////////////////////////////////////////////////////// void R3SurfelObjectProperty:: Draw(RNFlags flags) const { // Draw property based on type switch (type) { case R3_SURFEL_OBJECT_PCA_PROPERTY: if (noperands == 21) { R3Point centroid(operands[0], operands[1], operands[2]); R3Vector axis1(operands[3], operands[4], operands[5]); R3Vector axis2(operands[6], operands[7], operands[8]); R3Vector axis3(operands[9], operands[10], operands[11]); RNScalar stddev1 = sqrt(operands[12]); RNScalar stddev2 = sqrt(operands[13]); RNScalar stddev3 = sqrt(operands[14]); RNScalar extent01 = operands[15]; RNScalar extent02 = operands[16]; RNScalar extent03 = operands[17]; RNScalar extent11 = operands[18]; RNScalar extent12 = operands[19]; RNScalar extent13 = operands[20]; // Draw normal glLineWidth(5); glBegin(GL_LINES); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 0, 1); R3LoadPoint(centroid); R3LoadPoint(centroid + extent13*axis3); glEnd(); // Draw stddevs glLineWidth(2); glBegin(GL_LINES); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(1, 0, 0); R3LoadPoint(centroid - stddev1 * axis1); R3LoadPoint(centroid + stddev1 * axis1); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 1, 0); R3LoadPoint(centroid - stddev2 * axis2); R3LoadPoint(centroid + stddev2 * axis2); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 0, 1); R3LoadPoint(centroid - stddev3 * axis3); R3LoadPoint(centroid + stddev3 * axis3); glEnd(); // Draw extents glLineWidth(1); glBegin(GL_LINES); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(1, 0, 0); R3LoadPoint(centroid + extent01 * axis1); R3LoadPoint(centroid + extent11 * axis1); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 1, 0); R3LoadPoint(centroid + extent02 * axis2); R3LoadPoint(centroid + extent12 * axis2); if (flags[R3_SURFEL_COLOR_DRAW_FLAG]) glColor3d(0, 0, 1); R3LoadPoint(centroid + extent03 * axis3); R3LoadPoint(centroid + extent13 * axis3); glEnd(); } break; } } //////////////////////////////////////////////////////////////////////// // INTERNAL FUNCDTIONS //////////////////////////////////////////////////////////////////////// void R3SurfelObjectProperty:: UpdateOperands(void) { // Check if already uptodate if (noperands > 0) return; // Check object if (!object) return; // Check property type switch(type) { case R3_SURFEL_OBJECT_PCA_PROPERTY: { // PCA Properties // noperands = 21 // operands[0-2]: centroid // operands[3-5]: xyz of axis1 // operands[6-8]: xyz of axis2 // operands[9-11]: xyz of axis3 // operands[12-14]: variances // operands[15-20]: extents // Allocate operands noperands = 21; operands = new RNScalar [ noperands ]; for (int i = 0; i < noperands; i++) operands[i] = 0; // Create pointset R3SurfelPointSet *pointset = object->PointSet(); if (!pointset) return; if (pointset->NPoints() < 3) { delete pointset; return; } // Compute principle axes RNScalar variances[3]; R3Point centroid = pointset->Centroid(); R3Triad triad = pointset->PrincipleAxes(&centroid, variances); // Check if positive z of triad is facing away from viewpoint(s) int npositive = 0, nnegative = 0; R3Plane plane(centroid, triad.Axis(2)); for (int i = 0; i < pointset->NPoints(); i++) { R3SurfelPoint *point = pointset->Point(i); R3SurfelBlock *block = point->Block(); if (!block) continue; R3SurfelNode *node = block->Node(); if (!node) continue; R3SurfelScan *scan = node->Scan(); if (!scan) continue; RNScalar d = R3SignedDistance(plane, scan->Viewpoint()); if (d < 0) nnegative++; else if (d > 0) npositive++; } // Rotate triad so that z is not backfacing to viewpoints if (nnegative > npositive) triad = R3Triad(triad[0], -triad[1], -triad[2]); // Find extents R3Box extent = R3null_box; for (int i = 0; i < pointset->NPoints(); i++) { R3SurfelPoint *point = pointset->Point(i); R3Point position = point->Position(); R3Vector vector = position - centroid; RNScalar x = triad.Axis(0).Dot(vector); RNScalar y = triad.Axis(1).Dot(vector); RNScalar z = triad.Axis(2).Dot(vector); extent.Union(R3Point(x, y, z)); } // Fill operands operands[0] = centroid.X(); operands[1] = centroid.Y(); operands[2] = centroid.Z(); operands[3] = triad.Axis(0).X(); operands[4] = triad.Axis(0).Y(); operands[5] = triad.Axis(0).Z(); operands[6] = triad.Axis(1).X(); operands[7] = triad.Axis(1).Y(); operands[8] = triad.Axis(1).Z(); operands[9] = triad.Axis(2).X(); operands[10] = triad.Axis(2).Y(); operands[11] = triad.Axis(2).Z(); operands[12] = variances[0]; operands[13] = variances[1]; operands[14] = variances[2]; operands[15] = extent[0][0]; operands[16] = extent[0][1]; operands[17] = extent[0][2]; operands[18] = extent[1][0]; operands[19] = extent[1][1]; operands[20] = extent[1][2]; // Delete pointset delete pointset; break; } } } } // namespace gaps <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <limits> #include <string> #include <sstream> #include <vector> #include "janus_io.h" using namespace std; // These functions have no external dependencies vector<string> split(const string &str, char delim) { vector<string> elems; stringstream ss(str); string item; while (getline(ss, item, delim)) elems.push_back(item); return elems; } vector<janus_attribute> attributesFromStrings(const vector<string> &strings, int *templateIDIndex, int *fileNameIndex) { vector<janus_attribute> attributes; for (size_t i=0; i<strings.size(); i++) { const string &str = strings[i]; if (str == "Template_ID") *templateIDIndex = i; else if (str == "File_Name") *fileNameIndex = i; else if (str == "Frame") attributes.push_back(JANUS_FRAME); else if (str == "Right_Eye_X") attributes.push_back(JANUS_RIGHT_EYE_X); else if (str == "Right_Eye_Y") attributes.push_back(JANUS_RIGHT_EYE_Y); else if (str == "Left_Eye_X") attributes.push_back(JANUS_LEFT_EYE_X); else if (str == "Left_Eye_Y") attributes.push_back(JANUS_LEFT_EYE_Y); else if (str == "Nose_Base_X") attributes.push_back(JANUS_NOSE_BASE_X); else if (str == "Nose_Base_Y") attributes.push_back(JANUS_NOSE_BASE_Y); else attributes.push_back(JANUS_INVALID_ATTRIBUTE); } return attributes; } vector<double> valuesFromStrings(const vector<string> &strings, size_t templateIDIndex, size_t fileNameIndex) { vector<double> values; for (size_t i=0; i<strings.size(); i++) { if ((i == templateIDIndex) || (i == fileNameIndex)) continue; const string &str = strings[i]; if (str.empty()) values.push_back(numeric_limits<float>::quiet_NaN()); else values.push_back(atof(str.c_str())); } return values; } janus_error readMetadataFile(janus_metadata_file file_name, vector<string> &fileNames, vector<janus_template_id> &templateIDs, vector<janus_attribute_list> &attributeLists) { // Open file ifstream file(file_name); if (!file.is_open()) return JANUS_OPEN_ERROR; // Parse header string line; getline(file, line); int templateIDIndex = -1, fileNameIndex = -1; vector<janus_attribute> attributes = attributesFromStrings(split(line, ','), &templateIDIndex, &fileNameIndex); if (templateIDIndex == -1) return JANUS_MISSING_TEMPLATE_ID; if (fileNameIndex == -1) return JANUS_MISSING_FILE_NAME; // Parse rows while (getline(file, line)) { const vector<string> words = split(line, ','); // Make sure all files have the same template ID fileNames.push_back(words[fileNameIndex]); templateIDs.push_back(atoi(words[templateIDIndex].c_str())); vector<double> values = valuesFromStrings(words, templateIDIndex, fileNameIndex); if (values.size() != attributes.size()) return JANUS_PARSE_ERROR; const size_t n = attributes.size(); // Construct attribute list, removing missing fields janus_attribute_list attributeList; attributeList.size = 0; attributeList.attributes = new janus_attribute[n]; attributeList.values = new double[n]; for (size_t i=0; i<n; i++) { if (values[i] != values[i]) /* NaN */ continue; attributeList.attributes[attributeList.size] = attributes[i]; attributeList.values[attributeList.size] = values[i]; attributeList.size++; } attributeLists.push_back(attributeList); } file.close(); return JANUS_SUCCESS; } janus_error enrollTemplate(const vector<string> &fileNames, const vector<janus_template_id> &templateIDs, const vector<janus_attribute_list> &attributeLists, janus_flat_template flat_template, size_t *bytes) { for (size_t i=1; i<templateIDs.size(); i++) if (templateIDs[i] != templateIDs[0]) return JANUS_TEMPLATE_ID_MISMATCH; janus_template template_; JANUS_TRY(janus_initialize_template(&template_)) for (size_t i=0; i<fileNames.size(); i++) { janus_image image; JANUS_TRY(janus_read_image(fileNames[i].c_str(), &image)) JANUS_TRY(janus_add_image(image, attributeLists[i], template_)); janus_free_image(image); } JANUS_TRY(janus_finalize_template(template_, flat_template, bytes)); return JANUS_SUCCESS; } janus_error janus_enroll_template(janus_metadata_file name_file, janus_flat_template flat_template, size_t *bytes) { vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; janus_error error = readMetadataFile(name_file, fileNames, templateIDs, attributeLists); if (error != JANUS_SUCCESS) return error; return enrollTemplate(fileNames, templateIDs, attributeLists, flat_template, bytes); } janus_error janus_enroll_gallery(janus_metadata_file file_name, const char *gallery_file) { vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; janus_error error = readMetadataFile(file_name, fileNames, templateIDs, attributeLists); if (error != JANUS_SUCCESS) return error; janus_gallery incomplete_gallery; error = janus_initialize_gallery(&incomplete_gallery); if (error != JANUS_SUCCESS) return error; size_t i = 0; while (i < attributeLists.size()) { size_t j = i; while ((j < attributeLists.size()) && (templateIDs[j] == templateIDs[i])) j++; janus_flat_template template_ = new janus_data[janus_max_template_size()]; size_t bytes; enrollTemplate(vector<string>(fileNames.begin()+i, fileNames.begin()+j), vector<janus_template_id>(templateIDs.begin()+i, templateIDs.begin()+j), vector<janus_attribute_list>(attributeLists.begin()+i, attributeLists.begin()+j), template_, &bytes); error = janus_add_template(template_, bytes, templateIDs[i], incomplete_gallery); if (error != JANUS_SUCCESS) return error; } return janus_finalize_gallery(incomplete_gallery, gallery_file); } <commit_msg>added status messages to janus_enroll_gallery<commit_after>#include <fstream> #include <iostream> #include <limits> #include <string> #include <sstream> #include <vector> #include "janus_io.h" using namespace std; // These functions have no external dependencies vector<string> split(const string &str, char delim) { vector<string> elems; stringstream ss(str); string item; while (getline(ss, item, delim)) elems.push_back(item); return elems; } vector<janus_attribute> attributesFromStrings(const vector<string> &strings, int *templateIDIndex, int *fileNameIndex) { vector<janus_attribute> attributes; for (size_t i=0; i<strings.size(); i++) { const string &str = strings[i]; if (str == "Template_ID") *templateIDIndex = i; else if (str == "File_Name") *fileNameIndex = i; else if (str == "Frame") attributes.push_back(JANUS_FRAME); else if (str == "Right_Eye_X") attributes.push_back(JANUS_RIGHT_EYE_X); else if (str == "Right_Eye_Y") attributes.push_back(JANUS_RIGHT_EYE_Y); else if (str == "Left_Eye_X") attributes.push_back(JANUS_LEFT_EYE_X); else if (str == "Left_Eye_Y") attributes.push_back(JANUS_LEFT_EYE_Y); else if (str == "Nose_Base_X") attributes.push_back(JANUS_NOSE_BASE_X); else if (str == "Nose_Base_Y") attributes.push_back(JANUS_NOSE_BASE_Y); else attributes.push_back(JANUS_INVALID_ATTRIBUTE); } return attributes; } vector<double> valuesFromStrings(const vector<string> &strings, size_t templateIDIndex, size_t fileNameIndex) { vector<double> values; for (size_t i=0; i<strings.size(); i++) { if ((i == templateIDIndex) || (i == fileNameIndex)) continue; const string &str = strings[i]; if (str.empty()) values.push_back(numeric_limits<float>::quiet_NaN()); else values.push_back(atof(str.c_str())); } return values; } janus_error readMetadataFile(janus_metadata_file file_name, vector<string> &fileNames, vector<janus_template_id> &templateIDs, vector<janus_attribute_list> &attributeLists) { // Open file ifstream file(file_name); if (!file.is_open()) return JANUS_OPEN_ERROR; // Parse header string line; getline(file, line); int templateIDIndex = -1, fileNameIndex = -1; vector<janus_attribute> attributes = attributesFromStrings(split(line, ','), &templateIDIndex, &fileNameIndex); if (templateIDIndex == -1) return JANUS_MISSING_TEMPLATE_ID; if (fileNameIndex == -1) return JANUS_MISSING_FILE_NAME; // Parse rows while (getline(file, line)) { const vector<string> words = split(line, ','); // Make sure all files have the same template ID fileNames.push_back(words[fileNameIndex]); templateIDs.push_back(atoi(words[templateIDIndex].c_str())); vector<double> values = valuesFromStrings(words, templateIDIndex, fileNameIndex); if (values.size() != attributes.size()) return JANUS_PARSE_ERROR; const size_t n = attributes.size(); // Construct attribute list, removing missing fields janus_attribute_list attributeList; attributeList.size = 0; attributeList.attributes = new janus_attribute[n]; attributeList.values = new double[n]; for (size_t i=0; i<n; i++) { if (values[i] != values[i]) /* NaN */ continue; attributeList.attributes[attributeList.size] = attributes[i]; attributeList.values[attributeList.size] = values[i]; attributeList.size++; } attributeLists.push_back(attributeList); } file.close(); return JANUS_SUCCESS; } janus_error enrollTemplate(const vector<string> &fileNames, const vector<janus_template_id> &templateIDs, const vector<janus_attribute_list> &attributeLists, janus_flat_template flat_template, size_t *bytes) { for (size_t i=1; i<templateIDs.size(); i++) if (templateIDs[i] != templateIDs[0]) return JANUS_TEMPLATE_ID_MISMATCH; janus_template template_; JANUS_TRY(janus_initialize_template(&template_)) for (size_t i=0; i<fileNames.size(); i++) { janus_image image; JANUS_TRY(janus_read_image(fileNames[i].c_str(), &image)) JANUS_TRY(janus_add_image(image, attributeLists[i], template_)); janus_free_image(image); } JANUS_TRY(janus_finalize_template(template_, flat_template, bytes)); return JANUS_SUCCESS; } janus_error janus_enroll_template(janus_metadata_file name_file, janus_flat_template flat_template, size_t *bytes) { vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; janus_error error = readMetadataFile(name_file, fileNames, templateIDs, attributeLists); if (error != JANUS_SUCCESS) return error; return enrollTemplate(fileNames, templateIDs, attributeLists, flat_template, bytes); } janus_error janus_enroll_gallery(janus_metadata_file file_name, const char *gallery_file) { fprintf(stderr, "Enrolling 0/?"); vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; janus_error error = readMetadataFile(file_name, fileNames, templateIDs, attributeLists); if (error != JANUS_SUCCESS) return error; janus_gallery gallery; error = janus_initialize_gallery(&gallery); if (error != JANUS_SUCCESS) return error; size_t i = 0; while (i < attributeLists.size()) { fprintf(stderr, "\rEnrolling %zu/%zu", i, attributeLists.size()); size_t j = i; while ((j < attributeLists.size()) && (templateIDs[j] == templateIDs[i])) j++; janus_flat_template template_ = new janus_data[janus_max_template_size()]; size_t bytes; enrollTemplate(vector<string>(fileNames.begin()+i, fileNames.begin()+j), vector<janus_template_id>(templateIDs.begin()+i, templateIDs.begin()+j), vector<janus_attribute_list>(attributeLists.begin()+i, attributeLists.begin()+j), template_, &bytes); error = janus_add_template(template_, bytes, templateIDs[i], gallery); if (error != JANUS_SUCCESS) return error; i = j; } fprintf(stderr, "\rEnrolling %zu/%zu\n", i, attributeLists.size()); return janus_finalize_gallery(gallery, gallery_file); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include <catch.hpp> #include "Call.hpp" #include <map> using std::multimap; using std::pair; bool Call::completesBefore(const Call & call) const { return pid == call.pid && index < call.index && envelope.completesBefore(call.envelope); } bool Call::hasAncestors(const set<Call> & calls) const { for (auto other : calls) { assert(pid == other.pid); if (index >= other.index) { return false; } if (other.completesBefore(*this)) { return true; } } return false; } map<int, set<Call> > sort_by_procs(const set<Call> & calls) { map<int, set<Call> > result; for (auto call : calls) { result[call.pid].insert(call); } return result; } set<Call> filter_enabled(const set<Call> & calls) { set<Call> result; for (auto c : calls) { if (! c.hasAncestors(calls)) { result.insert(c); } } return result; } TEST_CASE("Testing Call::equals", "[call]") { REQUIRE(Call(1, 10, Envelope()) == Call(1, 10, Envelope())); REQUIRE(Call(1, 5, Envelope()) == Call(1, 5, Envelope())); REQUIRE(Call(0, 2, Envelope()) == Call(0, 2, Envelope())); // neq REQUIRE(Call(1, 10, Envelope()) != Call(1, 0, Envelope())); REQUIRE(Call(1, 5, Envelope()) != Call(2, 5, Envelope())); } TEST_CASE("Testing Call::lt", "[call]") { REQUIRE(!(Call(1, 10, Envelope()) < Call(1, 10, Envelope()))); REQUIRE(!(Call(1, 10, Envelope()) < Call(1, 5, Envelope()))); REQUIRE(!(Call(1, 10, Envelope()) < Call(0, 2, Envelope()))); REQUIRE((Call(1, 5, Envelope()) < Call(1, 10, Envelope()))); REQUIRE(!(Call(1, 5, Envelope()) < Call(1, 5, Envelope()))); REQUIRE(!(Call(1, 5, Envelope()) < Call(0, 2, Envelope()))); REQUIRE((Call(0, 2, Envelope()) < Call(1, 10, Envelope()))); REQUIRE((Call(0, 2, Envelope()) < Call(1, 5, Envelope()))); REQUIRE(!(Call(0, 2, Envelope()) < Call(0, 2, Envelope()))); } TEST_CASE("Testing sort_by_procs", "[call]") { set<Call> calls; calls.insert(Call(1, 10, Envelope())); calls.insert(Call(1, 5, Envelope())); calls.insert(Call(0, 2, Envelope())); auto procs = sort_by_procs(calls); auto proc1 = procs[0]; auto it = proc1.begin(); REQUIRE(it != proc1.end()); REQUIRE((*it) == Call(0, 2, Envelope())); it++; REQUIRE(it == proc1.end()); auto proc2 = procs[1]; it = proc2.begin(); REQUIRE(it != proc2.end()); REQUIRE((*it) == Call(1, 5, Envelope())); it++; REQUIRE(it != proc2.end()); REQUIRE((*it) == Call(1, 10, Envelope())); it++; REQUIRE(it == proc2.end()); auto proc3 = procs[10]; REQUIRE(proc3.size() == 0); } // DOI: 10.1007/978-3-642-03770-2_33 TEST_CASE("ISP Tool Update: Scalable MPI Verification", "example-1") { /* * P0: Isend(to P1, &h0) ; Barrier; Wait(h0); * P1: Irecv(*, &h1) ; Barrier; Wait(h1); * P2: Barrier; Isend(to P1, &h2); Wait(h2); */ const int P0 = 0, P1 = 1, P2 = 2; // GET THE SCHEDULE WHERE ALL PROCESSES ARE BLOCKED set<Call> trace; // P0: Call c1(P0, 0, Envelope::ISend(P1)); trace.insert(c1); Call c2(P0, 1, Envelope::Barrier()); trace.insert(c2); Call c3(P0, 2, Envelope::Wait(0)); //trace.insert(c3); REQUIRE(! c1.completesBefore(c2)); REQUIRE(! c2.completesBefore(c1)); // P1: Call c4(P1, 0, Envelope::IRecv(WILDCARD)); trace.insert(c4); Call c5(P1, 1, Envelope::Barrier()); trace.insert(c5); Call c6(P1, 2, Envelope::Wait(0)); //trace.insert(c6); REQUIRE(! c4.completesBefore(c5)); REQUIRE(! c5.completesBefore(c4)); // P2: Call c7(P2, 0, Envelope::Barrier()); trace.insert(c7); Call c8(P2, 1, Envelope::ISend(P1)); //trace.insert(c8); Call c9(P2, 2, Envelope::Wait(1)); //trace.insert(c9); auto procs = sort_by_procs(trace); set<Call> proc0 = procs[P0]; proc0 = filter_enabled(proc0); REQUIRE(2 == proc0.size()); REQUIRE(proc0.find(c1) != proc0.end()); REQUIRE(proc0.find(c2) != proc0.end()); } <commit_msg>The paper in the test case was wrong. Groups calls to allow for match-set.<commit_after>#define CATCH_CONFIG_MAIN #include <catch.hpp> #include "Call.hpp" #include <map> using std::multimap; using std::pair; bool Call::completesBefore(const Call & call) const { return pid == call.pid && index < call.index && envelope.completesBefore(call.envelope); } bool Call::hasAncestors(const set<Call> & calls) const { for (auto other : calls) { assert(pid == other.pid); if (index >= other.index) { return false; } if (other.completesBefore(*this)) { return true; } } return false; } map<int, set<Call> > sort_by_procs(const set<Call> & calls) { map<int, set<Call> > result; for (auto call : calls) { result[call.pid].insert(call); } return result; } set<Call> filter_enabled(const set<Call> & calls) { set<Call> result; for (auto c : calls) { if (! c.hasAncestors(calls)) { result.insert(c); } } return result; } enum class Match { Collective, ReceiveAny, Receive, Send, Wait, Unknown }; Match get_match(const Envelope &env) { if (env.isCollectiveType()) { return Match::Collective; } else if (env.isRecvType()) { return env.src == WILDCARD ? Match::ReceiveAny : Match::Receive; } else if (env.isSendType()) { return Match::Send; } else if (env.isWaitType()) { return Match::Wait; } return Match::Unknown; } map<Match, set<Call> > group_by_match(const set<Call> & enabled) { map<Match, set<Call> > result; for (auto call : enabled) { result[get_match(call.envelope)].insert(call); } return result; } TEST_CASE("Testing Call::equals", "[call]") { REQUIRE(Call(1, 10, Envelope()) == Call(1, 10, Envelope())); REQUIRE(Call(1, 5, Envelope()) == Call(1, 5, Envelope())); REQUIRE(Call(0, 2, Envelope()) == Call(0, 2, Envelope())); // neq REQUIRE(Call(1, 10, Envelope()) != Call(1, 0, Envelope())); REQUIRE(Call(1, 5, Envelope()) != Call(2, 5, Envelope())); } TEST_CASE("Testing Call::lt", "[call]") { REQUIRE(!(Call(1, 10, Envelope()) < Call(1, 10, Envelope()))); REQUIRE(!(Call(1, 10, Envelope()) < Call(1, 5, Envelope()))); REQUIRE(!(Call(1, 10, Envelope()) < Call(0, 2, Envelope()))); REQUIRE((Call(1, 5, Envelope()) < Call(1, 10, Envelope()))); REQUIRE(!(Call(1, 5, Envelope()) < Call(1, 5, Envelope()))); REQUIRE(!(Call(1, 5, Envelope()) < Call(0, 2, Envelope()))); REQUIRE((Call(0, 2, Envelope()) < Call(1, 10, Envelope()))); REQUIRE((Call(0, 2, Envelope()) < Call(1, 5, Envelope()))); REQUIRE(!(Call(0, 2, Envelope()) < Call(0, 2, Envelope()))); } TEST_CASE("Testing sort_by_procs", "[call]") { set<Call> calls; calls.insert(Call(1, 10, Envelope())); calls.insert(Call(1, 5, Envelope())); calls.insert(Call(0, 2, Envelope())); auto procs = sort_by_procs(calls); auto proc1 = procs[0]; auto it = proc1.begin(); REQUIRE(it != proc1.end()); REQUIRE((*it) == Call(0, 2, Envelope())); it++; REQUIRE(it == proc1.end()); auto proc2 = procs[1]; it = proc2.begin(); REQUIRE(it != proc2.end()); REQUIRE((*it) == Call(1, 5, Envelope())); it++; REQUIRE(it != proc2.end()); REQUIRE((*it) == Call(1, 10, Envelope())); it++; REQUIRE(it == proc2.end()); auto proc3 = procs[10]; REQUIRE(proc3.size() == 0); } // DOI: 10.1007/978-3-642-11261-4_12 TEST_CASE("ISP Tool Update: Scalable MPI Verification example-1", "example-1") { /* * P0: Isend(to P1, &h0) ; Barrier; Wait(h0); * P1: Irecv(*, &h1) ; Barrier; Wait(h1); * P2: Barrier; Isend(to P1, &h2); Wait(h2); */ const int P0 = 0, P1 = 1, P2 = 2; // GET THE SCHEDULE WHERE ALL PROCESSES ARE BLOCKED set<Call> trace; // P0: Call c1(P0, 0, Envelope::ISend(P1)); trace.insert(c1); Call c2(P0, 1, Envelope::Barrier()); trace.insert(c2); Call c3(P0, 2, Envelope::Wait(0)); //trace.insert(c3); REQUIRE(! c1.completesBefore(c2)); REQUIRE(! c2.completesBefore(c1)); // P1: Call c4(P1, 0, Envelope::IRecv(WILDCARD)); trace.insert(c4); Call c5(P1, 1, Envelope::Barrier()); trace.insert(c5); Call c6(P1, 2, Envelope::Wait(0)); //trace.insert(c6); REQUIRE(! c4.completesBefore(c5)); REQUIRE(! c5.completesBefore(c4)); // P2: Call c7(P2, 0, Envelope::Barrier()); trace.insert(c7); Call c8(P2, 1, Envelope::ISend(P1)); //trace.insert(c8); Call c9(P2, 2, Envelope::Wait(1)); //trace.insert(c9); auto procs = sort_by_procs(trace); set<Call> proc0 = procs[P0]; proc0 = filter_enabled(proc0); REQUIRE(2 == proc0.size()); REQUIRE(proc0.find(c1) != proc0.end()); REQUIRE(proc0.find(c2) != proc0.end()); } <|endoftext|>
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "MultiSoretDiffusion.h" template<> InputParameters validParams<SoretDiffusion>() { InputParameters params = validParams<Kernel>(); params.addClassDescription("Add Soret effect to Split formulation Cahn-Hilliard Kernel"); params.addRequiredCoupledVar("T", "Temperature"); params.addRequiredCoupledVar("c", "Concentration"); params.addRequiredParam<MaterialPropertyName>("diffname_1", "The diffusivity of Cu or Element 1 used with the kernel"); params.addRequiredParam<MaterialPropertyName>("diffname_2", "The diffusivity of Sn or Element 2 used with the kernel"); params.addParam<MaterialPropertyName>("Qname_1", "Qheat_1", "The material 1 name for the heat of transport"); params.addParam<MaterialPropertyName>("Qname_2", "Qheat_2", "The material 2 name for the heat of transport"); return params; } MultiSoretDiffusion::MultiSoretDiffusion(const InputParameters & parameters) : Kernel(parameters), _T_var(coupled("T")), _T(coupledValue("T")), _grad_T(coupledGradient("T")), _c_var(coupled("c")), _c(coupledValue("c")), _D1(getMaterialProperty<Real>("diffname_1")), _D2(getMaterialProperty<Real>("diffname_2")), _Q1(getMaterialProperty<Real>("Qname_1")), _Q2(getMaterialProperty<Real>("Qname_2")), _kb(8.617343e-5) // Boltzmann constant in eV/K { } Real MultiSoretDiffusion::computeQpResidual() { # use the term to represent the differences of D1,D2 and Q1 and Q2 (or something like this) Real T_term = _D[_qp] * _Q[_qp] * _c[_qp] / (_kb * _T[_qp] * _T[_qp]); return T_term * _grad_T[_qp] * _grad_test[_i][_qp]; } Real MultiSoretDiffusion::computeQpJacobian() { if (_c_var == _var.number()) //Requires c jacobian return computeQpCJacobian(); return 0.0; } Real MultiSoretDiffusion::computeQpOffDiagJacobian(unsigned int jvar) { if (_c_var == jvar) //Requires c jacobian return computeQpCJacobian(); else if (_T_var == jvar) //Requires T jacobian return _D[_qp] * _Q[_qp] * _c[_qp] * _grad_test[_i][_qp] * (_grad_phi[_j][_qp]/(_kb * _T[_qp] * _T[_qp]) - 2.0 * _grad_T[_qp] * _phi[_j][_qp] / (_kb * _T[_qp] * _T[_qp] * _T[_qp])); return 0.0; } Real MultiSoretDiffusion::computeQpCJacobian() { //Calculate the Jacobian for the c variable return _D[_qp] * _Q[_qp] * _phi[_j][_qp] * _grad_T[_qp] / (_kb * _T[_qp] * _T[_qp]) * _grad_test[_i][_qp]; } <commit_msg>Update MultiSorretDiffusion.C<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "MultiSoretDiffusion.h" template<> InputParameters validParams<SoretDiffusion>() { InputParameters params = validParams<Kernel>(); params.addClassDescription("Add Soret effect to Split formulation Cahn-Hilliard Kernel"); params.addRequiredCoupledVar("T", "Temperature"); params.addRequiredCoupledVar("c", "Concentration"); params.addRequiredParam<MaterialPropertyName>("diffname_1", "The diffusivity of Sn or Element 1 used with the kernel"); params.addRequiredParam<MaterialPropertyName>("diffname_2", "The diffusivity of Cu or Element 2 used with the kernel"); params.addParam<MaterialPropertyName>("Qname_1", "Qheat_1", "The material 1 name for the heat of transport"); params.addParam<MaterialPropertyName>("Qname_2", "Qheat_2", "The material 2 name for the heat of transport"); return params; } MultiSoretDiffusion::MultiSoretDiffusion(const InputParameters & parameters) : Kernel(parameters), _T_var(coupled("T")), _T(coupledValue("T")), _grad_T(coupledGradient("T")), _c_var(coupled("c")), _c(coupledValue("c")), _D1(getMaterialProperty<Real>("diffname_1")), _D2(getMaterialProperty<Real>("diffname_2")), _Q1(getMaterialProperty<Real>("Qname_1")), _Q2(getMaterialProperty<Real>("Qname_2")), _kb(8.617343e-5) // Boltzmann constant in eV/K { } Real MultiSoretDiffusion::computeQpResidual() { # use the term to represent the differences of D1,D2 and Q1 and Q2 (or something like this) Real T_term = _D[_qp] * _Q[_qp] * _c[_qp] / (_kb * _T[_qp] * _T[_qp]); return T_term * _grad_T[_qp] * _grad_test[_i][_qp]; } Real MultiSoretDiffusion::computeQpJacobian() { if (_c_var == _var.number()) //Requires c jacobian return computeQpCJacobian(); return 0.0; } Real MultiSoretDiffusion::computeQpOffDiagJacobian(unsigned int jvar) { if (_c_var == jvar) //Requires c jacobian return computeQpCJacobian(); else if (_T_var == jvar) //Requires T jacobian return _D[_qp] * _Q[_qp] * _c[_qp] * _grad_test[_i][_qp] * (_grad_phi[_j][_qp]/(_kb * _T[_qp] * _T[_qp]) - 2.0 * _grad_T[_qp] * _phi[_j][_qp] / (_kb * _T[_qp] * _T[_qp] * _T[_qp])); return 0.0; } Real MultiSoretDiffusion::computeQpCJacobian() { //Calculate the Jacobian for the c variable return _D[_qp] * _Q[_qp] * _phi[_j][_qp] * _grad_T[_qp] / (_kb * _T[_qp] * _T[_qp]) * _grad_test[_i][_qp]; } <|endoftext|>
<commit_before>#include "geocoder.h" #include <sstream> #include <deque> #include <set> #include <iostream> #include <algorithm> using namespace GeoNLP; Geocoder::Geocoder() { } std::string Geocoder::name_primary(const std::string &dname) { return dname + "/geonlp-primary.sqlite"; } std::string Geocoder::name_normalized_trie(const std::string &dname) { return dname + "/geonlp-normalized.trie"; } std::string Geocoder::name_normalized_id(const std::string &dname) { return dname + "/geonlp-normalized-id.kch"; } Geocoder::Geocoder(const std::string &dbname) { if ( !load(dbname) ) std::cerr << "Geocoder: error loading " << dbname << std::endl; } bool Geocoder::load(const std::string &dbname) { if (dbname == m_database_path && m_database_open) return true; // clean before loading anything drop(); bool error = false; try { m_database_path = dbname; if ( m_db.connect(name_primary(m_database_path).c_str(), SQLITE_OPEN_READONLY) != SQLITE_OK ) { error = true; std::cerr << "Error opening SQLite database\n"; } if ( !error && !check_version() ) { error = true; } // Limit Kyoto Cabinet caches m_database_norm_id.tune_map(32LL*1024LL*1024LL); // 64MB default //m_database_norm_id.tune_page_cache(32LL*1024LL*1024LL); // 64MB default if ( !error && !m_database_norm_id.open(name_normalized_id(m_database_path).c_str(), kyotocabinet::HashDB::OREADER | kyotocabinet::HashDB::ONOLOCK ) ) { error = true; std::cerr << "Error opening IDs database\n"; } if ( !error ) m_trie_norm.load(name_normalized_trie(m_database_path).c_str()); // throws exception on error m_database_open = true; } catch (sqlite3pp::database_error e) { error = true; std::cerr << "Geocoder SQLite exception: " << e.what() << std::endl; } catch (marisa::Exception e) { error = true; std::cerr << "Geocoder MARISA exception: " << e.what() << std::endl; } if (error) drop(); return !error; } bool Geocoder::load() { return load( m_database_path ); } void Geocoder::drop() { m_db.disconnect(); m_database_norm_id.close(); m_trie_norm.clear(); m_database_path = std::string(); m_database_open = false; } bool Geocoder::check_version() { return check_version("3"); } bool Geocoder::check_version(const char *supported) { // this cannot through exceptions try { sqlite3pp::query qry(m_db, "SELECT value FROM meta WHERE key=\"version\""); for (auto v: qry) { std::string n; v.getter() >> n; if ( n == supported ) return true; else { std::cerr << "Geocoder: wrong version of the database. Supported: " << supported << " / database version: " << n << std::endl; return false; } } } catch (sqlite3pp::database_error e) { std::cerr << "Geocoder exception while checking database version: " << e.what() << std::endl; return false; } return false; } #ifdef GEONLP_PRINT_DEBUG static std::string v2s(const std::vector<std::string> &v) { std::string s = "{"; for (auto i: v) { if (s.length() > 1) s += ", "; s += i; } s += "}"; return s; } #endif bool Geocoder::search(const std::vector<Postal::ParseResult> &parsed_query, std::vector<Geocoder::GeoResult> &result, size_t min_levels) { if (!m_database_open) return false; // parse query by libpostal std::vector< Postal::Hierarchy > parsed_result; Postal::result2hierarchy(parsed_query, parsed_result); result.clear(); m_levels_resolved = min_levels; #ifdef GEONLP_PRINT_DEBUG std::cout << "Search hierarchies:\n"; #endif #ifdef GEONLP_PRINT_DEBUG_QUERIES std::cout << "\n"; #endif try { // catch and process SQLite and other exceptions for (const auto &r: parsed_result) { #ifdef GEONLP_PRINT_DEBUG for (auto a: r) std::cout << v2s(a) << " / "; std::cout << "\n"; #endif m_query_count = 0; if ( r.size() >= m_levels_resolved || (r.size() == m_levels_resolved && result.size() < m_max_results) ) search(r, result); #ifdef GEONLP_PRINT_DEBUG_QUERIES else std::cout << "Skipping hierarchy since search result already has more levels than provided\n"; #endif #ifdef GEONLP_PRINT_DEBUG_QUERIES std::cout << "\n"; #endif } #ifdef GEONLP_PRINT_DEBUG std::cout << "\n"; #endif // fill the data for (GeoResult &r: result) { get_name(r.id, r.title, r.address, m_levels_in_title); r.type = get_type(r.id); sqlite3pp::query qry(m_db, "SELECT latitude, longitude FROM object_primary WHERE id=?"); qry.bind(1, r.id); for (auto v: qry) { // only one entry is expected v.getter() >> r.latitude >> r.longitude; break; } } } catch (sqlite3pp::database_error e) { std::cerr << "Geocoder exception: " << e.what() << std::endl; return false; } return true; } bool Geocoder::search(const Postal::Hierarchy &parsed, std::vector<Geocoder::GeoResult> &result, size_t level, long long int range0, long long int range1) { if ( level >= parsed.size() || (m_max_queries_per_hierarchy>0 && m_query_count > m_max_queries_per_hierarchy) ) return false; m_query_count++; std::set<long long int> ids_explored; /// keeps all ids which have been used to search further at this level // help structure keeping marisa-found search string with found ids struct IntermediateResult { std::string txt; index_id_value id; IntermediateResult(const std::string &t, index_id_value i): txt(t), id(i) {} bool operator<(const IntermediateResult &A) const { return ( txt.length() < A.txt.length() || (txt.length() == A.txt.length() && txt<A.txt) || (txt==A.txt && id<A.id) ); } }; std::deque<IntermediateResult> search_result; for (const std::string s: parsed[level]) { marisa::Agent agent; agent.set_query(s.c_str()); while (m_trie_norm.predictive_search(agent)) { std::string val; if ( m_database_norm_id.get( make_id_key( agent.key().id() ), &val) ) { index_id_value *idx, *idx1; if ( get_id_range(val, (level==0), range0, range1, &idx, &idx1) ) { for (; idx < idx1; ++idx) { long long int id = *idx; IntermediateResult r( std::string(agent.key().ptr(), agent.key().length()), id ); search_result.push_back(r); } } } else { std::cerr << "Internal inconsistency of the databases: TRIE " << agent.key().id() << "\n"; } } } std::sort(search_result.begin(), search_result.end()); bool last_level = ( level+1 >= parsed.size() ); for (const IntermediateResult &branch: search_result) { long long int id = branch.id; long long int last_subobject = id; if (ids_explored.count(id) > 0) continue; // has been looked into it already if (parsed.size() < m_levels_resolved || (parsed.size()==m_levels_resolved && result.size() >= m_max_results)) break; // this search cannot add more results ids_explored.insert(id); // are we interested in this result even if it doesn't have subregions? if (!last_level) { sqlite3pp::query qry(m_db, "SELECT last_subobject FROM hierarchy WHERE prim_id=?"); qry.bind(1, id); for (auto v: qry) { // only one entry is expected v.getter() >> last_subobject; break; } // check if we have results which are better than this one if it // does not have any subobjects if (m_levels_resolved > level+1 && id >= last_subobject) continue; // take the next search_result } if ( last_level || last_subobject <= id || !search(parsed, result, level+1, id, last_subobject) ) { size_t levels_resolved = level+1; if ( m_levels_resolved < levels_resolved ) { result.clear(); m_levels_resolved = levels_resolved; } if (m_levels_resolved == levels_resolved && (result.size() < m_max_results)) { bool have_already = false; for (const auto &r: result) if (r.id == id) { have_already = true; break; } if (!have_already) { GeoResult r; r.id = id; r.levels_resolved = levels_resolved; result.push_back(r); } } } } return !ids_explored.empty(); } void Geocoder::get_name(long long id, std::string &title, std::string &full, int levels_in_title) { long long int parent; std::string name; sqlite3pp::query qry(m_db, "SELECT name, parent FROM object_primary WHERE id=?"); qry.bind(1, id); for (auto v: qry) { // only one entry is expected v.getter() >> name >> parent; if (!full.empty()) full += ", "; full += name; if (levels_in_title > 0) { if (!title.empty()) title += ", "; title += name; } get_name(parent, title, full, levels_in_title-1); return; } } std::string Geocoder::get_type(long long id) { std::string name; sqlite3pp::query qry(m_db, "SELECT t.name FROM object_primary o JOIN type t ON t.id=o.type_id WHERE o.id=?"); qry.bind(1, id); for (auto v: qry) { std::string n; v.getter() >> n; if (!name.empty()) name += ", "; name += n; } return name; } bool Geocoder::get_id_range(std::string &v, bool full_range, index_id_value range0, index_id_value range1, index_id_value* *idx0, index_id_value* *idx1) { int sz = get_id_number_of_values(v); index_id_value* v0 = (index_id_value*)v.data(); if (sz == 0) return false; if (full_range) { *idx0 = v0; *idx1 = v0 + sz; return true; } *idx0 = std::lower_bound(v0, v0 + sz, range0); if (*idx0 - v0 >= sz) return false; *idx1 = std::upper_bound(v0, v0 + sz, range1); if (*idx1 - v0 >= sz && *(v0) > range1 ) return false; return true; } bool Geocoder::search_nearby( const std::vector< std::string > &name_query, const std::string &type_query, double latitude, double longitude, double radius, std::vector<GeoResult> &result, Postal &postal ) { if ( name_query.empty() && type_query.empty() ) return false; // rough estimates of distance (meters) per degree // const double dist_per_degree_lat = 111e3; const double dist_per_degree_lon = std::max(1000.0, M_PI/180.0 * 6378137.0 * cos(latitude)); try { std::string query_txt( "SELECT o.id, o.name, t.name, o.box_id, o.latitude, o.longitude " "FROM object_primary o " "JOIN type t ON o.type_id=t.id " "JOIN object_primary_rtree ON (o.box_id = object_primary_rtree.id) " "WHERE " ); if (!type_query.empty()) query_txt += " t.name LIKE '%" + type_query + "%' AND "; query_txt += "maxLat>=:minLat AND minLat<=:maxLat AND maxLon >= :minLon AND minLon <= :maxLon"; sqlite3pp::query qry(m_db, query_txt.c_str()); qry.bind(":minLat", latitude - radius/dist_per_degree_lat); qry.bind(":maxLat", latitude + radius/dist_per_degree_lat); qry.bind(":minLon", longitude - radius/dist_per_degree_lon); qry.bind(":maxLon", longitude + radius/dist_per_degree_lon); for (auto v: qry) { long long id, box_id; std::string name, type; double lat, lon; v.getter() >> id >> name >> type >> box_id >> lat >> lon; // check if distance is ok. note that the distance is expected // to be small (on the scale of the planet) { double dlat = dist_per_degree_lat * (latitude-lat); double dlon = dist_per_degree_lon * (longitude-lon); double dist = sqrt( dlat*dlat + dlon*dlon ); if ( dist > radius ) continue; // skip this result } // if name specified, check for it if ( !name_query.empty() ) { std::vector<std::string> expanded; postal.expand_string( name, expanded ); bool found = false; for ( auto q = name_query.cbegin(); !found && q != name_query.cend(); ++q ) for ( auto e = expanded.begin(); !found && e != expanded.end(); ++e ) found = ( e->find(*q) != std::string::npos ); if (!found) continue; // substring not found } GeoResult r; r.id = id; get_name(r.id, r.title, r.address, m_levels_in_title); r.type = get_type(r.id); r.latitude = lat; r.longitude = lon; r.levels_resolved = 1; // not used in this search result.push_back(r); if ( result.size() >= m_max_results) break; } } catch (sqlite3pp::database_error e) { std::cerr << "Geocoder exception: " << e.what() << std::endl; return false; } return true; } <commit_msg>angle to rad<commit_after>#include "geocoder.h" #include <sstream> #include <deque> #include <set> #include <iostream> #include <algorithm> using namespace GeoNLP; Geocoder::Geocoder() { } std::string Geocoder::name_primary(const std::string &dname) { return dname + "/geonlp-primary.sqlite"; } std::string Geocoder::name_normalized_trie(const std::string &dname) { return dname + "/geonlp-normalized.trie"; } std::string Geocoder::name_normalized_id(const std::string &dname) { return dname + "/geonlp-normalized-id.kch"; } Geocoder::Geocoder(const std::string &dbname) { if ( !load(dbname) ) std::cerr << "Geocoder: error loading " << dbname << std::endl; } bool Geocoder::load(const std::string &dbname) { if (dbname == m_database_path && m_database_open) return true; // clean before loading anything drop(); bool error = false; try { m_database_path = dbname; if ( m_db.connect(name_primary(m_database_path).c_str(), SQLITE_OPEN_READONLY) != SQLITE_OK ) { error = true; std::cerr << "Error opening SQLite database\n"; } if ( !error && !check_version() ) { error = true; } // Limit Kyoto Cabinet caches m_database_norm_id.tune_map(32LL*1024LL*1024LL); // 64MB default //m_database_norm_id.tune_page_cache(32LL*1024LL*1024LL); // 64MB default if ( !error && !m_database_norm_id.open(name_normalized_id(m_database_path).c_str(), kyotocabinet::HashDB::OREADER | kyotocabinet::HashDB::ONOLOCK ) ) { error = true; std::cerr << "Error opening IDs database\n"; } if ( !error ) m_trie_norm.load(name_normalized_trie(m_database_path).c_str()); // throws exception on error m_database_open = true; } catch (sqlite3pp::database_error e) { error = true; std::cerr << "Geocoder SQLite exception: " << e.what() << std::endl; } catch (marisa::Exception e) { error = true; std::cerr << "Geocoder MARISA exception: " << e.what() << std::endl; } if (error) drop(); return !error; } bool Geocoder::load() { return load( m_database_path ); } void Geocoder::drop() { m_db.disconnect(); m_database_norm_id.close(); m_trie_norm.clear(); m_database_path = std::string(); m_database_open = false; } bool Geocoder::check_version() { return check_version("3"); } bool Geocoder::check_version(const char *supported) { // this cannot through exceptions try { sqlite3pp::query qry(m_db, "SELECT value FROM meta WHERE key=\"version\""); for (auto v: qry) { std::string n; v.getter() >> n; if ( n == supported ) return true; else { std::cerr << "Geocoder: wrong version of the database. Supported: " << supported << " / database version: " << n << std::endl; return false; } } } catch (sqlite3pp::database_error e) { std::cerr << "Geocoder exception while checking database version: " << e.what() << std::endl; return false; } return false; } #ifdef GEONLP_PRINT_DEBUG static std::string v2s(const std::vector<std::string> &v) { std::string s = "{"; for (auto i: v) { if (s.length() > 1) s += ", "; s += i; } s += "}"; return s; } #endif bool Geocoder::search(const std::vector<Postal::ParseResult> &parsed_query, std::vector<Geocoder::GeoResult> &result, size_t min_levels) { if (!m_database_open) return false; // parse query by libpostal std::vector< Postal::Hierarchy > parsed_result; Postal::result2hierarchy(parsed_query, parsed_result); result.clear(); m_levels_resolved = min_levels; #ifdef GEONLP_PRINT_DEBUG std::cout << "Search hierarchies:\n"; #endif #ifdef GEONLP_PRINT_DEBUG_QUERIES std::cout << "\n"; #endif try { // catch and process SQLite and other exceptions for (const auto &r: parsed_result) { #ifdef GEONLP_PRINT_DEBUG for (auto a: r) std::cout << v2s(a) << " / "; std::cout << "\n"; #endif m_query_count = 0; if ( r.size() >= m_levels_resolved || (r.size() == m_levels_resolved && result.size() < m_max_results) ) search(r, result); #ifdef GEONLP_PRINT_DEBUG_QUERIES else std::cout << "Skipping hierarchy since search result already has more levels than provided\n"; #endif #ifdef GEONLP_PRINT_DEBUG_QUERIES std::cout << "\n"; #endif } #ifdef GEONLP_PRINT_DEBUG std::cout << "\n"; #endif // fill the data for (GeoResult &r: result) { get_name(r.id, r.title, r.address, m_levels_in_title); r.type = get_type(r.id); sqlite3pp::query qry(m_db, "SELECT latitude, longitude FROM object_primary WHERE id=?"); qry.bind(1, r.id); for (auto v: qry) { // only one entry is expected v.getter() >> r.latitude >> r.longitude; break; } } } catch (sqlite3pp::database_error e) { std::cerr << "Geocoder exception: " << e.what() << std::endl; return false; } return true; } bool Geocoder::search(const Postal::Hierarchy &parsed, std::vector<Geocoder::GeoResult> &result, size_t level, long long int range0, long long int range1) { if ( level >= parsed.size() || (m_max_queries_per_hierarchy>0 && m_query_count > m_max_queries_per_hierarchy) ) return false; m_query_count++; std::set<long long int> ids_explored; /// keeps all ids which have been used to search further at this level // help structure keeping marisa-found search string with found ids struct IntermediateResult { std::string txt; index_id_value id; IntermediateResult(const std::string &t, index_id_value i): txt(t), id(i) {} bool operator<(const IntermediateResult &A) const { return ( txt.length() < A.txt.length() || (txt.length() == A.txt.length() && txt<A.txt) || (txt==A.txt && id<A.id) ); } }; std::deque<IntermediateResult> search_result; for (const std::string s: parsed[level]) { marisa::Agent agent; agent.set_query(s.c_str()); while (m_trie_norm.predictive_search(agent)) { std::string val; if ( m_database_norm_id.get( make_id_key( agent.key().id() ), &val) ) { index_id_value *idx, *idx1; if ( get_id_range(val, (level==0), range0, range1, &idx, &idx1) ) { for (; idx < idx1; ++idx) { long long int id = *idx; IntermediateResult r( std::string(agent.key().ptr(), agent.key().length()), id ); search_result.push_back(r); } } } else { std::cerr << "Internal inconsistency of the databases: TRIE " << agent.key().id() << "\n"; } } } std::sort(search_result.begin(), search_result.end()); bool last_level = ( level+1 >= parsed.size() ); for (const IntermediateResult &branch: search_result) { long long int id = branch.id; long long int last_subobject = id; if (ids_explored.count(id) > 0) continue; // has been looked into it already if (parsed.size() < m_levels_resolved || (parsed.size()==m_levels_resolved && result.size() >= m_max_results)) break; // this search cannot add more results ids_explored.insert(id); // are we interested in this result even if it doesn't have subregions? if (!last_level) { sqlite3pp::query qry(m_db, "SELECT last_subobject FROM hierarchy WHERE prim_id=?"); qry.bind(1, id); for (auto v: qry) { // only one entry is expected v.getter() >> last_subobject; break; } // check if we have results which are better than this one if it // does not have any subobjects if (m_levels_resolved > level+1 && id >= last_subobject) continue; // take the next search_result } if ( last_level || last_subobject <= id || !search(parsed, result, level+1, id, last_subobject) ) { size_t levels_resolved = level+1; if ( m_levels_resolved < levels_resolved ) { result.clear(); m_levels_resolved = levels_resolved; } if (m_levels_resolved == levels_resolved && (result.size() < m_max_results)) { bool have_already = false; for (const auto &r: result) if (r.id == id) { have_already = true; break; } if (!have_already) { GeoResult r; r.id = id; r.levels_resolved = levels_resolved; result.push_back(r); } } } } return !ids_explored.empty(); } void Geocoder::get_name(long long id, std::string &title, std::string &full, int levels_in_title) { long long int parent; std::string name; sqlite3pp::query qry(m_db, "SELECT name, parent FROM object_primary WHERE id=?"); qry.bind(1, id); for (auto v: qry) { // only one entry is expected v.getter() >> name >> parent; if (!full.empty()) full += ", "; full += name; if (levels_in_title > 0) { if (!title.empty()) title += ", "; title += name; } get_name(parent, title, full, levels_in_title-1); return; } } std::string Geocoder::get_type(long long id) { std::string name; sqlite3pp::query qry(m_db, "SELECT t.name FROM object_primary o JOIN type t ON t.id=o.type_id WHERE o.id=?"); qry.bind(1, id); for (auto v: qry) { std::string n; v.getter() >> n; if (!name.empty()) name += ", "; name += n; } return name; } bool Geocoder::get_id_range(std::string &v, bool full_range, index_id_value range0, index_id_value range1, index_id_value* *idx0, index_id_value* *idx1) { int sz = get_id_number_of_values(v); index_id_value* v0 = (index_id_value*)v.data(); if (sz == 0) return false; if (full_range) { *idx0 = v0; *idx1 = v0 + sz; return true; } *idx0 = std::lower_bound(v0, v0 + sz, range0); if (*idx0 - v0 >= sz) return false; *idx1 = std::upper_bound(v0, v0 + sz, range1); if (*idx1 - v0 >= sz && *(v0) > range1 ) return false; return true; } bool Geocoder::search_nearby( const std::vector< std::string > &name_query, const std::string &type_query, double latitude, double longitude, double radius, std::vector<GeoResult> &result, Postal &postal ) { if ( name_query.empty() && type_query.empty() ) return false; // rough estimates of distance (meters) per degree // const double dist_per_degree_lat = 111e3; const double dist_per_degree_lon = std::max(1000.0, M_PI/180.0 * 6378137.0 * cos(latitude*M_PI/180.0)); try { std::string query_txt( "SELECT o.id, o.name, t.name, o.box_id, o.latitude, o.longitude " "FROM object_primary o " "JOIN type t ON o.type_id=t.id " "JOIN object_primary_rtree ON (o.box_id = object_primary_rtree.id) " "WHERE " ); if (!type_query.empty()) query_txt += " t.name LIKE '%" + type_query + "%' AND "; query_txt += "maxLat>=:minLat AND minLat<=:maxLat AND maxLon >= :minLon AND minLon <= :maxLon"; sqlite3pp::query qry(m_db, query_txt.c_str()); qry.bind(":minLat", latitude - radius/dist_per_degree_lat); qry.bind(":maxLat", latitude + radius/dist_per_degree_lat); qry.bind(":minLon", longitude - radius/dist_per_degree_lon); qry.bind(":maxLon", longitude + radius/dist_per_degree_lon); for (auto v: qry) { long long id, box_id; std::string name, type; double lat, lon; v.getter() >> id >> name >> type >> box_id >> lat >> lon; // check if distance is ok. note that the distance is expected // to be small (on the scale of the planet) { double dlat = dist_per_degree_lat * (latitude-lat); double dlon = dist_per_degree_lon * (longitude-lon); double dist = sqrt( dlat*dlat + dlon*dlon ); if ( dist > radius ) continue; // skip this result } // if name specified, check for it if ( !name_query.empty() ) { std::vector<std::string> expanded; postal.expand_string( name, expanded ); bool found = false; for ( auto q = name_query.cbegin(); !found && q != name_query.cend(); ++q ) for ( auto e = expanded.begin(); !found && e != expanded.end(); ++e ) found = ( e->find(*q) != std::string::npos ); if (!found) continue; // substring not found } GeoResult r; r.id = id; get_name(r.id, r.title, r.address, m_levels_in_title); r.type = get_type(r.id); r.latitude = lat; r.longitude = lon; r.levels_resolved = 1; // not used in this search result.push_back(r); if ( result.size() >= m_max_results) break; } } catch (sqlite3pp::database_error e) { std::cerr << "Geocoder exception: " << e.what() << std::endl; return false; } return true; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "buildgraph.h" #include "artifact.h" #include "projectbuilddata.h" #include "productbuilddata.h" #include <jsextensions/jsextensions.h> #include <jsextensions/moduleproperties.h> #include <language/language.h> #include <language/scriptengine.h> #include <logging/logger.h> #include <logging/translator.h> #include <tools/error.h> #include <tools/qbsassert.h> #include <QFile> namespace qbs { namespace Internal { static void setupProductScriptValue(ScriptEngine *engine, QScriptValue &productScriptValue, const ResolvedProductConstPtr &product, ScriptPropertyObserver *observer); class DependenciesFunction { public: DependenciesFunction(ScriptEngine *engine) : m_engine(engine) { } void init(QScriptValue &productScriptValue, const ResolvedProductConstPtr &product) { QScriptValue depfunc = m_engine->newFunction(&js_productDependencies); setProduct(depfunc, product.data()); QScriptValue descriptor = m_engine->newObject(); descriptor.setProperty(QLatin1String("get"), depfunc); descriptor.setProperty(QLatin1String("set"), m_engine->evaluate("(function(){})")); descriptor.setProperty(QLatin1String("enumerable"), true); m_engine->defineProperty(productScriptValue, QLatin1String("dependencies"), descriptor); } private: static QScriptValue js_productDependencies(QScriptContext *context, QScriptEngine *engine) { QScriptValue callee = context->callee(); const ResolvedProduct * const product = getProduct(callee); QScriptValue result = engine->newArray(); quint32 idx = 0; foreach (const ResolvedProductPtr &dependency, product->dependencies) { QScriptValue obj = engine->newObject(); setupProductScriptValue(static_cast<ScriptEngine *>(engine), obj, dependency, 0); result.setProperty(idx++, obj); } foreach (const ResolvedModuleConstPtr &dependency, product->modules) { QScriptValue obj = engine->newObject(); setupModuleScriptValue(static_cast<ScriptEngine *>(engine), obj, product->properties->value(), dependency->name); result.setProperty(idx++, obj); } return result; } static QScriptValue js_moduleDependencies(QScriptContext *context, QScriptEngine *engine) { QScriptValue callee = context->callee(); const QVariantMap modulesMap = callee.data().toVariant().toMap(); QScriptValue result = engine->newArray(); quint32 idx = 0; for (QVariantMap::const_iterator it = modulesMap.begin(); it != modulesMap.end(); ++it) { QScriptValue obj = engine->newObject(); obj.setProperty(QLatin1String("name"), it.key()); setupModuleScriptValue(static_cast<ScriptEngine *>(engine), obj, it.value().toMap(), it.key()); result.setProperty(idx++, obj); } return result; } static void setupModuleScriptValue(ScriptEngine *engine, QScriptValue &moduleScriptValue, const QVariantMap &propertyMap, const QString &moduleName) { const QVariantMap propMap = propertyMap.value(QLatin1String("modules")).toMap().value(moduleName).toMap(); for (QVariantMap::ConstIterator it = propMap.constBegin(); it != propMap.constEnd(); ++it) { const QVariant &value = it.value(); if (value.isValid() && (!value.canConvert<QVariantMap>() || it.key() != QLatin1String("modules"))) moduleScriptValue.setProperty(it.key(), engine->toScriptValue(value)); } QScriptValue depfunc = engine->newFunction(&js_moduleDependencies); depfunc.setData(engine->toScriptValue(propMap.value(QLatin1String("modules")))); QScriptValue descriptor = engine->newObject(); descriptor.setProperty(QLatin1String("get"), depfunc); descriptor.setProperty(QLatin1String("set"), engine->evaluate("(function(){})")); descriptor.setProperty(QLatin1String("enumerable"), true); engine->defineProperty(moduleScriptValue, QLatin1String("dependencies"), descriptor); moduleScriptValue.setProperty(QLatin1String("type"), QLatin1String("module")); } static void setProduct(QScriptValue scriptValue, const ResolvedProduct *product) { QVariant v; v.setValue<quintptr>(reinterpret_cast<quintptr>(product)); scriptValue.setData(scriptValue.engine()->newVariant(v)); } static const ResolvedProduct *getProduct(const QScriptValue &scriptValue) { const quintptr ptr = scriptValue.data().toVariant().value<quintptr>(); return reinterpret_cast<const ResolvedProduct *>(ptr); } ScriptEngine *m_engine; }; static void setupProductScriptValue(ScriptEngine *engine, QScriptValue &productScriptValue, const ResolvedProductConstPtr &product, ScriptPropertyObserver *observer) { ModuleProperties::init(productScriptValue, product); DependenciesFunction(engine).init(productScriptValue, product); const QVariantMap &propMap = product->properties->value(); for (QVariantMap::ConstIterator it = propMap.constBegin(); it != propMap.constEnd(); ++it) { const QVariant &value = it.value(); if (value.isValid() && (!value.canConvert<QVariantMap>() || it.key() != QLatin1String("modules"))) engine->setObservedProperty(productScriptValue, it.key(), engine->toScriptValue(value), observer); } } void setupScriptEngineForProduct(ScriptEngine *engine, const ResolvedProductConstPtr &product, const RuleConstPtr &rule, QScriptValue targetObject, ScriptPropertyObserver *observer) { ScriptEngine::ScriptValueCache * const cache = engine->scriptValueCache(); if (cache->observer != observer) { cache->project = 0; cache->product = 0; } if (cache->project != product->project) { cache->project = product->project.data(); cache->projectScriptValue = engine->newObject(); cache->projectScriptValue.setProperty(QLatin1String("filePath"), product->project->location.fileName()); cache->projectScriptValue.setProperty(QLatin1String("path"), FileInfo::path(product->project->location.fileName())); const QVariantMap &projectProperties = product->project->projectProperties(); for (QVariantMap::const_iterator it = projectProperties.begin(); it != projectProperties.end(); ++it) cache->projectScriptValue.setProperty(it.key(), engine->toScriptValue(it.value())); } targetObject.setProperty(QLatin1String("project"), cache->projectScriptValue); if (cache->product != product) { cache->product = product.data(); { QVariant v; v.setValue<void*>(&product->buildEnvironment); engine->setProperty("_qbs_procenv", v); } cache->productScriptValue = engine->newObject(); setupProductScriptValue(engine, cache->productScriptValue, product, observer); } targetObject.setProperty(QLatin1String("product"), cache->productScriptValue); // If the Rule is in a Module, set up the 'moduleName' property cache->productScriptValue.setProperty(QLatin1String("moduleName"), rule->module->name.isEmpty() ? QScriptValue() : rule->module->name); engine->import(rule->jsImports, targetObject, targetObject); JsExtensions::setupExtensions(rule->jsExtensions, targetObject); } bool findPath(Artifact *u, Artifact *v, QList<Artifact*> &path) { if (u == v) { path.append(v); return true; } for (ArtifactList::const_iterator it = u->children.begin(); it != u->children.end(); ++it) { if (findPath(*it, v, path)) { path.prepend(u); return true; } } return false; } /* * c must be built before p * p ----> c * p.children = c * c.parents = p * * also: children means i depend on or i am produced by * parent means "produced by me" or "depends on me" */ void connect(Artifact *p, Artifact *c) { QBS_CHECK(p != c); p->children.insert(c); c->parents.insert(p); p->topLevelProject->buildData->isDirty = true; } void loggedConnect(Artifact *u, Artifact *v, const Logger &logger) { QBS_CHECK(u != v); if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] connect '%1' -> '%2'") .arg(relativeArtifactFileName(u), relativeArtifactFileName(v)); } connect(u, v); } static bool existsPath(Artifact *u, Artifact *v) { if (u == v) return true; for (ArtifactList::const_iterator it = u->children.begin(); it != u->children.end(); ++it) if (existsPath(*it, v)) return true; return false; } bool safeConnect(Artifact *u, Artifact *v, const Logger &logger) { QBS_CHECK(u != v); if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] safeConnect: '%1' '%2'") .arg(relativeArtifactFileName(u), relativeArtifactFileName(v)); } if (existsPath(v, u)) { QList<Artifact *> circle; findPath(v, u, circle); logger.qbsTrace() << "[BG] safeConnect: circle detected " << toStringList(circle); return false; } connect(u, v); return true; } void disconnect(Artifact *u, Artifact *v, const Logger &logger) { if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] disconnect: '%1' '%2'") .arg(relativeArtifactFileName(u), relativeArtifactFileName(v)); } u->children.remove(v); v->parents.remove(u); } void removeGeneratedArtifactFromDisk(Artifact *artifact, const Logger &logger) { if (artifact->artifactType != Artifact::Generated) return; QFile file(artifact->filePath()); if (!file.exists()) return; logger.qbsDebug() << "removing " << artifact->fileName(); if (!file.remove()) { logger.qbsWarning() << QString::fromLocal8Bit("Cannot remove '%1'.") .arg(artifact->filePath()); } } QString relativeArtifactFileName(const Artifact *n) { const QString &buildDir = n->topLevelProject->buildDirectory; QString str = n->filePath(); if (str.startsWith(buildDir)) str.remove(0, buildDir.count()); if (str.startsWith('/')) str.remove(0, 1); return str; } Artifact *lookupArtifact(const ResolvedProductConstPtr &product, const QString &dirPath, const QString &fileName) { QList<Artifact *> artifacts = product->topLevelProject()->buildData->lookupArtifacts(dirPath, fileName); for (QList<Artifact *>::const_iterator it = artifacts.constBegin(); it != artifacts.constEnd(); ++it) { if ((*it)->product == product) return *it; } return 0; } Artifact *lookupArtifact(const ResolvedProductConstPtr &product, const QString &filePath) { QString dirPath, fileName; FileInfo::splitIntoDirectoryAndFileName(filePath, &dirPath, &fileName); return lookupArtifact(product, dirPath, fileName); } Artifact *lookupArtifact(const ResolvedProductConstPtr &product, const Artifact *artifact) { return lookupArtifact(product, artifact->dirPath(), artifact->fileName()); } Artifact *createArtifact(const ResolvedProductPtr &product, const SourceArtifactConstPtr &sourceArtifact, const Logger &logger) { Artifact *artifact = new Artifact(product->topLevelProject()); artifact->artifactType = Artifact::SourceFile; artifact->setFilePath(sourceArtifact->absoluteFilePath); artifact->fileTags = sourceArtifact->fileTags; artifact->properties = sourceArtifact->properties; insertArtifact(product, artifact, logger); return artifact; } void insertArtifact(const ResolvedProductPtr &product, Artifact *artifact, const Logger &logger) { QBS_CHECK(!artifact->product); QBS_CHECK(!artifact->filePath().isEmpty()); QBS_CHECK(!product->buildData->artifacts.contains(artifact)); #ifdef QT_DEBUG foreach (const ResolvedProductConstPtr &otherProduct, product->project->products) { if (lookupArtifact(otherProduct, artifact->filePath())) { if (artifact->artifactType == Artifact::Generated) { QString pl; pl.append(QString(" - %1 \n").arg(product->name)); foreach (const ResolvedProductConstPtr &p, product->project->products) { if (lookupArtifact(p, artifact->filePath())) pl.append(QString(" - %1 \n").arg(p->name)); } throw ErrorInfo(QString ("BUG: already inserted in this project: %1\n%2") .arg(artifact->filePath()).arg(pl)); } } } #endif product->buildData->artifacts.insert(artifact); artifact->product = product; product->topLevelProject()->buildData->insertIntoArtifactLookupTable(artifact); product->topLevelProject()->buildData->isDirty = true; if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] insert artifact '%1'") .arg(artifact->filePath()); } } static void dumpProductBuildDataInternal(const ResolvedProductConstPtr &product, Artifact *artifact, QByteArray indent) { Artifact *artifactInProduct = lookupArtifact(product, artifact->filePath()); if (artifactInProduct && artifactInProduct != artifact) { qFatal("\ntree corrupted. %p ('%s') resolves to %p ('%s')\n", artifact, qPrintable(artifact->filePath()), lookupArtifact(product, artifact->filePath()), qPrintable(lookupArtifact(product, artifact->filePath())->filePath())); } printf("%s", indent.constData()); printf("Artifact (%p) ", artifact); printf("%s%s %s [%s]", qPrintable(QString(toString(artifact->buildState).at(0))), artifactInProduct ? "" : " SBS", // SBS == side-by-side artifact from other product qPrintable(artifact->filePath()), qPrintable(artifact->fileTags.toStringList().join(QLatin1String(", ")))); printf("\n"); indent.append(" "); foreach (Artifact *child, artifact->children) { dumpProductBuildDataInternal(product, child, indent); } } void dumpProductBuildData(const ResolvedProductConstPtr &product) { foreach (Artifact *artifact, product->buildData->artifacts) if (artifact->parents.isEmpty()) dumpProductBuildDataInternal(product, artifact, QByteArray()); } } // namespace Internal } // namespace qbs <commit_msg>remove dumpProductBuildConfig<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "buildgraph.h" #include "artifact.h" #include "projectbuilddata.h" #include "productbuilddata.h" #include <jsextensions/jsextensions.h> #include <jsextensions/moduleproperties.h> #include <language/language.h> #include <language/scriptengine.h> #include <logging/logger.h> #include <logging/translator.h> #include <tools/error.h> #include <tools/qbsassert.h> #include <QFile> namespace qbs { namespace Internal { static void setupProductScriptValue(ScriptEngine *engine, QScriptValue &productScriptValue, const ResolvedProductConstPtr &product, ScriptPropertyObserver *observer); class DependenciesFunction { public: DependenciesFunction(ScriptEngine *engine) : m_engine(engine) { } void init(QScriptValue &productScriptValue, const ResolvedProductConstPtr &product) { QScriptValue depfunc = m_engine->newFunction(&js_productDependencies); setProduct(depfunc, product.data()); QScriptValue descriptor = m_engine->newObject(); descriptor.setProperty(QLatin1String("get"), depfunc); descriptor.setProperty(QLatin1String("set"), m_engine->evaluate("(function(){})")); descriptor.setProperty(QLatin1String("enumerable"), true); m_engine->defineProperty(productScriptValue, QLatin1String("dependencies"), descriptor); } private: static QScriptValue js_productDependencies(QScriptContext *context, QScriptEngine *engine) { QScriptValue callee = context->callee(); const ResolvedProduct * const product = getProduct(callee); QScriptValue result = engine->newArray(); quint32 idx = 0; foreach (const ResolvedProductPtr &dependency, product->dependencies) { QScriptValue obj = engine->newObject(); setupProductScriptValue(static_cast<ScriptEngine *>(engine), obj, dependency, 0); result.setProperty(idx++, obj); } foreach (const ResolvedModuleConstPtr &dependency, product->modules) { QScriptValue obj = engine->newObject(); setupModuleScriptValue(static_cast<ScriptEngine *>(engine), obj, product->properties->value(), dependency->name); result.setProperty(idx++, obj); } return result; } static QScriptValue js_moduleDependencies(QScriptContext *context, QScriptEngine *engine) { QScriptValue callee = context->callee(); const QVariantMap modulesMap = callee.data().toVariant().toMap(); QScriptValue result = engine->newArray(); quint32 idx = 0; for (QVariantMap::const_iterator it = modulesMap.begin(); it != modulesMap.end(); ++it) { QScriptValue obj = engine->newObject(); obj.setProperty(QLatin1String("name"), it.key()); setupModuleScriptValue(static_cast<ScriptEngine *>(engine), obj, it.value().toMap(), it.key()); result.setProperty(idx++, obj); } return result; } static void setupModuleScriptValue(ScriptEngine *engine, QScriptValue &moduleScriptValue, const QVariantMap &propertyMap, const QString &moduleName) { const QVariantMap propMap = propertyMap.value(QLatin1String("modules")).toMap().value(moduleName).toMap(); for (QVariantMap::ConstIterator it = propMap.constBegin(); it != propMap.constEnd(); ++it) { const QVariant &value = it.value(); if (value.isValid() && (!value.canConvert<QVariantMap>() || it.key() != QLatin1String("modules"))) moduleScriptValue.setProperty(it.key(), engine->toScriptValue(value)); } QScriptValue depfunc = engine->newFunction(&js_moduleDependencies); depfunc.setData(engine->toScriptValue(propMap.value(QLatin1String("modules")))); QScriptValue descriptor = engine->newObject(); descriptor.setProperty(QLatin1String("get"), depfunc); descriptor.setProperty(QLatin1String("set"), engine->evaluate("(function(){})")); descriptor.setProperty(QLatin1String("enumerable"), true); engine->defineProperty(moduleScriptValue, QLatin1String("dependencies"), descriptor); moduleScriptValue.setProperty(QLatin1String("type"), QLatin1String("module")); } static void setProduct(QScriptValue scriptValue, const ResolvedProduct *product) { QVariant v; v.setValue<quintptr>(reinterpret_cast<quintptr>(product)); scriptValue.setData(scriptValue.engine()->newVariant(v)); } static const ResolvedProduct *getProduct(const QScriptValue &scriptValue) { const quintptr ptr = scriptValue.data().toVariant().value<quintptr>(); return reinterpret_cast<const ResolvedProduct *>(ptr); } ScriptEngine *m_engine; }; static void setupProductScriptValue(ScriptEngine *engine, QScriptValue &productScriptValue, const ResolvedProductConstPtr &product, ScriptPropertyObserver *observer) { ModuleProperties::init(productScriptValue, product); DependenciesFunction(engine).init(productScriptValue, product); const QVariantMap &propMap = product->properties->value(); for (QVariantMap::ConstIterator it = propMap.constBegin(); it != propMap.constEnd(); ++it) { const QVariant &value = it.value(); if (value.isValid() && (!value.canConvert<QVariantMap>() || it.key() != QLatin1String("modules"))) engine->setObservedProperty(productScriptValue, it.key(), engine->toScriptValue(value), observer); } } void setupScriptEngineForProduct(ScriptEngine *engine, const ResolvedProductConstPtr &product, const RuleConstPtr &rule, QScriptValue targetObject, ScriptPropertyObserver *observer) { ScriptEngine::ScriptValueCache * const cache = engine->scriptValueCache(); if (cache->observer != observer) { cache->project = 0; cache->product = 0; } if (cache->project != product->project) { cache->project = product->project.data(); cache->projectScriptValue = engine->newObject(); cache->projectScriptValue.setProperty(QLatin1String("filePath"), product->project->location.fileName()); cache->projectScriptValue.setProperty(QLatin1String("path"), FileInfo::path(product->project->location.fileName())); const QVariantMap &projectProperties = product->project->projectProperties(); for (QVariantMap::const_iterator it = projectProperties.begin(); it != projectProperties.end(); ++it) cache->projectScriptValue.setProperty(it.key(), engine->toScriptValue(it.value())); } targetObject.setProperty(QLatin1String("project"), cache->projectScriptValue); if (cache->product != product) { cache->product = product.data(); { QVariant v; v.setValue<void*>(&product->buildEnvironment); engine->setProperty("_qbs_procenv", v); } cache->productScriptValue = engine->newObject(); setupProductScriptValue(engine, cache->productScriptValue, product, observer); } targetObject.setProperty(QLatin1String("product"), cache->productScriptValue); // If the Rule is in a Module, set up the 'moduleName' property cache->productScriptValue.setProperty(QLatin1String("moduleName"), rule->module->name.isEmpty() ? QScriptValue() : rule->module->name); engine->import(rule->jsImports, targetObject, targetObject); JsExtensions::setupExtensions(rule->jsExtensions, targetObject); } bool findPath(Artifact *u, Artifact *v, QList<Artifact*> &path) { if (u == v) { path.append(v); return true; } for (ArtifactList::const_iterator it = u->children.begin(); it != u->children.end(); ++it) { if (findPath(*it, v, path)) { path.prepend(u); return true; } } return false; } /* * c must be built before p * p ----> c * p.children = c * c.parents = p * * also: children means i depend on or i am produced by * parent means "produced by me" or "depends on me" */ void connect(Artifact *p, Artifact *c) { QBS_CHECK(p != c); p->children.insert(c); c->parents.insert(p); p->topLevelProject->buildData->isDirty = true; } void loggedConnect(Artifact *u, Artifact *v, const Logger &logger) { QBS_CHECK(u != v); if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] connect '%1' -> '%2'") .arg(relativeArtifactFileName(u), relativeArtifactFileName(v)); } connect(u, v); } static bool existsPath(Artifact *u, Artifact *v) { if (u == v) return true; for (ArtifactList::const_iterator it = u->children.begin(); it != u->children.end(); ++it) if (existsPath(*it, v)) return true; return false; } bool safeConnect(Artifact *u, Artifact *v, const Logger &logger) { QBS_CHECK(u != v); if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] safeConnect: '%1' '%2'") .arg(relativeArtifactFileName(u), relativeArtifactFileName(v)); } if (existsPath(v, u)) { QList<Artifact *> circle; findPath(v, u, circle); logger.qbsTrace() << "[BG] safeConnect: circle detected " << toStringList(circle); return false; } connect(u, v); return true; } void disconnect(Artifact *u, Artifact *v, const Logger &logger) { if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] disconnect: '%1' '%2'") .arg(relativeArtifactFileName(u), relativeArtifactFileName(v)); } u->children.remove(v); v->parents.remove(u); } void removeGeneratedArtifactFromDisk(Artifact *artifact, const Logger &logger) { if (artifact->artifactType != Artifact::Generated) return; QFile file(artifact->filePath()); if (!file.exists()) return; logger.qbsDebug() << "removing " << artifact->fileName(); if (!file.remove()) { logger.qbsWarning() << QString::fromLocal8Bit("Cannot remove '%1'.") .arg(artifact->filePath()); } } QString relativeArtifactFileName(const Artifact *n) { const QString &buildDir = n->topLevelProject->buildDirectory; QString str = n->filePath(); if (str.startsWith(buildDir)) str.remove(0, buildDir.count()); if (str.startsWith('/')) str.remove(0, 1); return str; } Artifact *lookupArtifact(const ResolvedProductConstPtr &product, const QString &dirPath, const QString &fileName) { QList<Artifact *> artifacts = product->topLevelProject()->buildData->lookupArtifacts(dirPath, fileName); for (QList<Artifact *>::const_iterator it = artifacts.constBegin(); it != artifacts.constEnd(); ++it) { if ((*it)->product == product) return *it; } return 0; } Artifact *lookupArtifact(const ResolvedProductConstPtr &product, const QString &filePath) { QString dirPath, fileName; FileInfo::splitIntoDirectoryAndFileName(filePath, &dirPath, &fileName); return lookupArtifact(product, dirPath, fileName); } Artifact *lookupArtifact(const ResolvedProductConstPtr &product, const Artifact *artifact) { return lookupArtifact(product, artifact->dirPath(), artifact->fileName()); } Artifact *createArtifact(const ResolvedProductPtr &product, const SourceArtifactConstPtr &sourceArtifact, const Logger &logger) { Artifact *artifact = new Artifact(product->topLevelProject()); artifact->artifactType = Artifact::SourceFile; artifact->setFilePath(sourceArtifact->absoluteFilePath); artifact->fileTags = sourceArtifact->fileTags; artifact->properties = sourceArtifact->properties; insertArtifact(product, artifact, logger); return artifact; } void insertArtifact(const ResolvedProductPtr &product, Artifact *artifact, const Logger &logger) { QBS_CHECK(!artifact->product); QBS_CHECK(!artifact->filePath().isEmpty()); QBS_CHECK(!product->buildData->artifacts.contains(artifact)); #ifdef QT_DEBUG foreach (const ResolvedProductConstPtr &otherProduct, product->project->products) { if (lookupArtifact(otherProduct, artifact->filePath())) { if (artifact->artifactType == Artifact::Generated) { QString pl; pl.append(QString(" - %1 \n").arg(product->name)); foreach (const ResolvedProductConstPtr &p, product->project->products) { if (lookupArtifact(p, artifact->filePath())) pl.append(QString(" - %1 \n").arg(p->name)); } throw ErrorInfo(QString ("BUG: already inserted in this project: %1\n%2") .arg(artifact->filePath()).arg(pl)); } } } #endif product->buildData->artifacts.insert(artifact); artifact->product = product; product->topLevelProject()->buildData->insertIntoArtifactLookupTable(artifact); product->topLevelProject()->buildData->isDirty = true; if (logger.traceEnabled()) { logger.qbsTrace() << QString::fromLocal8Bit("[BG] insert artifact '%1'") .arg(artifact->filePath()); } } } // namespace Internal } // namespace qbs <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <thread> #include <string> #include <sstream> #include <utility> #include <type_traits> #include <boost/variant.hpp> #include <boost/timer/timer.hpp> #include "variant.hpp" namespace test { template <typename T> struct string_to_number {}; template <> struct string_to_number<double> { double operator() (std::string const& str) const { return std::stod(str); } }; template <> struct string_to_number<int64_t> { int64_t operator() (std::string const& str) const { return std::stoll(str); } }; template <> struct string_to_number<uint64_t> { uint64_t operator() (std::string const& str) const { return std::stoull(str); } }; template <> struct string_to_number<bool> { bool operator() (std::string const& str) const { bool result; std::istringstream(str) >> std::boolalpha >> result; return result; } }; struct javascript_equal_visitor : util::static_visitor<bool> { template <typename T> bool operator() (T lhs, T rhs) const { return lhs == rhs; } template <typename T, class = typename std::enable_if<std::is_arithmetic<T>::value>::type > bool operator() (T lhs, std::string const& rhs) const { return lhs == string_to_number<T>()(rhs); } template <typename T, class = typename std::enable_if<std::is_arithmetic<T>::value>::type > bool operator() (std::string const& lhs, T rhs) const { return string_to_number<T>()(lhs) == rhs; } template <typename T0, typename T1> bool operator() (T0 lhs, T1 rhs) const { return lhs == rhs; } }; template <typename T> struct javascript_equal { javascript_equal(T const& lhs) : lhs_(lhs) {} bool operator() (T const& rhs) const { return util::apply_visitor(lhs_, rhs, test::javascript_equal_visitor()); } T const& lhs_; }; } int main (/*int argc, char** argv*/) { //typedef util::variant<int, std::string> variant_type; typedef util::variant<bool, int64_t, uint64_t, double, std::string> variant_type; variant_type v0(3.14159); variant_type v1(std::string("3.14159")); variant_type v2(1ULL); std::cerr << v0 << " == " << v1 << " -> " << std::boolalpha << util::apply_visitor(v0, v1, test::javascript_equal_visitor()) << std::endl; std::vector<variant_type> vec; vec.emplace_back(std::string("1")); vec.push_back(variant_type(2ULL)); vec.push_back(variant_type(3ULL)); vec.push_back(std::string("3.14159")); vec.emplace_back(3.14159); //auto itr = std::find_if(vec.begin(), vec.end(), [&v0](variant_type const& val) { // return util::apply_visitor(v0, val, test::javascript_equal_visitor()); // }); auto itr = std::find_if(vec.begin(), vec.end(),test::javascript_equal<variant_type>(v2)); if (itr != std::end(vec)) { std::cout << "found " << *itr << std::endl; } else { std::cout << "can't find " << v2 << '\n'; } return EXIT_SUCCESS; } <commit_msg>qualify c++11 int types<commit_after>#include <cstdint> #include <iostream> #include <vector> #include <thread> #include <string> #include <sstream> #include <utility> #include <type_traits> #include <boost/variant.hpp> #include <boost/timer/timer.hpp> #include "variant.hpp" namespace test { template <typename T> struct string_to_number {}; template <> struct string_to_number<double> { double operator() (std::string const& str) const { return std::stod(str); } }; template <> struct string_to_number<std::int64_t> { std::int64_t operator() (std::string const& str) const { return std::stoll(str); } }; template <> struct string_to_number<std::uint64_t> { std::uint64_t operator() (std::string const& str) const { return std::stoull(str); } }; template <> struct string_to_number<bool> { bool operator() (std::string const& str) const { bool result; std::istringstream(str) >> std::boolalpha >> result; return result; } }; struct javascript_equal_visitor : util::static_visitor<bool> { template <typename T> bool operator() (T lhs, T rhs) const { return lhs == rhs; } template <typename T, class = typename std::enable_if<std::is_arithmetic<T>::value>::type > bool operator() (T lhs, std::string const& rhs) const { return lhs == string_to_number<T>()(rhs); } template <typename T, class = typename std::enable_if<std::is_arithmetic<T>::value>::type > bool operator() (std::string const& lhs, T rhs) const { return string_to_number<T>()(lhs) == rhs; } template <typename T0, typename T1> bool operator() (T0 lhs, T1 rhs) const { return lhs == rhs; } }; template <typename T> struct javascript_equal { javascript_equal(T const& lhs) : lhs_(lhs) {} bool operator() (T const& rhs) const { return util::apply_visitor(lhs_, rhs, test::javascript_equal_visitor()); } T const& lhs_; }; } int main (/*int argc, char** argv*/) { typedef util::variant<bool, std::uint64_t, double, std::string> variant_type; variant_type v0(3.14159); variant_type v1(std::string("3.14159")); variant_type v2(1ULL); std::cerr << v0 << " == " << v1 << " -> " << std::boolalpha << util::apply_visitor(v0, v1, test::javascript_equal_visitor()) << std::endl; std::vector<variant_type> vec; vec.emplace_back(std::string("1")); vec.push_back(variant_type(2ULL)); vec.push_back(variant_type(3ULL)); vec.push_back(std::string("3.14159")); vec.emplace_back(3.14159); //auto itr = std::find_if(vec.begin(), vec.end(), [&v0](variant_type const& val) { // return util::apply_visitor(v0, val, test::javascript_equal_visitor()); // }); auto itr = std::find_if(vec.begin(), vec.end(),test::javascript_equal<variant_type>(v2)); if (itr != std::end(vec)) { std::cout << "found " << *itr << std::endl; } else { std::cout << "can't find " << v2 << '\n'; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "game.h" #include "git_versioning.h" #include <iostream> using std::cout; using std::endl; // in binding.cpp void register_all_classes( lua_State* L ); // in colortext.cpp void test_colored_text( ALLEGRO_FONT* font ); void Game::initialiseAllegro() { al_init(); al_install_mouse(); al_install_keyboard(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); } bool Game::createDisplay() { al_set_new_display_flags( ALLEGRO_RESIZABLE ); display = al_create_display( SCREEN_W, SCREEN_H ); if( display == nullptr ) return false; al_set_window_title( display, "My Game" ); resize(); return true; } void Game::resize() { width = al_get_display_width( display ); height = al_get_display_height( display ); scaleX = width / (float)SCREEN_W; scaleY = height / (float)SCREEN_H; cout << "X scale: " << scaleX << endl; cout << "Y scale: " << scaleY << endl; cout << endl; ALLEGRO_TRANSFORM trans; al_identity_transform(&trans); al_scale_transform(&trans, scaleX, scaleY); al_use_transform(&trans); } void Game::registerEventSources() { frameTimer = al_create_timer( 1.0 / 30.0 ); // 60 FPS scriptTimer = al_create_timer( 1.0 / 100.0 ); // Update script called 100x per second eventQueue = al_create_event_queue(); al_register_event_source( eventQueue, al_get_keyboard_event_source() ); al_register_event_source( eventQueue, al_get_mouse_event_source() ); al_register_event_source( eventQueue, al_get_display_event_source(display) ); al_register_event_source( eventQueue, al_get_timer_event_source(frameTimer) ); al_register_event_source( eventQueue, al_get_timer_event_source(scriptTimer) ); al_start_timer( frameTimer ); al_start_timer( scriptTimer ); } void Game::initialiseLua() { L = luaL_newstate(); luaL_openlibs( L ); register_all_classes( L ); lua_pushlightuserdata( L, this ); lua_setfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX ); lua_register( L, "quit", Game::quit ); lua_register( L, "setTimerDivider", Game::setTimerDivider ); FontBinding::push( L, font ); lua_setglobal( L, "fixed_font" ); RenderListBinding::push( L, renderlist ); lua_setglobal( L, "renderlist" ); LuaRef info = LuaRef::newTable( L ); info["width"] = SCREEN_W; info["height"] = SCREEN_H; info["gitver"] = GIT_REPO_VERSION_STR; info.push(); lua_setglobal( L, "info" ); } bool Game::boot() { renderlist = std::make_shared<RenderList>(); initialiseAllegro(); if( ! createDisplay() ) return false; registerEventSources(); font = std::make_shared<Font>( "data/fixed_font.tga", 0, 0 ); icon = al_load_bitmap( "data/icon.tga" ); if( !font || !icon ) return false; al_set_display_icon( display, icon ); initialiseLua(); FontPtr console_font = std::make_shared<Font>( "data/liberation_mono/LiberationMono-Bold.ttf", -16, ALLEGRO_TTF_NO_KERNING ); console = std::make_shared<Console>( L, console_font, SCREEN_W ); console->setOrder(255); console->print( std::string( "Está es una prueba\n^red^Bu bir test\nOne\t1\nTwo\t2\nÜç\t3\nDört\t4" ) ); console->print( std::string( "^yellow^" GIT_REPO_VERSION_STR )); return true; } void Game::setScene() { using std::make_shared; RenderListPtr rl = make_shared<RenderList>(); rl->add( make_shared<Rectangle>( SCREEN_W-480, SCREEN_H-35, SCREEN_W-330, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200))); rl->add( make_shared<Rectangle>( SCREEN_W-320, SCREEN_H-35, SCREEN_W-170, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200))); rl->add( make_shared<Rectangle>( SCREEN_W-160, SCREEN_H-35, SCREEN_W-10, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200))); fpsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-85, SCREEN_H-30 ); rl->add( fpsText ); spsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-245, SCREEN_H-30 ); rl->add( spsText ); memText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-405, SCREEN_H-30 ); rl->add( memText ); rl->setOrder( 254 ); renderlist->insert( std::move(rl) ); } void Game::run() { if( luaL_dofile( L, "scripts/main.lua" ) ) { std::cerr << lua_tostring( L, -1 ) << std::endl; return; } LuaRef luaUpdate( L, "update" ); LuaRef luaKeyEvent( L, "keyEvent" ); LuaRef luaMouseEvent( L, "mouseEvent" ); // Check scripts are sane. if( ! luaUpdate.isFunction() ) { std::cerr << "Lua update function is not defined." << std::endl; shouldStop = true; } if( ! luaKeyEvent.isFunction() ) { std::cerr << "Lua keyEvent function is not defined." << std::endl; shouldStop = true; } if( ! luaMouseEvent.isFunction() ) { std::cerr << "Lua mouseEvent function is not defined." << std::endl; shouldStop = true; } int fps_accum = 0; int fps_worst = 1000; int fps_best = 0; int sps_accum = 0; int sps_worst = 1000; int sps_best = 0; double update_time = al_get_time(); double t; bool redraw = false; bool scriptrun = false; while( ! shouldStop ) { ALLEGRO_EVENT event; al_wait_for_event( eventQueue, &event ); t = al_get_time(); if( t - update_time >= 1 ) // Every second ... { update_time = t; if( fps_best < fps_accum ) { fps_best = fps_accum; } if( fps_worst > fps_accum ) { fps_worst = fps_accum; } fpsText->clearText(); fpsText << "FPS: " << fps_accum << "/" << fps_best << "/" << fps_worst; fps_accum = 0; if( sps_best < sps_accum ) { sps_best = sps_accum; } if( sps_worst > sps_accum ) { sps_worst = sps_accum; } spsText->clearText(); spsText << "SPS: " << sps_accum << "/" << sps_best << "/" << sps_worst; sps_accum = 0; memText->clearText(); memText << "Lua Mem " << lua_gc( L, LUA_GCCOUNT, 0 ) << "kb"; } if( event.type == ALLEGRO_EVENT_DISPLAY_CLOSE ) break; try { if( event.type == ALLEGRO_EVENT_KEY_CHAR ) { if( event.keyboard.keycode == ALLEGRO_KEY_ESCAPE ) { if( console->isVisible() ) { console->toggleVisibility(); continue; } else { // We grab it here, as 'quit' may change depending // on what is happening. LuaRef quit( L, "quit" ); if( quit.isFunction() ) { quit(); } continue; } } if( console->isVisible() ) { if( console->injectKeyPress( event ) ) { redraw = true; continue; } } else { if( event.keyboard.keycode == ALLEGRO_KEY_TILDE ) { console->toggleVisibility(); continue; } } luaKeyEvent( al_get_time(), event.keyboard.keycode, event.keyboard.unichar ); } if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == frameTimer ) { redraw = true; } if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == scriptTimer ) { scriptrun = true; } if( scriptrun && al_is_event_queue_empty( eventQueue ) ) { sps_accum++; luaUpdate( t ); console->resume(); scriptrun = false; } if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN ) { luaMouseEvent( al_get_time(), "down", event.mouse.button ); } if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP ) { luaMouseEvent( al_get_time(), "up", event.mouse.button ); } if( event.type == ALLEGRO_EVENT_MOUSE_AXES || event.type == ALLEGRO_EVENT_MOUSE_WARPED ) { luaMouseEvent( al_get_time(), "move", event.mouse.button, event.mouse.x / scaleX, event.mouse.y / scaleY, event.mouse.z, event.mouse.dx / scaleX, event.mouse.dy / scaleY, event.mouse.dz ); } if( event.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY ) { luaMouseEvent( al_get_time(), "enter", event.mouse.button, event.mouse.x / scaleX, event.mouse.y / scaleY, event.mouse.z ); } if( event.type == ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY ) { luaMouseEvent( al_get_time(), "leave", event.mouse.button, event.mouse.x / scaleX, event.mouse.y / scaleY, event.mouse.z ); } } catch( LuaException &e ) { std::cerr << e.what() << std::endl; } if( event.type == ALLEGRO_EVENT_DISPLAY_RESIZE ) { al_acknowledge_resize( display ); resize(); redraw = true; } if( redraw && al_is_event_queue_empty( eventQueue ) ) { fps_accum++; redraw = false; al_clear_to_color( al_map_rgb( 43, 73, 46 ) ); renderlist->render(); console->render(); al_flip_display(); } } } void Game::deregisterEventSources() { if( eventQueue ) { al_destroy_event_queue( eventQueue ); eventQueue = nullptr; } } void Game::destroyDisplay() { if( display ) { al_destroy_display( display ); display = nullptr; } } Game::~Game() { console.reset(); if( L ) { lua_close( L ); } deregisterEventSources(); destroyDisplay(); } int Game::quit( lua_State *L ) { lua_getfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX ); Game* self = static_cast<Game*>(lua_touserdata( L, -1 )); self->shouldStop = true; return 0; } int Game::setTimerDivider( lua_State *L ) { static const char* keys[] = { "fps", "sps", nullptr }; lua_getfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX ); Game* self = static_cast<Game*>(lua_touserdata( L, -1 )); int which = luaL_checkoption( L, 1, nullptr, keys ); float divider = luaL_checknumber( L, 2 ); switch( which ) { case 0: al_set_timer_speed( self->frameTimer, 1.0 / divider ); break; case 1: al_set_timer_speed( self->scriptTimer, 1.0 / divider ); break; default: return luaL_error( L, "First parameter should be either 'fps' or 'sps'." ); break; } return 0; } <commit_msg>Linear filtering<commit_after>#include "game.h" #include "git_versioning.h" #include <iostream> using std::cout; using std::endl; // in binding.cpp void register_all_classes( lua_State* L ); // in colortext.cpp void test_colored_text( ALLEGRO_FONT* font ); void Game::initialiseAllegro() { al_init(); al_install_mouse(); al_install_keyboard(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); } bool Game::createDisplay() { al_set_new_display_flags( ALLEGRO_RESIZABLE ); display = al_create_display( SCREEN_W, SCREEN_H ); if( display == nullptr ) return false; al_set_window_title( display, "My Game" ); al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); resize(); return true; } void Game::resize() { width = al_get_display_width( display ); height = al_get_display_height( display ); scaleX = width / (float)SCREEN_W; scaleY = height / (float)SCREEN_H; cout << "X scale: " << scaleX << endl; cout << "Y scale: " << scaleY << endl; cout << endl; ALLEGRO_TRANSFORM trans; al_identity_transform(&trans); al_scale_transform(&trans, scaleX, scaleY); al_use_transform(&trans); } void Game::registerEventSources() { frameTimer = al_create_timer( 1.0 / 30.0 ); // 60 FPS scriptTimer = al_create_timer( 1.0 / 100.0 ); // Update script called 100x per second eventQueue = al_create_event_queue(); al_register_event_source( eventQueue, al_get_keyboard_event_source() ); al_register_event_source( eventQueue, al_get_mouse_event_source() ); al_register_event_source( eventQueue, al_get_display_event_source(display) ); al_register_event_source( eventQueue, al_get_timer_event_source(frameTimer) ); al_register_event_source( eventQueue, al_get_timer_event_source(scriptTimer) ); al_start_timer( frameTimer ); al_start_timer( scriptTimer ); } void Game::initialiseLua() { L = luaL_newstate(); luaL_openlibs( L ); register_all_classes( L ); lua_pushlightuserdata( L, this ); lua_setfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX ); lua_register( L, "quit", Game::quit ); lua_register( L, "setTimerDivider", Game::setTimerDivider ); FontBinding::push( L, font ); lua_setglobal( L, "fixed_font" ); RenderListBinding::push( L, renderlist ); lua_setglobal( L, "renderlist" ); LuaRef info = LuaRef::newTable( L ); info["width"] = SCREEN_W; info["height"] = SCREEN_H; info["gitver"] = GIT_REPO_VERSION_STR; info.push(); lua_setglobal( L, "info" ); } bool Game::boot() { renderlist = std::make_shared<RenderList>(); initialiseAllegro(); if( ! createDisplay() ) return false; registerEventSources(); font = std::make_shared<Font>( "data/fixed_font.tga", 0, 0 ); icon = al_load_bitmap( "data/icon.tga" ); if( !font || !icon ) return false; al_set_display_icon( display, icon ); initialiseLua(); FontPtr console_font = std::make_shared<Font>( "data/liberation_mono/LiberationMono-Bold.ttf", -16, ALLEGRO_TTF_NO_KERNING ); console = std::make_shared<Console>( L, console_font, SCREEN_W ); console->setOrder(255); console->print( std::string( "Está es una prueba\n^red^Bu bir test\nOne\t1\nTwo\t2\nÜç\t3\nDört\t4" ) ); console->print( std::string( "^yellow^" GIT_REPO_VERSION_STR )); return true; } void Game::setScene() { using std::make_shared; RenderListPtr rl = make_shared<RenderList>(); rl->add( make_shared<Rectangle>( SCREEN_W-480, SCREEN_H-35, SCREEN_W-330, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200))); rl->add( make_shared<Rectangle>( SCREEN_W-320, SCREEN_H-35, SCREEN_W-170, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200))); rl->add( make_shared<Rectangle>( SCREEN_W-160, SCREEN_H-35, SCREEN_W-10, SCREEN_H-5, 8, 8, al_map_rgba(58,68,115,200))); fpsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-85, SCREEN_H-30 ); rl->add( fpsText ); spsText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-245, SCREEN_H-30 ); rl->add( spsText ); memText = make_shared<Text>( font, al_map_rgb( 255, 255, 255 ), SCREEN_W-405, SCREEN_H-30 ); rl->add( memText ); rl->setOrder( 254 ); renderlist->insert( std::move(rl) ); } void Game::run() { if( luaL_dofile( L, "scripts/main.lua" ) ) { std::cerr << lua_tostring( L, -1 ) << std::endl; return; } LuaRef luaUpdate( L, "update" ); LuaRef luaKeyEvent( L, "keyEvent" ); LuaRef luaMouseEvent( L, "mouseEvent" ); // Check scripts are sane. if( ! luaUpdate.isFunction() ) { std::cerr << "Lua update function is not defined." << std::endl; shouldStop = true; } if( ! luaKeyEvent.isFunction() ) { std::cerr << "Lua keyEvent function is not defined." << std::endl; shouldStop = true; } if( ! luaMouseEvent.isFunction() ) { std::cerr << "Lua mouseEvent function is not defined." << std::endl; shouldStop = true; } int fps_accum = 0; int fps_worst = 1000; int fps_best = 0; int sps_accum = 0; int sps_worst = 1000; int sps_best = 0; double update_time = al_get_time(); double t; bool redraw = false; bool scriptrun = false; while( ! shouldStop ) { ALLEGRO_EVENT event; al_wait_for_event( eventQueue, &event ); t = al_get_time(); if( t - update_time >= 1 ) // Every second ... { update_time = t; if( fps_best < fps_accum ) { fps_best = fps_accum; } if( fps_worst > fps_accum ) { fps_worst = fps_accum; } fpsText->clearText(); fpsText << "FPS: " << fps_accum << "/" << fps_best << "/" << fps_worst; fps_accum = 0; if( sps_best < sps_accum ) { sps_best = sps_accum; } if( sps_worst > sps_accum ) { sps_worst = sps_accum; } spsText->clearText(); spsText << "SPS: " << sps_accum << "/" << sps_best << "/" << sps_worst; sps_accum = 0; memText->clearText(); memText << "Lua Mem " << lua_gc( L, LUA_GCCOUNT, 0 ) << "kb"; } if( event.type == ALLEGRO_EVENT_DISPLAY_CLOSE ) break; try { if( event.type == ALLEGRO_EVENT_KEY_CHAR ) { if( event.keyboard.keycode == ALLEGRO_KEY_ESCAPE ) { if( console->isVisible() ) { console->toggleVisibility(); continue; } else { // We grab it here, as 'quit' may change depending // on what is happening. LuaRef quit( L, "quit" ); if( quit.isFunction() ) { quit(); } continue; } } if( console->isVisible() ) { if( console->injectKeyPress( event ) ) { redraw = true; continue; } } else { if( event.keyboard.keycode == ALLEGRO_KEY_TILDE ) { console->toggleVisibility(); continue; } } luaKeyEvent( al_get_time(), event.keyboard.keycode, event.keyboard.unichar ); } if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == frameTimer ) { redraw = true; } if( event.type == ALLEGRO_EVENT_TIMER && event.timer.source == scriptTimer ) { scriptrun = true; } if( scriptrun && al_is_event_queue_empty( eventQueue ) ) { sps_accum++; luaUpdate( t ); console->resume(); scriptrun = false; } if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN ) { luaMouseEvent( al_get_time(), "down", event.mouse.button ); } if( event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP ) { luaMouseEvent( al_get_time(), "up", event.mouse.button ); } if( event.type == ALLEGRO_EVENT_MOUSE_AXES || event.type == ALLEGRO_EVENT_MOUSE_WARPED ) { luaMouseEvent( al_get_time(), "move", event.mouse.button, event.mouse.x / scaleX, event.mouse.y / scaleY, event.mouse.z, event.mouse.dx / scaleX, event.mouse.dy / scaleY, event.mouse.dz ); } if( event.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY ) { luaMouseEvent( al_get_time(), "enter", event.mouse.button, event.mouse.x / scaleX, event.mouse.y / scaleY, event.mouse.z ); } if( event.type == ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY ) { luaMouseEvent( al_get_time(), "leave", event.mouse.button, event.mouse.x / scaleX, event.mouse.y / scaleY, event.mouse.z ); } } catch( LuaException &e ) { std::cerr << e.what() << std::endl; } if( event.type == ALLEGRO_EVENT_DISPLAY_RESIZE ) { al_acknowledge_resize( display ); resize(); redraw = true; } if( redraw && al_is_event_queue_empty( eventQueue ) ) { fps_accum++; redraw = false; al_clear_to_color( al_map_rgb( 43, 73, 46 ) ); renderlist->render(); console->render(); al_flip_display(); } } } void Game::deregisterEventSources() { if( eventQueue ) { al_destroy_event_queue( eventQueue ); eventQueue = nullptr; } } void Game::destroyDisplay() { if( display ) { al_destroy_display( display ); display = nullptr; } } Game::~Game() { console.reset(); if( L ) { lua_close( L ); } deregisterEventSources(); destroyDisplay(); } int Game::quit( lua_State *L ) { lua_getfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX ); Game* self = static_cast<Game*>(lua_touserdata( L, -1 )); self->shouldStop = true; return 0; } int Game::setTimerDivider( lua_State *L ) { static const char* keys[] = { "fps", "sps", nullptr }; lua_getfield( L, LUA_REGISTRYINDEX, LUA_GAME_INDEX ); Game* self = static_cast<Game*>(lua_touserdata( L, -1 )); int which = luaL_checkoption( L, 1, nullptr, keys ); float divider = luaL_checknumber( L, 2 ); switch( which ) { case 0: al_set_timer_speed( self->frameTimer, 1.0 / divider ); break; case 1: al_set_timer_speed( self->scriptTimer, 1.0 / divider ); break; default: return luaL_error( L, "First parameter should be either 'fps' or 'sps'." ); break; } return 0; } <|endoftext|>
<commit_before>#include <ncurses.h> #include <string> #include <random> #include "game.h" #include "menu.h" #include "classes/Player.h" #include "classes/Enemy.h" #include "classes/InfoPanel.h" using namespace std; InfoPanel *infoPanel_game = new InfoPanel(); Player player; Enemy enemy; rect game_area; void startGame() { game_area = { {0, 0}, {80, 40} }; WINDOW *wgame = newwin(40, 80, 1, 1); box(wgame, 0, 0); keypad(wgame, true); /* * Randomly place player anywhere in game area */ random_device rd; uniform_int_distribution<int> distx(game_area.left(), game_area.right()); uniform_int_distribution<int> disty(game_area.top(), game_area.bot()); int randx = distx(rd) + 1; int randy = disty(rd) + 1; // Cast int to vector's expected type vec2i initPos = { (int_fast8_t) randx, (int_fast8_t) randy }; player.setPos(initPos); wmove(wgame, player.getPos().y, player.getPos().x); waddch(wgame, player.getDispChar()); wmove(wgame, enemy.getPos().y, enemy.getPos().x); waddch(wgame, enemy.getDispChar()); int ch; string infoKey, infoMsg; while (( ch = wgetch(wgame)) != 'q') { infoMsg = ""; infoKey = to_string(ch); werase(wgame); box(wgame, 0, 0); int x = player.getPos().x; int y = player.getPos().y; switch (ch) { case KEY_UP: case 'k': if (y > (int) game_area.top() + 1) player.setPosY(y - 1); break; case KEY_DOWN: case 'j': if (y < (int) game_area.bot() - 2) player.setPosY(y + 1); break; case KEY_LEFT: case 'h': if (x > (int) game_area.left() + 1) player.setPosX(x - 1); break; case KEY_RIGHT: case 'l': if (x < (int) game_area.right() - 2) player.setPosX(x + 1); break; case KEY_ENTER: /* numpad enter */ case '\n': /* keyboard return */ break; } // Move to updates position (Player & Enemy) wmove(wgame, player.getPos().y, player.getPos().x); waddch(wgame, player.getDispChar()); wmove(wgame, enemy.getPos().y, enemy.getPos().x); waddch(wgame, enemy.getDispChar()); infoPanel_game->push('{' + std::to_string(x) + ',' + std::to_string(y) + '}' + " - right & left: {" + std::to_string(game_area.right()) + ',' + std::to_string(game_area.left()) + '}' + " top & bot: {" + std::to_string(game_area.top()) + ',' + std::to_string(game_area.bot()) + '}' ); wrefresh(wgame); } delwin(wgame); } <commit_msg>Use stdlib rand, srand for pseudo-random starts<commit_after>#include <ncurses.h> #include <time.h> #include <string> #include "game.h" #include "menu.h" #include "classes/Player.h" #include "classes/Enemy.h" #include "classes/InfoPanel.h" using namespace std; InfoPanel *infoPanel_game = new InfoPanel(); Player player; Enemy enemy; rect game_area; void startGame() { game_area = { {0, 0}, {80, 40} }; WINDOW *wgame = newwin(40, 80, 1, 1); box(wgame, 0, 0); keypad(wgame, true); /* * Randomly place player anywhere in game area */ srand(time(NULL)); int randx = rand() % game_area.right() + game_area.left(); int randy = rand() % game_area.bot() + game_area.top(); // Cast int to vector's expected type vec2i initPos = { (int_fast8_t) randx, (int_fast8_t) randy }; player.setPos(initPos); wmove(wgame, player.getPos().y, player.getPos().x); waddch(wgame, player.getDispChar()); wmove(wgame, enemy.getPos().y, enemy.getPos().x); waddch(wgame, enemy.getDispChar()); int ch; string infoKey, infoMsg; while (( ch = wgetch(wgame)) != 'q') { infoMsg = ""; infoKey = to_string(ch); werase(wgame); box(wgame, 0, 0); int x = player.getPos().x; int y = player.getPos().y; switch (ch) { case KEY_UP: case 'k': if (y > (int) game_area.top() + 1) player.setPosY(y - 1); break; case KEY_DOWN: case 'j': if (y < (int) game_area.bot() - 2) player.setPosY(y + 1); break; case KEY_LEFT: case 'h': if (x > (int) game_area.left() + 1) player.setPosX(x - 1); break; case KEY_RIGHT: case 'l': if (x < (int) game_area.right() - 2) player.setPosX(x + 1); break; case KEY_ENTER: /* numpad enter */ case '\n': /* keyboard return */ break; } // Move to updates position (Player & Enemy) wmove(wgame, player.getPos().y, player.getPos().x); waddch(wgame, player.getDispChar()); wmove(wgame, enemy.getPos().y, enemy.getPos().x); waddch(wgame, enemy.getDispChar()); infoPanel_game->push('{' + std::to_string(x) + ',' + std::to_string(y) + '}' + " - right & left: {" + std::to_string(game_area.right()) + ',' + std::to_string(game_area.left()) + '}' + " top & bot: {" + std::to_string(game_area.top()) + ',' + std::to_string(game_area.bot()) + '}' ); wrefresh(wgame); } delwin(wgame); } <|endoftext|>
<commit_before>/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * fermin at tid dot es * * Author: developer */ #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "ConnectionInfo.h" #include "clientSocketHttp.h" #include "serviceRoutines/versionTreat.h" #include <iostream> #include <sys/types.h> // system types ... #include <sys/socket.h> // socket, bind, listen #include <sys/un.h> // sockaddr_un #include <netinet/in.h> // struct sockaddr_in #include <netdb.h> // gethostbyname #include <arpa/inet.h> // inet_ntoa #include <netinet/tcp.h> // TCP_NODELAY #include <string> #include <unistd.h> // close() /* **************************************************************************** * * socketHttpConnect - */ int socketHttpConnect(std::string host, unsigned short port) { int fd; struct hostent* hp; struct sockaddr_in peer; if ((hp = gethostbyname(host.c_str())) == NULL) LM_RE(-1, ("gethostbyname('%s'): %s", host.c_str(), strerror(errno))); if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) LM_RE(-1, ("socket: %s", strerror(errno))); memset((char*) &peer, 0, sizeof(peer)); peer.sin_family = AF_INET; peer.sin_addr.s_addr = ((struct in_addr*) (hp->h_addr))->s_addr; peer.sin_port = htons(port); if (connect(fd, (struct sockaddr*) &peer, sizeof(peer)) == -1) { close(fd); LM_E(("connect(%s, %d): %s", host.c_str(), port, strerror(errno))); return -1; } return fd; } /* **************************************************************************** * * sendHttpSocket - * * The waitForResponse arguments specifies if the method has to wait for response * before return. If this argument is false, the return string is "" * * FIXME: I don't like too much "reusing" natural output to return "error" in the * case of error. I think it would be smarter to use "std::string* error" in the * arguments or (even better) and exception. To be solved in the future in a hardening * period. * */ #define MSG_SIZE (8 * 1024 * 1024) char msg[MSG_SIZE]; std::string sendHttpSocket ( std::string ip, unsigned short port, std::string verb, std::string resource, std::string content_type, std::string content, bool waitForResponse ) { char buffer[TAM_BUF]; char response[TAM_BUF];; std::string result; // Buffers clear memset(buffer, 0, TAM_BUF); memset(response, 0, TAM_BUF); memset(msg, 0, MSG_SIZE); if (port == 0) LM_RE("error", ("port is ZERO")); if (ip.empty()) LM_RE("error", ("ip is empty")); if (verb.empty()) LM_RE("error", ("verb is empty")); if (resource.empty()) LM_RE("error", ("resource is empty")); snprintf(msg, sizeof(msg), "%s %s HTTP/1.1\n" "User-Agent: orion/%s\n" "Host: %s:%d\n" "Accept: application/xml, application/json\n", verb.c_str(), resource.c_str(), versionGet(), ip.c_str(), (int) port); if ((!content_type.empty()) && (!content.empty())) { char rest[512]; sprintf(rest, "Content-Type: %s\n" "Content-Length: %zu\n", content_type.c_str(), content.length() + 1); strncat(msg, rest, sizeof(msg) - strlen(msg)); strncat(msg, "\n", sizeof(msg) - strlen(msg)); strncat(msg, content.c_str(), sizeof(msg) - strlen(msg)); } strncat(msg, "\n", sizeof(msg) - strlen(msg)); int fd = socketHttpConnect(ip, port); // Connecting to HTTP server if (fd == -1) LM_RE("error", ("Unable to connect to HTTP server at %s:%d", ip.c_str(), port)); int sz = strlen(msg); int nb; if (sz >= MSG_SIZE) LM_RE("Msg too large", ("A message got too large (%d bytes - max size is %d). The contextBroker must be recompiled!!!", sz, sizeof(msg))); LM_T(LmtClientOutputPayload, ("Sending to HTTP server:\n%s", msg)); nb = send(fd, msg, sz, 0); if (nb == -1) LM_RE("error", ("error sending to HTTP server: %s", strerror(errno))); else if (nb != sz) LM_E(("error sending to HTTP server. Sent %d bytes of %d", nb, sz)); if (waitForResponse) { nb = recv(fd,&buffer,TAM_BUF-1,0); if (nb == -1) LM_RE("error", ("error recv from HTTP server: %s", strerror(errno))); else if ( nb >= TAM_BUF) LM_RE("error", ("recv from HTTP server too long")); else { memcpy(response, buffer, nb); LM_T(LmtClientInputPayload, ("Received from HTTP server:\n%s", response)); } if (strlen(response) > 0) result = response; } else result = ""; close(fd); return result; } <commit_msg>FIX 'msg' grom global to local variable to avoid race conditions in notification sending threads<commit_after>/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * fermin at tid dot es * * Author: developer */ #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "ConnectionInfo.h" #include "clientSocketHttp.h" #include "serviceRoutines/versionTreat.h" #include <iostream> #include <sys/types.h> // system types ... #include <sys/socket.h> // socket, bind, listen #include <sys/un.h> // sockaddr_un #include <netinet/in.h> // struct sockaddr_in #include <netdb.h> // gethostbyname #include <arpa/inet.h> // inet_ntoa #include <netinet/tcp.h> // TCP_NODELAY #include <string> #include <unistd.h> // close() /* **************************************************************************** * * socketHttpConnect - */ int socketHttpConnect(std::string host, unsigned short port) { int fd; struct hostent* hp; struct sockaddr_in peer; if ((hp = gethostbyname(host.c_str())) == NULL) LM_RE(-1, ("gethostbyname('%s'): %s", host.c_str(), strerror(errno))); if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) LM_RE(-1, ("socket: %s", strerror(errno))); memset((char*) &peer, 0, sizeof(peer)); peer.sin_family = AF_INET; peer.sin_addr.s_addr = ((struct in_addr*) (hp->h_addr))->s_addr; peer.sin_port = htons(port); if (connect(fd, (struct sockaddr*) &peer, sizeof(peer)) == -1) { close(fd); LM_E(("connect(%s, %d): %s", host.c_str(), port, strerror(errno))); return -1; } return fd; } /* **************************************************************************** * * sendHttpSocket - * * The waitForResponse arguments specifies if the method has to wait for response * before return. If this argument is false, the return string is "" * * FIXME: I don't like too much "reusing" natural output to return "error" in the * case of error. I think it would be smarter to use "std::string* error" in the * arguments or (even better) and exception. To be solved in the future in a hardening * period. * */ #define MSG_SIZE (8 * 1024 * 1024) std::string sendHttpSocket ( std::string ip, unsigned short port, std::string verb, std::string resource, std::string content_type, std::string content, bool waitForResponse ) { char msg[MSG_SIZE]; char buffer[TAM_BUF]; char response[TAM_BUF];; std::string result; // Buffers clear memset(buffer, 0, TAM_BUF); memset(response, 0, TAM_BUF); memset(msg, 0, MSG_SIZE); if (port == 0) LM_RE("error", ("port is ZERO")); if (ip.empty()) LM_RE("error", ("ip is empty")); if (verb.empty()) LM_RE("error", ("verb is empty")); if (resource.empty()) LM_RE("error", ("resource is empty")); snprintf(msg, sizeof(msg), "%s %s HTTP/1.1\n" "User-Agent: orion/%s\n" "Host: %s:%d\n" "Accept: application/xml, application/json\n", verb.c_str(), resource.c_str(), versionGet(), ip.c_str(), (int) port); if ((!content_type.empty()) && (!content.empty())) { char rest[512]; sprintf(rest, "Content-Type: %s\n" "Content-Length: %zu\n", content_type.c_str(), content.length() + 1); strncat(msg, rest, sizeof(msg) - strlen(msg)); strncat(msg, "\n", sizeof(msg) - strlen(msg)); strncat(msg, content.c_str(), sizeof(msg) - strlen(msg)); } strncat(msg, "\n", sizeof(msg) - strlen(msg)); int fd = socketHttpConnect(ip, port); // Connecting to HTTP server if (fd == -1) LM_RE("error", ("Unable to connect to HTTP server at %s:%d", ip.c_str(), port)); int sz = strlen(msg); int nb; if (sz >= MSG_SIZE) LM_RE("Msg too large", ("A message got too large (%d bytes - max size is %d). The contextBroker must be recompiled!!!", sz, sizeof(msg))); LM_T(LmtClientOutputPayload, ("Sending to HTTP server:\n%s", msg)); nb = send(fd, msg, sz, 0); if (nb == -1) LM_RE("error", ("error sending to HTTP server: %s", strerror(errno))); else if (nb != sz) LM_E(("error sending to HTTP server. Sent %d bytes of %d", nb, sz)); if (waitForResponse) { nb = recv(fd,&buffer,TAM_BUF-1,0); if (nb == -1) LM_RE("error", ("error recv from HTTP server: %s", strerror(errno))); else if ( nb >= TAM_BUF) LM_RE("error", ("recv from HTTP server too long")); else { memcpy(response, buffer, nb); LM_T(LmtClientInputPayload, ("Received from HTTP server:\n%s", response)); } if (strlen(response) > 0) result = response; } else result = ""; close(fd); return result; } <|endoftext|>
<commit_before>// Copyright 2011 Google Inc. 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 "graph.h" #include <assert.h> #include <stdio.h> #include "build_log.h" #include "depfile_parser.h" #include "disk_interface.h" #include "explain.h" #include "manifest_parser.h" #include "metrics.h" #include "state.h" #include "util.h" bool Node::Stat(DiskInterface* disk_interface) { METRIC_RECORD("node stat"); mtime_ = disk_interface->Stat(path_); return mtime_ > 0; } void Rule::AddBinding(const string& key, const EvalString& val) { bindings_[key] = val; } const EvalString* Rule::GetBinding(const string& key) const { map<string, EvalString>::const_iterator i = bindings_.find(key); if (i == bindings_.end()) return NULL; return &i->second; } // static bool Rule::IsReservedBinding(const string& var) { return var == "command" || var == "depfile" || var == "description" || var == "generator" || var == "pool" || var == "restat" || var == "rspfile" || var == "rspfile_content"; } bool DependencyScan::RecomputeDirty(Edge* edge, string* err) { bool dirty = false; edge->outputs_ready_ = true; string depfile = edge->GetBinding("depfile"); if (!depfile.empty()) { if (!LoadDepFile(edge, depfile, err)) { if (!err->empty()) return false; EXPLAIN("Edge targets are dirty because depfile '%s' is missing", depfile.c_str()); dirty = true; } } // Visit all inputs; we're dirty if any of the inputs are dirty. Node* most_recent_input = NULL; for (vector<Node*>::iterator i = edge->inputs_.begin(); i != edge->inputs_.end(); ++i) { if ((*i)->StatIfNecessary(disk_interface_)) { if (Edge* in_edge = (*i)->in_edge()) { if (!RecomputeDirty(in_edge, err)) return false; } else { // This input has no in-edge; it is dirty if it is missing. if (!(*i)->exists()) EXPLAIN("%s has no in-edge and is missing", (*i)->path().c_str()); (*i)->set_dirty(!(*i)->exists()); } } // If an input is not ready, neither are our outputs. if (Edge* in_edge = (*i)->in_edge()) { if (!in_edge->outputs_ready_) edge->outputs_ready_ = false; } if (!edge->is_order_only(i - edge->inputs_.begin())) { // If a regular input is dirty (or missing), we're dirty. // Otherwise consider mtime. if ((*i)->dirty()) { EXPLAIN("%s is dirty", (*i)->path().c_str()); dirty = true; } else { if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) { most_recent_input = *i; } } } } // We may also be dirty due to output state: missing outputs, out of // date outputs, etc. Visit all outputs and determine whether they're dirty. if (!dirty) { string command = edge->EvaluateCommand(true); for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (RecomputeOutputDirty(edge, most_recent_input, command, *i)) { dirty = true; break; } } } // Finally, visit each output to mark off that we've visited it, and update // their dirty state if necessary. for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (dirty) (*i)->MarkDirty(); } // If an edge is dirty, its outputs are normally not ready. (It's // possible to be clean but still not be ready in the presence of // order-only inputs.) // But phony edges with no inputs have nothing to do, so are always // ready. if (dirty && !(edge->is_phony() && edge->inputs_.empty())) edge->outputs_ready_ = false; return true; } bool DependencyScan::RecomputeOutputDirty(Edge* edge, Node* most_recent_input, const string& command, Node* output) { if (edge->is_phony()) { // Phony edges don't write any output. Outputs are only dirty if // there are no inputs and we're missing the output. return edge->inputs_.empty() && !output->exists(); } BuildLog::LogEntry* entry = 0; // Dirty if we're missing the output. if (!output->exists()) { EXPLAIN("output %s doesn't exist", output->path().c_str()); return true; } // Dirty if the output is older than the input. if (most_recent_input && output->mtime() < most_recent_input->mtime()) { // If this is a restat rule, we may have cleaned the output with a restat // rule in a previous run and stored the most recent input mtime in the // build log. Use that mtime instead, so that the file will only be // considered dirty if an input was modified since the previous run. TimeStamp most_recent_stamp = most_recent_input->mtime(); if (edge->GetBindingBool("restat") && build_log() && (entry = build_log()->LookupByOutput(output->path()))) { if (entry->restat_mtime < most_recent_stamp) { EXPLAIN("restat of output %s older than most recent input %s " "(%d vs %d)", output->path().c_str(), most_recent_input->path().c_str(), entry->restat_mtime, most_recent_stamp); return true; } } else { EXPLAIN("output %s older than most recent input %s (%d vs %d)", output->path().c_str(), most_recent_input->path().c_str(), output->mtime(), most_recent_stamp); return true; } } // May also be dirty due to the command changing since the last build. // But if this is a generator rule, the command changing does not make us // dirty. if (!edge->GetBindingBool("generator") && build_log()) { if (entry || (entry = build_log()->LookupByOutput(output->path()))) { if (BuildLog::LogEntry::HashCommand(command) != entry->command_hash) { EXPLAIN("command line changed for %s", output->path().c_str()); return true; } } if (!entry) { EXPLAIN("command line not found in log for %s", output->path().c_str()); return true; } } return false; } bool Edge::AllInputsReady() const { for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end(); ++i) { if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready()) return false; } return true; } /// An Env for an Edge, providing $in and $out. struct EdgeEnv : public Env { explicit EdgeEnv(Edge* edge) : edge_(edge) {} virtual string LookupVariable(const string& var); /// Given a span of Nodes, construct a list of paths suitable for a command /// line. string MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep); Edge* edge_; }; string EdgeEnv::LookupVariable(const string& var) { if (var == "in" || var == "in_newline") { int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ - edge_->order_only_deps_; return MakePathList(edge_->inputs_.begin(), edge_->inputs_.begin() + explicit_deps_count, var == "in" ? ' ' : '\n'); } else if (var == "out") { return MakePathList(edge_->outputs_.begin(), edge_->outputs_.end(), ' '); } // See notes on BindingEnv::LookupWithFallback. const EvalString* eval = edge_->rule_->GetBinding(var); return edge_->env_->LookupWithFallback(var, eval, this); } string EdgeEnv::MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep) { string result; for (vector<Node*>::iterator i = begin; i != end; ++i) { if (!result.empty()) result.push_back(sep); const string& path = (*i)->path(); if (path.find(" ") != string::npos) { result.append("\""); result.append(path); result.append("\""); } else { result.append(path); } } return result; } string Edge::EvaluateCommand(bool incl_rsp_file) { string command = GetBinding("command"); if (incl_rsp_file) { string rspfile_content = GetBinding("rspfile_content"); if (!rspfile_content.empty()) command += ";rspfile=" + rspfile_content; } return command; } string Edge::GetBinding(const string& key) { EdgeEnv env(this); return env.LookupVariable(key); } bool Edge::GetBindingBool(const string& key) { return !GetBinding(key).empty(); } bool DependencyScan::LoadDepFile(Edge* edge, const string& path, string* err) { METRIC_RECORD("depfile load"); string content = disk_interface_->ReadFile(path, err); if (!err->empty()) { *err = "loading '" + path + "': " + *err; return false; } // On a missing depfile: return false and empty *err. if (content.empty()) return false; DepfileParser depfile; string depfile_err; if (!depfile.Parse(&content, &depfile_err)) { *err = path + ": " + depfile_err; return false; } // Check that this depfile matches the edge's output. Node* first_output = edge->outputs_[0]; StringPiece opath = StringPiece(first_output->path()); if (opath != depfile.out_) { *err = "expected depfile '" + path + "' to mention '" + first_output->path() + "', got '" + depfile.out_.AsString() + "'"; return false; } // Preallocate space in edge->inputs_ to be filled in below. edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_, depfile.ins_.size(), 0); edge->implicit_deps_ += depfile.ins_.size(); vector<Node*>::iterator implicit_dep = edge->inputs_.end() - edge->order_only_deps_ - depfile.ins_.size(); // Add all its in-edges. for (vector<StringPiece>::iterator i = depfile.ins_.begin(); i != depfile.ins_.end(); ++i, ++implicit_dep) { if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err)) return false; Node* node = state_->GetNode(*i); *implicit_dep = node; node->AddOutEdge(edge); // If we don't have a edge that generates this input already, // create one; this makes us not abort if the input is missing, // but instead will rebuild in that circumstance. if (!node->in_edge()) { Edge* phony_edge = state_->AddEdge(&State::kPhonyRule); node->set_in_edge(phony_edge); phony_edge->outputs_.push_back(node); // RecomputeDirty might not be called for phony_edge if a previous call // to RecomputeDirty had caused the file to be stat'ed. Because previous // invocations of RecomputeDirty would have seen this node without an // input edge (and therefore ready), we have to set outputs_ready_ to true // to avoid a potential stuck build. If we do call RecomputeDirty for // this node, it will simply set outputs_ready_ to the correct value. phony_edge->outputs_ready_ = true; } } return true; } void Edge::Dump(const char* prefix) const { printf("%s[ ", prefix); for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } printf("--%s-> ", rule_->name().c_str()); for (vector<Node*>::const_iterator i = outputs_.begin(); i != outputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } if (pool_) { if (!pool_->name().empty()) { printf("(in pool '%s')", pool_->name().c_str()); } } else { printf("(null pool?)"); } printf("] 0x%p\n", this); } bool Edge::is_phony() const { return rule_ == &State::kPhonyRule; } void Node::Dump(const char* prefix) const { printf("%s <%s 0x%p> mtime: %d%s, (:%s), ", prefix, path().c_str(), this, mtime(), mtime() ? "" : " (:missing)", dirty() ? " dirty" : " clean"); if (in_edge()) { in_edge()->Dump("in-edge: "); } else { printf("no in-edge\n"); } printf(" out edges:\n"); for (vector<Edge*>::const_iterator e = out_edges().begin(); e != out_edges().end() && *e != NULL; ++e) { (*e)->Dump(" +- "); } } <commit_msg>refactor some of the output mtime-handling code<commit_after>// Copyright 2011 Google Inc. 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 "graph.h" #include <assert.h> #include <stdio.h> #include "build_log.h" #include "depfile_parser.h" #include "disk_interface.h" #include "explain.h" #include "manifest_parser.h" #include "metrics.h" #include "state.h" #include "util.h" bool Node::Stat(DiskInterface* disk_interface) { METRIC_RECORD("node stat"); mtime_ = disk_interface->Stat(path_); return mtime_ > 0; } void Rule::AddBinding(const string& key, const EvalString& val) { bindings_[key] = val; } const EvalString* Rule::GetBinding(const string& key) const { map<string, EvalString>::const_iterator i = bindings_.find(key); if (i == bindings_.end()) return NULL; return &i->second; } // static bool Rule::IsReservedBinding(const string& var) { return var == "command" || var == "depfile" || var == "description" || var == "generator" || var == "pool" || var == "restat" || var == "rspfile" || var == "rspfile_content"; } bool DependencyScan::RecomputeDirty(Edge* edge, string* err) { bool dirty = false; edge->outputs_ready_ = true; string depfile = edge->GetBinding("depfile"); if (!depfile.empty()) { if (!LoadDepFile(edge, depfile, err)) { if (!err->empty()) return false; EXPLAIN("Edge targets are dirty because depfile '%s' is missing", depfile.c_str()); dirty = true; } } // Visit all inputs; we're dirty if any of the inputs are dirty. Node* most_recent_input = NULL; for (vector<Node*>::iterator i = edge->inputs_.begin(); i != edge->inputs_.end(); ++i) { if ((*i)->StatIfNecessary(disk_interface_)) { if (Edge* in_edge = (*i)->in_edge()) { if (!RecomputeDirty(in_edge, err)) return false; } else { // This input has no in-edge; it is dirty if it is missing. if (!(*i)->exists()) EXPLAIN("%s has no in-edge and is missing", (*i)->path().c_str()); (*i)->set_dirty(!(*i)->exists()); } } // If an input is not ready, neither are our outputs. if (Edge* in_edge = (*i)->in_edge()) { if (!in_edge->outputs_ready_) edge->outputs_ready_ = false; } if (!edge->is_order_only(i - edge->inputs_.begin())) { // If a regular input is dirty (or missing), we're dirty. // Otherwise consider mtime. if ((*i)->dirty()) { EXPLAIN("%s is dirty", (*i)->path().c_str()); dirty = true; } else { if (!most_recent_input || (*i)->mtime() > most_recent_input->mtime()) { most_recent_input = *i; } } } } // We may also be dirty due to output state: missing outputs, out of // date outputs, etc. Visit all outputs and determine whether they're dirty. if (!dirty) { string command = edge->EvaluateCommand(true); for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (RecomputeOutputDirty(edge, most_recent_input, command, *i)) { dirty = true; break; } } } // Finally, visit each output to mark off that we've visited it, and update // their dirty state if necessary. for (vector<Node*>::iterator i = edge->outputs_.begin(); i != edge->outputs_.end(); ++i) { (*i)->StatIfNecessary(disk_interface_); if (dirty) (*i)->MarkDirty(); } // If an edge is dirty, its outputs are normally not ready. (It's // possible to be clean but still not be ready in the presence of // order-only inputs.) // But phony edges with no inputs have nothing to do, so are always // ready. if (dirty && !(edge->is_phony() && edge->inputs_.empty())) edge->outputs_ready_ = false; return true; } bool DependencyScan::RecomputeOutputDirty(Edge* edge, Node* most_recent_input, const string& command, Node* output) { if (edge->is_phony()) { // Phony edges don't write any output. Outputs are only dirty if // there are no inputs and we're missing the output. return edge->inputs_.empty() && !output->exists(); } BuildLog::LogEntry* entry = 0; // Dirty if we're missing the output. if (!output->exists()) { EXPLAIN("output %s doesn't exist", output->path().c_str()); return true; } // Dirty if the output is older than the input. if (most_recent_input && output->mtime() < most_recent_input->mtime()) { TimeStamp output_mtime = output->mtime(); // If this is a restat rule, we may have cleaned the output with a restat // rule in a previous run and stored the most recent input mtime in the // build log. Use that mtime instead, so that the file will only be // considered dirty if an input was modified since the previous run. bool used_restat = false; if (edge->GetBindingBool("restat") && build_log() && (entry = build_log()->LookupByOutput(output->path()))) { output_mtime = entry->restat_mtime; used_restat = true; } if (output_mtime < most_recent_input->mtime()) { EXPLAIN("%soutput %s older than most recent input %s " "(%d vs %d)", used_restat ? "restat of " : "", output->path().c_str(), most_recent_input->path().c_str(), output_mtime, most_recent_input->mtime()); return true; } } // May also be dirty due to the command changing since the last build. // But if this is a generator rule, the command changing does not make us // dirty. if (!edge->GetBindingBool("generator") && build_log()) { if (entry || (entry = build_log()->LookupByOutput(output->path()))) { if (BuildLog::LogEntry::HashCommand(command) != entry->command_hash) { EXPLAIN("command line changed for %s", output->path().c_str()); return true; } } if (!entry) { EXPLAIN("command line not found in log for %s", output->path().c_str()); return true; } } return false; } bool Edge::AllInputsReady() const { for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end(); ++i) { if ((*i)->in_edge() && !(*i)->in_edge()->outputs_ready()) return false; } return true; } /// An Env for an Edge, providing $in and $out. struct EdgeEnv : public Env { explicit EdgeEnv(Edge* edge) : edge_(edge) {} virtual string LookupVariable(const string& var); /// Given a span of Nodes, construct a list of paths suitable for a command /// line. string MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep); Edge* edge_; }; string EdgeEnv::LookupVariable(const string& var) { if (var == "in" || var == "in_newline") { int explicit_deps_count = edge_->inputs_.size() - edge_->implicit_deps_ - edge_->order_only_deps_; return MakePathList(edge_->inputs_.begin(), edge_->inputs_.begin() + explicit_deps_count, var == "in" ? ' ' : '\n'); } else if (var == "out") { return MakePathList(edge_->outputs_.begin(), edge_->outputs_.end(), ' '); } // See notes on BindingEnv::LookupWithFallback. const EvalString* eval = edge_->rule_->GetBinding(var); return edge_->env_->LookupWithFallback(var, eval, this); } string EdgeEnv::MakePathList(vector<Node*>::iterator begin, vector<Node*>::iterator end, char sep) { string result; for (vector<Node*>::iterator i = begin; i != end; ++i) { if (!result.empty()) result.push_back(sep); const string& path = (*i)->path(); if (path.find(" ") != string::npos) { result.append("\""); result.append(path); result.append("\""); } else { result.append(path); } } return result; } string Edge::EvaluateCommand(bool incl_rsp_file) { string command = GetBinding("command"); if (incl_rsp_file) { string rspfile_content = GetBinding("rspfile_content"); if (!rspfile_content.empty()) command += ";rspfile=" + rspfile_content; } return command; } string Edge::GetBinding(const string& key) { EdgeEnv env(this); return env.LookupVariable(key); } bool Edge::GetBindingBool(const string& key) { return !GetBinding(key).empty(); } bool DependencyScan::LoadDepFile(Edge* edge, const string& path, string* err) { METRIC_RECORD("depfile load"); string content = disk_interface_->ReadFile(path, err); if (!err->empty()) { *err = "loading '" + path + "': " + *err; return false; } // On a missing depfile: return false and empty *err. if (content.empty()) return false; DepfileParser depfile; string depfile_err; if (!depfile.Parse(&content, &depfile_err)) { *err = path + ": " + depfile_err; return false; } // Check that this depfile matches the edge's output. Node* first_output = edge->outputs_[0]; StringPiece opath = StringPiece(first_output->path()); if (opath != depfile.out_) { *err = "expected depfile '" + path + "' to mention '" + first_output->path() + "', got '" + depfile.out_.AsString() + "'"; return false; } // Preallocate space in edge->inputs_ to be filled in below. edge->inputs_.insert(edge->inputs_.end() - edge->order_only_deps_, depfile.ins_.size(), 0); edge->implicit_deps_ += depfile.ins_.size(); vector<Node*>::iterator implicit_dep = edge->inputs_.end() - edge->order_only_deps_ - depfile.ins_.size(); // Add all its in-edges. for (vector<StringPiece>::iterator i = depfile.ins_.begin(); i != depfile.ins_.end(); ++i, ++implicit_dep) { if (!CanonicalizePath(const_cast<char*>(i->str_), &i->len_, err)) return false; Node* node = state_->GetNode(*i); *implicit_dep = node; node->AddOutEdge(edge); // If we don't have a edge that generates this input already, // create one; this makes us not abort if the input is missing, // but instead will rebuild in that circumstance. if (!node->in_edge()) { Edge* phony_edge = state_->AddEdge(&State::kPhonyRule); node->set_in_edge(phony_edge); phony_edge->outputs_.push_back(node); // RecomputeDirty might not be called for phony_edge if a previous call // to RecomputeDirty had caused the file to be stat'ed. Because previous // invocations of RecomputeDirty would have seen this node without an // input edge (and therefore ready), we have to set outputs_ready_ to true // to avoid a potential stuck build. If we do call RecomputeDirty for // this node, it will simply set outputs_ready_ to the correct value. phony_edge->outputs_ready_ = true; } } return true; } void Edge::Dump(const char* prefix) const { printf("%s[ ", prefix); for (vector<Node*>::const_iterator i = inputs_.begin(); i != inputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } printf("--%s-> ", rule_->name().c_str()); for (vector<Node*>::const_iterator i = outputs_.begin(); i != outputs_.end() && *i != NULL; ++i) { printf("%s ", (*i)->path().c_str()); } if (pool_) { if (!pool_->name().empty()) { printf("(in pool '%s')", pool_->name().c_str()); } } else { printf("(null pool?)"); } printf("] 0x%p\n", this); } bool Edge::is_phony() const { return rule_ == &State::kPhonyRule; } void Node::Dump(const char* prefix) const { printf("%s <%s 0x%p> mtime: %d%s, (:%s), ", prefix, path().c_str(), this, mtime(), mtime() ? "" : " (:missing)", dirty() ? " dirty" : " clean"); if (in_edge()) { in_edge()->Dump("in-edge: "); } else { printf("no in-edge\n"); } printf(" out edges:\n"); for (vector<Edge*>::const_iterator e = out_edges().begin(); e != out_edges().end() && *e != NULL; ++e) { (*e)->Dump(" +- "); } } <|endoftext|>
<commit_before>#include "psqlwrapper.h" #include <QDebug> #include <QSqlError> #include <QSqlQuery> #include <QVariant> PsqlWrapper::PsqlWrapper(QSqlDatabase *db) : QObject(NULL) { m_db = db; } SqlWrapper::WrapperFeatures PsqlWrapper::features() { return Schemas; } SqlWrapper* PsqlWrapper::newInstance(QSqlDatabase *db) { return new PsqlWrapper(db); } /** * Récupération d'un schéma */ SqlSchema PsqlWrapper::schema(QString sch) { SqlSchema schema; if (!m_db) { return schema; } QString sql; sql += "SELECT schemaname, typname, 'T', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_tables "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = tablename "; sql += "AND typname not like 'pg_%' "; sql += "AND schemaname = '" + sch + "' "; sql += "UNION "; sql += "SELECT schemaname, typname, 'V', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_views "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = viewname "; sql += "AND typname not like 'pg_%' "; sql += "AND schemaname = '" + sch + "' "; sql += "ORDER BY schemaname, typname, attnum "; QSqlQuery query(*m_db); if (!query.exec(sql)) { qDebug() << query.lastError().text(); return schema; } bool ruptureTable = false; SqlTable t; while (query.next()) { schema.name = query.value(0).toString(); schema.defaultSchema = schema.name == "public"; // Tables ruptureTable = t.name != query.value(1).toString(); if (ruptureTable) { if (t.name.length() > 0) { schema.tables << t; } t = SqlTable(); t.name = query.value(1).toString(); if (query.value(2).toString() == "T") { t.type = Table; } else if (query.value(2).toString() == "V") { t.type = ViewTable; } } // Colonnes SqlColumn c; c.name = query.value(3).toString(); c.permitsNull = query.value(4).toBool(); c.primaryKey = false; t.columns << c; } if (t.name.length() > 0) { schema.tables << t; } return schema; } /** * Récupération de la liste des tables */ QList<SqlSchema> PsqlWrapper::schemas() { QList<SqlSchema> schemas; if (!m_db) { return schemas; } QString sql; sql += "SELECT schemaname, typname, 'T', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_tables "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = tablename "; sql += "AND typname not like 'pg_%' "; sql += "UNION "; sql += "SELECT schemaname, typname, 'V', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_views "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = viewname "; sql += "AND typname not like 'pg_%' "; sql += "ORDER BY schemaname, typname, attnum "; QSqlQuery query(*m_db); if (!query.exec(sql)) { qDebug() << query.lastError().text(); return schemas; } bool first = true; bool ruptureSchema = false; bool ruptureTable = false; SqlSchema s; SqlTable t; while (query.next()) { // Schémas ruptureSchema = s.name != query.value(0).toString(); if (ruptureSchema && s.name != "") { s.tables << t; schemas << s; } if (ruptureSchema) { s = SqlSchema(); s.name = query.value(0).toString(); s.defaultSchema = s.name == "public"; } // Tables ruptureTable = t.name != query.value(1).toString(); if (first || (ruptureTable && !ruptureSchema && t.name != "")) { first = false; s.tables << t; } if (ruptureTable) { t = SqlTable(); t.name = query.value(1).toString(); if (query.value(2).toString() == "T") { t.type = Table; } else if (query.value(2).toString() == "V") { t.type = ViewTable; } } // Colonnes SqlColumn c; c.name = query.value(3).toString(); c.permitsNull = query.value(4).toBool(); c.primaryKey = false; t.columns << c; } if (s.name.length() > 0) { if (t.name.length() > 0) { s.tables << t; } schemas << s; } return schemas; } QList<SqlTable> PsqlWrapper::tables() { QList<SqlTable> tables; if (m_db) { return tables; } QString sql = "select "; return tables; } Q_EXPORT_PLUGIN2(dbm_psql_wrapper, PsqlWrapper) <commit_msg>PostgreSQL supporte ODBC<commit_after>#include "psqlwrapper.h" #include <QDebug> #include <QSqlError> #include <QSqlQuery> #include <QVariant> PsqlWrapper::PsqlWrapper(QSqlDatabase *db) : QObject(NULL) { m_db = db; } SqlWrapper::WrapperFeatures PsqlWrapper::features() { return ODBC | Schemas; } SqlWrapper* PsqlWrapper::newInstance(QSqlDatabase *db) { return new PsqlWrapper(db); } /** * Récupération d'un schéma */ SqlSchema PsqlWrapper::schema(QString sch) { SqlSchema schema; if (!m_db) { return schema; } QString sql; sql += "SELECT schemaname, typname, 'T', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_tables "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = tablename "; sql += "AND typname not like 'pg_%' "; sql += "AND schemaname = '" + sch + "' "; sql += "UNION "; sql += "SELECT schemaname, typname, 'V', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_views "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = viewname "; sql += "AND typname not like 'pg_%' "; sql += "AND schemaname = '" + sch + "' "; sql += "ORDER BY schemaname, typname, attnum "; QSqlQuery query(*m_db); if (!query.exec(sql)) { qDebug() << query.lastError().text(); return schema; } bool ruptureTable = false; SqlTable t; while (query.next()) { schema.name = query.value(0).toString(); schema.defaultSchema = schema.name == "public"; // Tables ruptureTable = t.name != query.value(1).toString(); if (ruptureTable) { if (t.name.length() > 0) { schema.tables << t; } t = SqlTable(); t.name = query.value(1).toString(); if (query.value(2).toString() == "T") { t.type = Table; } else if (query.value(2).toString() == "V") { t.type = ViewTable; } } // Colonnes SqlColumn c; c.name = query.value(3).toString(); c.permitsNull = query.value(4).toBool(); c.primaryKey = false; t.columns << c; } if (t.name.length() > 0) { schema.tables << t; } return schema; } /** * Récupération de la liste des tables */ QList<SqlSchema> PsqlWrapper::schemas() { QList<SqlSchema> schemas; if (!m_db) { return schemas; } QString sql; sql += "SELECT schemaname, typname, 'T', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_tables "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = tablename "; sql += "AND typname not like 'pg_%' "; sql += "UNION "; sql += "SELECT schemaname, typname, 'V', attname, attnotnull, attlen, attnum "; sql += "FROM pg_attribute, pg_type, pg_views "; sql += "WHERE attrelid = typrelid "; sql += "AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', "; sql += "'tableoid', 'xmin', 'xmax') "; sql += "AND typname = viewname "; sql += "AND typname not like 'pg_%' "; sql += "ORDER BY schemaname, typname, attnum "; QSqlQuery query(*m_db); if (!query.exec(sql)) { qDebug() << query.lastError().text(); return schemas; } bool first = true; bool ruptureSchema = false; bool ruptureTable = false; SqlSchema s; SqlTable t; while (query.next()) { // Schémas ruptureSchema = s.name != query.value(0).toString(); if (ruptureSchema && s.name != "") { s.tables << t; schemas << s; } if (ruptureSchema) { s = SqlSchema(); s.name = query.value(0).toString(); s.defaultSchema = s.name == "public"; } // Tables ruptureTable = t.name != query.value(1).toString(); if (first || (ruptureTable && !ruptureSchema && t.name != "")) { first = false; s.tables << t; } if (ruptureTable) { t = SqlTable(); t.name = query.value(1).toString(); if (query.value(2).toString() == "T") { t.type = Table; } else if (query.value(2).toString() == "V") { t.type = ViewTable; } } // Colonnes SqlColumn c; c.name = query.value(3).toString(); c.permitsNull = query.value(4).toBool(); c.primaryKey = false; t.columns << c; } if (s.name.length() > 0) { if (t.name.length() > 0) { s.tables << t; } schemas << s; } return schemas; } QList<SqlTable> PsqlWrapper::tables() { QList<SqlTable> tables; if (m_db) { return tables; } QString sql = "select "; return tables; } Q_EXPORT_PLUGIN2(dbm_psql_wrapper, PsqlWrapper) <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #include "flint/tr.h" #include "cli.pb.h" #include "system.h" #define BOOST_TEST_MODULE test_translate #include "test.h" struct F : public test::TemporaryWorkingDirectory { std::unique_ptr<cli::RunOption> GenerateOption(const char *model_filename, const char *output_filename) { std::unique_ptr<cli::RunOption> option(new cli::RunOption); option->set_model_filename(model_filename); option->set_output_filename(output_filename); return option; } std::unique_ptr<char[]> input_; }; BOOST_FIXTURE_TEST_SUITE(test_translate, F) #define TRANSLATE_OK_CASE(name, filename) BOOST_AUTO_TEST_CASE(name) { \ PushWorkingDirectory(#name); \ std::unique_ptr<cli::RunOption> option(GenerateOption(TEST_MODELS(filename), filename ".c")); \ test::StderrCapture sc; \ BOOST_CHECK(tr::Translate(*option)); \ BOOST_CHECK_EQUAL(RunSystem("gcc -std=c99 -Wall -W " filename ".c -lm"), EXIT_SUCCESS); \ BOOST_CHECK(sc.Get().empty()); \ PopWorkingDirectory(); \ } TRANSLATE_OK_CASE(BIOMD0000000114, "BIOMD0000000114.xml") TRANSLATE_OK_CASE(BIOMD0000000152, "BIOMD0000000152.xml") TRANSLATE_OK_CASE(fhn, "fhn.phml") TRANSLATE_OK_CASE(fsk, "fsk.phml") TRANSLATE_OK_CASE(hepatocyte_external, "hepatocyte_external.isml") TRANSLATE_OK_CASE(hepatocyte_internal, "hepatocyte_internal.isml") TRANSLATE_OK_CASE(lockwood_ewy_hermann_holford_2006, "lockwood_ewy_hermann_holford_2006.cellml") TRANSLATE_OK_CASE(lorenz, "lorenz.phml") TRANSLATE_OK_CASE(LR1_ring_reentry_initiate, "LR1-ring_reentry_initiate.isml") TRANSLATE_OK_CASE(LR_pulse_189_164, "LR-pulse-189-164.isml") TRANSLATE_OK_CASE(luo_rudy_1991, "luo_rudy_1991.isml") TRANSLATE_OK_CASE(reduction, "reduction.phml") TRANSLATE_OK_CASE(ringed_Beeler_Reuter_1977_model_with_static_instance, "ringed_Beeler_Reuter_1977_model_with_static_instance.isml") TRANSLATE_OK_CASE(ringed_Luo_Rudy_1991_model_with_instance, "ringed_Luo_Rudy_1991_model_with_instance.isml") TRANSLATE_OK_CASE(Rybak_2006_with_static_instance_and_multiple_input, "Rybak_2006_with_static_instance_and_multiple_input.isml") TRANSLATE_OK_CASE(yang_tong_mccarver_hines_beard_2006, "yang_tong_mccarver_hines_beard_2006.cellml") BOOST_AUTO_TEST_SUITE_END() <commit_msg>Call clang if we use it<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #include "flint/tr.h" #include "cli.pb.h" #include "system.h" #define BOOST_TEST_MODULE test_translate #include "test.h" struct F : public test::TemporaryWorkingDirectory { std::unique_ptr<cli::RunOption> GenerateOption(const char *model_filename, const char *output_filename) { std::unique_ptr<cli::RunOption> option(new cli::RunOption); option->set_model_filename(model_filename); option->set_output_filename(output_filename); return option; } std::unique_ptr<char[]> input_; }; BOOST_FIXTURE_TEST_SUITE(test_translate, F) #ifdef __clang__ #define CC "clang" #else #define CC "gcc" #endif #define TRANSLATE_OK_CASE(name, filename) BOOST_AUTO_TEST_CASE(name) { \ PushWorkingDirectory(#name); \ std::unique_ptr<cli::RunOption> option(GenerateOption(TEST_MODELS(filename), filename ".c")); \ test::StderrCapture sc; \ BOOST_CHECK(tr::Translate(*option)); \ BOOST_CHECK_EQUAL(RunSystem(CC " -std=c99 -Wall -W " filename ".c -lm"), EXIT_SUCCESS); \ BOOST_CHECK(sc.Get().empty()); \ PopWorkingDirectory(); \ } TRANSLATE_OK_CASE(BIOMD0000000114, "BIOMD0000000114.xml") TRANSLATE_OK_CASE(BIOMD0000000152, "BIOMD0000000152.xml") TRANSLATE_OK_CASE(fhn, "fhn.phml") TRANSLATE_OK_CASE(fsk, "fsk.phml") TRANSLATE_OK_CASE(hepatocyte_external, "hepatocyte_external.isml") TRANSLATE_OK_CASE(hepatocyte_internal, "hepatocyte_internal.isml") TRANSLATE_OK_CASE(lockwood_ewy_hermann_holford_2006, "lockwood_ewy_hermann_holford_2006.cellml") TRANSLATE_OK_CASE(lorenz, "lorenz.phml") TRANSLATE_OK_CASE(LR1_ring_reentry_initiate, "LR1-ring_reentry_initiate.isml") TRANSLATE_OK_CASE(LR_pulse_189_164, "LR-pulse-189-164.isml") TRANSLATE_OK_CASE(luo_rudy_1991, "luo_rudy_1991.isml") TRANSLATE_OK_CASE(reduction, "reduction.phml") TRANSLATE_OK_CASE(ringed_Beeler_Reuter_1977_model_with_static_instance, "ringed_Beeler_Reuter_1977_model_with_static_instance.isml") TRANSLATE_OK_CASE(ringed_Luo_Rudy_1991_model_with_instance, "ringed_Luo_Rudy_1991_model_with_instance.isml") TRANSLATE_OK_CASE(Rybak_2006_with_static_instance_and_multiple_input, "Rybak_2006_with_static_instance_and_multiple_input.isml") TRANSLATE_OK_CASE(yang_tong_mccarver_hines_beard_2006, "yang_tong_mccarver_hines_beard_2006.cellml") #undef CC BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>{ // // To see the output of this macro, click begin_html <a href="gif/shapes.gif" >here</a> end_html // gROOT->Reset(); c1 = new TCanvas("c1","Geometry Shapes",200,10,700,500); // Define some volumes brik = new TBRIK("BRIK","BRIK","void",200,150,150); trd1 = new TTRD1("TRD1","TRD1","void",200,50,100,100); trd2 = new TTRD2("TRD2","TRD2","void",200,50,200,50,100); trap = new TTRAP("TRAP","TRAP","void",190,0,0,60,40,90,15,120,80,180,15); para = new TPARA("PARA","PARA","void",100,200,200,15,30,30); gtra = new TGTRA("GTRA","GTRA","void",390,0,0,20,60,40,90,15,120,80,180,15); tube = new TTUBE("TUBE","TUBE","void",150,200,400); tubs = new TTUBS("TUBS","TUBS","void",80,100,100,90,235); cone = new TCONE("CONE","CONE","void",100,50,70,120,150); cons = new TCONS("CONS","CONS","void",50,100,100,200,300,90,270); sphe = new TSPHE("SPHE","SPHE","void",25,340, 45,135, 0,270); sphe1 = new TSPHE("SPHE1","SPHE1","void",0,140, 0,180, 0,360); sphe2 = new TSPHE("SPHE2","SPHE2","void",0,200, 10,120, 45,145); pcon = new TPCON("PCON","PCON","void",180,270,4); pcon->DefineSection(0,-200,50,100); pcon->DefineSection(1,-50,50,80); pcon->DefineSection(2,50,50,80); pcon->DefineSection(3,200,50,100); pgon = new TPGON("PGON","PGON","void",180,270,8,4); pgon->DefineSection(0,-200,50,100); pgon->DefineSection(1,-50,50,80); pgon->DefineSection(2,50,50,80); pgon->DefineSection(3,200,50,100); // Set shapes attributes brik->SetLineColor(1); trd1->SetLineColor(2); trd2->SetLineColor(3); trap->SetLineColor(4); para->SetLineColor(5); gtra->SetLineColor(7); tube->SetLineColor(6); tubs->SetLineColor(7); cone->SetLineColor(2); cons->SetLineColor(3); pcon->SetLineColor(6); pgon->SetLineColor(2); sphe->SetLineColor(kRed); sphe1->SetLineColor(kBlack); sphe2->SetLineColor(kBlue); // Build the geometry hierarchy node1 = new TNode("NODE1","NODE1","BRIK"); node1->cd(); node2 = new TNode("NODE2","NODE2","TRD1",0,0,-1000); node3 = new TNode("NODE3","NODE3","TRD2",0,0,1000); node4 = new TNode("NODE4","NODE4","TRAP",0,-1000,0); node5 = new TNode("NODE5","NODE5","PARA",0,1000,0); node6 = new TNode("NODE6","NODE6","TUBE",-1000,0,0); node7 = new TNode("NODE7","NODE7","TUBS",1000,0,0); node8 = new TNode("NODE8","NODE8","CONE",-300,-300,0); node9 = new TNode("NODE9","NODE9","CONS",300,300,0); node10 = new TNode("NODE10","NODE10","PCON",0,-1000,-1000); node11 = new TNode("NODE11","NODE11","PGON",0,1000,1000); node12 = new TNode("NODE12","NODE12","GTRA",0,-400,700); node13 = new TNode("NODE13","NODE13","SPHE",10,-400,500); node14 = new TNode("NODE14","NODE14","SPHE1",10, 250,300); node15 = new TNode("NODE15","NODE15","SPHE2",10,-100,-200); // Draw this geometry in the current canvas node1->cd(); node1->Draw(); c1->Update(); // // Draw the geometry using the x3d viewver. // Note that this viewver may also be invoked from the "View" menu in // the canvas tool bar c1->x3d(); // // once in x3d viewer, type m to see the menu. // For example typing r will show a solid model of this geometry. } <commit_msg>Add protections in shapes.C in case this script is reexecuted multiple times with different values of shape parameters. The previous list of shapes and nodes must be deleted.<commit_after>{ // // To see the output of this macro, click begin_html <a href="gif/shapes.gif" >here</a> end_html // gROOT->Reset(); c1 = new TCanvas("c1","Geometry Shapes",200,10,700,500); //delete previous geometry objects in case this script is reexecuted if (gGeometry) { gGeometry->GetListOfNodes()->Delete(); gGeometry->GetListOfShapes()->Delete(); } // Define some volumes brik = new TBRIK("BRIK","BRIK","void",200,150,150); trd1 = new TTRD1("TRD1","TRD1","void",200,50,100,100); trd2 = new TTRD2("TRD2","TRD2","void",200,50,200,50,100); trap = new TTRAP("TRAP","TRAP","void",190,0,0,60,40,90,15,120,80,180,15); para = new TPARA("PARA","PARA","void",100,200,200,15,30,30); gtra = new TGTRA("GTRA","GTRA","void",390,0,0,20,60,40,90,15,120,80,180,15); tube = new TTUBE("TUBE","TUBE","void",150,200,400); tubs = new TTUBS("TUBS","TUBS","void",80,100,100,90,235); cone = new TCONE("CONE","CONE","void",100,50,70,120,150); cons = new TCONS("CONS","CONS","void",50,100,100,200,300,90,270); sphe = new TSPHE("SPHE","SPHE","void",25,340, 45,135, 0,270); sphe1 = new TSPHE("SPHE1","SPHE1","void",0,140, 0,180, 0,360); sphe2 = new TSPHE("SPHE2","SPHE2","void",0,200, 10,120, 45,145); pcon = new TPCON("PCON","PCON","void",180,270,4); pcon->DefineSection(0,-200,50,100); pcon->DefineSection(1,-50,50,80); pcon->DefineSection(2,50,50,80); pcon->DefineSection(3,200,50,100); pgon = new TPGON("PGON","PGON","void",180,270,8,4); pgon->DefineSection(0,-200,50,100); pgon->DefineSection(1,-50,50,80); pgon->DefineSection(2,50,50,80); pgon->DefineSection(3,200,50,100); // Set shapes attributes brik->SetLineColor(1); trd1->SetLineColor(2); trd2->SetLineColor(3); trap->SetLineColor(4); para->SetLineColor(5); gtra->SetLineColor(7); tube->SetLineColor(6); tubs->SetLineColor(7); cone->SetLineColor(2); cons->SetLineColor(3); pcon->SetLineColor(6); pgon->SetLineColor(2); sphe->SetLineColor(kRed); sphe1->SetLineColor(kBlack); sphe2->SetLineColor(kBlue); // Build the geometry hierarchy node1 = new TNode("NODE1","NODE1","BRIK"); node1->cd(); node2 = new TNode("NODE2","NODE2","TRD1",0,0,-1000); node3 = new TNode("NODE3","NODE3","TRD2",0,0,1000); node4 = new TNode("NODE4","NODE4","TRAP",0,-1000,0); node5 = new TNode("NODE5","NODE5","PARA",0,1000,0); node6 = new TNode("NODE6","NODE6","TUBE",-1000,0,0); node7 = new TNode("NODE7","NODE7","TUBS",1000,0,0); node8 = new TNode("NODE8","NODE8","CONE",-300,-300,0); node9 = new TNode("NODE9","NODE9","CONS",300,300,0); node10 = new TNode("NODE10","NODE10","PCON",0,-1000,-1000); node11 = new TNode("NODE11","NODE11","PGON",0,1000,1000); node12 = new TNode("NODE12","NODE12","GTRA",0,-400,700); node13 = new TNode("NODE13","NODE13","SPHE",10,-400,500); node14 = new TNode("NODE14","NODE14","SPHE1",10, 250,300); node15 = new TNode("NODE15","NODE15","SPHE2",10,-100,-200); // Draw this geometry in the current canvas node1->cd(); node1->Draw(); c1->Update(); // // Draw the geometry using the x3d viewver. // Note that this viewver may also be invoked from the "View" menu in // the canvas tool bar c1->x3d(); // // once in x3d viewer, type m to see the menu. // For example typing r will show a solid model of this geometry. } <|endoftext|>
<commit_before>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * End to end tests for LLL. */ #include <string> #include <memory> #include <boost/test/unit_test.hpp> #include <test/liblll/ExecutionFramework.h> using namespace std; namespace dev { namespace lll { namespace test { BOOST_FIXTURE_TEST_SUITE(LLLEndToEndTest, LLLExecutionFramework) BOOST_AUTO_TEST_CASE(smoke_test) { char const* sourceCode = "(returnlll { (return \"test\") })"; compileAndRun(sourceCode); BOOST_CHECK(callFallback() == encodeArgs(string("test", 4))); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <commit_msg>Added 'panic' tests.<commit_after>/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * End to end tests for LLL. */ #include <string> #include <memory> #include <boost/test/unit_test.hpp> #include <test/liblll/ExecutionFramework.h> using namespace std; namespace dev { namespace lll { namespace test { BOOST_FIXTURE_TEST_SUITE(LLLEndToEndTest, LLLExecutionFramework) BOOST_AUTO_TEST_CASE(smoke_test) { char const* sourceCode = "(returnlll { (return \"test\") })"; compileAndRun(sourceCode); BOOST_CHECK(callFallback() == encodeArgs(string("test", 4))); } BOOST_AUTO_TEST_CASE(bare_panic) { char const* sourceCode = "(panic)"; compileAndRunWithoutCheck(sourceCode); BOOST_REQUIRE(m_output.empty()); } BOOST_AUTO_TEST_CASE(enclosed_panic) { char const* sourceCode = "(seq (panic))"; compileAndRunWithoutCheck(sourceCode); BOOST_REQUIRE(m_output.empty()); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces <|endoftext|>
<commit_before>#include "sys/rand.hpp" // #include "client/ui/menu.hpp" #include "game/ld22/screen.hpp" #include "client/opengl.hpp" #include "client/ui/event.hpp" #include "client/ui/window.hpp" #include "client/keyboard/keycode.h" #include "client/keyboard/keytable.h" #include "sys/path_posix.hpp" #include <gtk/gtk.h> #include <gtk/gtkgl.h> #include <stdlib.h> #include <unistd.h> class GTKWindow : public UI::Window { public: GTKWindow() : updateSize(false) { } virtual void close(); bool updateSize; }; void GTKWindow::close() { gtk_main_quit(); } static const unsigned int MAX_FPS = 100; static const unsigned int MIN_FRAMETIME = 1000 / MAX_FPS; static gboolean handle_expose(GtkWidget *area, GTKWindow *w) { GdkGLContext *context = gtk_widget_get_gl_context(area); GdkGLDrawable *drawable = gtk_widget_get_gl_drawable(area); if (!gdk_gl_drawable_gl_begin(drawable, context)) { fputs("Could not begin GL drawing\n", stderr); exit(1); } if (w->updateSize) { GtkAllocation a; gtk_widget_get_allocation(area, &a); glViewport(0, 0, a.width, a.height); w->setSize(a.width, a.height); } w->draw(); if (gdk_gl_drawable_is_double_buffered(drawable)) gdk_gl_drawable_swap_buffers(drawable); else glFlush(); gdk_gl_drawable_gl_end(drawable); return TRUE; } static gboolean handle_configure(GTKWindow *w) { w->updateSize = true; return TRUE; } static gboolean update(gpointer user_data) { GtkWidget *area = GTK_WIDGET(user_data); gdk_window_invalidate_rect(area->window, &area->allocation, FALSE); gdk_window_process_updates(area->window, FALSE); return TRUE; } static gboolean handle_key(GTKWindow *w, GdkEventKey *e, UI::EventType t) { int code = e->hardware_keycode, hcode; if (code < 0 || code > 255) return TRUE; hcode = EVDEV_NATIVE_TO_HID[code]; if (hcode == 255) return TRUE; UI::KeyEvent uevt(t, hcode); w->handleEvent(uevt); return TRUE; } static gboolean handle_motion(GTKWindow *w, GdkEventMotion *e) { int x = e->x, y = w->height() - 1 - e->y; UI::MouseEvent uevt(UI::MouseMove, -1, x, y); w->handleEvent(uevt); return TRUE; } static gboolean handle_button(GTKWindow *w, GdkEventButton *e, UI::EventType t) { int x = e->x, y = w->height() - 1 - e->y, button; switch (e->button) { case 1: button = UI::ButtonLeft; break; case 2: button = UI::ButtonMiddle; break; case 3: button = UI::ButtonRight; break; default: button = UI::ButtonOther + e->button - 4; break; } UI::MouseEvent uevt(t, button, x, y); w->handleEvent(uevt); return TRUE; } static gboolean handle_event(GtkWidget *widget, GdkEvent *event, gpointer user_data) { GTKWindow *w = reinterpret_cast<GTKWindow *>(user_data); switch (event->type) { case GDK_EXPOSE: return handle_expose(widget, w); case GDK_MOTION_NOTIFY: return handle_motion(w, &event->motion); case GDK_BUTTON_PRESS: return handle_button(w, &event->button, UI::MouseDown); case GDK_BUTTON_RELEASE: return handle_button(w, &event->button, UI::MouseUp); case GDK_KEY_PRESS: return handle_key(w, &event->key, UI::KeyDown); case GDK_KEY_RELEASE: return handle_key(w, &event->key, UI::KeyUp); case GDK_CONFIGURE: return handle_configure(w); default: return FALSE; } } static bool gEditor = false; static void init(int argc, char *argv[]) { int opt; const char *altpath = NULL; gtk_init(&argc, &argv); gtk_gl_init(&argc, &argv); while ((opt = getopt(argc, argv, "ei:")) != -1) { switch (opt) { case 'e': gEditor = true; break; case 'i': altpath = optarg; break; default: fputs("Invalid usage\n", stderr); exit(1); } } pathInit(altpath); Rand::global.seed(); } int main(int argc, char *argv[]) { gboolean r; GTKWindow w; init(argc, argv); w.setSize(768, 480); w.setScreen(new LD22::Screen); GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "Game"); gtk_window_set_default_size(GTK_WINDOW(window), 768, 480); g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL); GtkWidget *area = gtk_drawing_area_new(); gtk_container_add(GTK_CONTAINER(window), area); gtk_widget_set_can_focus(area, TRUE); unsigned mask = GDK_EXPOSURE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK; gtk_widget_set_events(area, mask); gtk_widget_show(window); gtk_widget_grab_focus(area); GdkScreen *screen = gtk_window_get_screen(GTK_WINDOW(window)); static const int ATTRIB_1[] = { GDK_GL_RGBA, GDK_GL_DOUBLEBUFFER, GDK_GL_RED_SIZE, 8, GDK_GL_BLUE_SIZE, 8, GDK_GL_GREEN_SIZE, 8, GDK_GL_ALPHA_SIZE, 8, GDK_GL_ATTRIB_LIST_NONE }; static const int ATTRIB_2[] = { GDK_GL_RGBA, GDK_GL_DOUBLEBUFFER, GDK_GL_RED_SIZE, 1, GDK_GL_BLUE_SIZE, 1, GDK_GL_GREEN_SIZE, 1, GDK_GL_ALPHA_SIZE, 1, GDK_GL_ATTRIB_LIST_NONE }; const int *attrib[] = { ATTRIB_1, ATTRIB_2, 0 }; GdkGLConfig *config = 0; for (unsigned int i = 0; !config && attrib[i]; ++i) config = gdk_gl_config_new_for_screen(screen, attrib[i]); if (!config) { fputs("Could not initialize GdkGL\n", stderr); return 1; } r = gtk_widget_set_gl_capability( area, config, NULL, TRUE, GDK_GL_RGBA_TYPE); if (!r) { fputs("Could not assign GL capability\n", stderr); return 1; } g_signal_connect(area, "event", G_CALLBACK(handle_event), &w); gtk_widget_show_all(window); g_timeout_add(10, update, area); gtk_main(); return 0; } <commit_msg>Initialize clock in Gtk port<commit_after>#include "sys/clock.hpp" #include "sys/rand.hpp" #include "game/ld22/screen.hpp" #include "client/opengl.hpp" #include "client/ui/event.hpp" #include "client/ui/window.hpp" #include "client/keyboard/keycode.h" #include "client/keyboard/keytable.h" #include "sys/path_posix.hpp" #include <gtk/gtk.h> #include <gtk/gtkgl.h> #include <stdlib.h> #include <unistd.h> class GTKWindow : public UI::Window { public: GTKWindow() : updateSize(false) { } virtual void close(); bool updateSize; }; void GTKWindow::close() { gtk_main_quit(); } static const unsigned int MAX_FPS = 100; static const unsigned int MIN_FRAMETIME = 1000 / MAX_FPS; static gboolean handle_expose(GtkWidget *area, GTKWindow *w) { GdkGLContext *context = gtk_widget_get_gl_context(area); GdkGLDrawable *drawable = gtk_widget_get_gl_drawable(area); if (!gdk_gl_drawable_gl_begin(drawable, context)) { fputs("Could not begin GL drawing\n", stderr); exit(1); } if (w->updateSize) { GtkAllocation a; gtk_widget_get_allocation(area, &a); glViewport(0, 0, a.width, a.height); w->setSize(a.width, a.height); } w->draw(); if (gdk_gl_drawable_is_double_buffered(drawable)) gdk_gl_drawable_swap_buffers(drawable); else glFlush(); gdk_gl_drawable_gl_end(drawable); return TRUE; } static gboolean handle_configure(GTKWindow *w) { w->updateSize = true; return TRUE; } static gboolean update(gpointer user_data) { GtkWidget *area = GTK_WIDGET(user_data); gdk_window_invalidate_rect(area->window, &area->allocation, FALSE); gdk_window_process_updates(area->window, FALSE); return TRUE; } static gboolean handle_key(GTKWindow *w, GdkEventKey *e, UI::EventType t) { int code = e->hardware_keycode, hcode; if (code < 0 || code > 255) return TRUE; hcode = EVDEV_NATIVE_TO_HID[code]; if (hcode == 255) return TRUE; UI::KeyEvent uevt(t, hcode); w->handleEvent(uevt); return TRUE; } static gboolean handle_motion(GTKWindow *w, GdkEventMotion *e) { int x = e->x, y = w->height() - 1 - e->y; UI::MouseEvent uevt(UI::MouseMove, -1, x, y); w->handleEvent(uevt); return TRUE; } static gboolean handle_button(GTKWindow *w, GdkEventButton *e, UI::EventType t) { int x = e->x, y = w->height() - 1 - e->y, button; switch (e->button) { case 1: button = UI::ButtonLeft; break; case 2: button = UI::ButtonMiddle; break; case 3: button = UI::ButtonRight; break; default: button = UI::ButtonOther + e->button - 4; break; } UI::MouseEvent uevt(t, button, x, y); w->handleEvent(uevt); return TRUE; } static gboolean handle_event(GtkWidget *widget, GdkEvent *event, gpointer user_data) { GTKWindow *w = reinterpret_cast<GTKWindow *>(user_data); switch (event->type) { case GDK_EXPOSE: return handle_expose(widget, w); case GDK_MOTION_NOTIFY: return handle_motion(w, &event->motion); case GDK_BUTTON_PRESS: return handle_button(w, &event->button, UI::MouseDown); case GDK_BUTTON_RELEASE: return handle_button(w, &event->button, UI::MouseUp); case GDK_KEY_PRESS: return handle_key(w, &event->key, UI::KeyDown); case GDK_KEY_RELEASE: return handle_key(w, &event->key, UI::KeyUp); case GDK_CONFIGURE: return handle_configure(w); default: return FALSE; } } static bool gEditor = false; static void init(int argc, char *argv[]) { int opt; const char *altpath = NULL; gtk_init(&argc, &argv); gtk_gl_init(&argc, &argv); while ((opt = getopt(argc, argv, "ei:")) != -1) { switch (opt) { case 'e': gEditor = true; break; case 'i': altpath = optarg; break; default: fputs("Invalid usage\n", stderr); exit(1); } } pathInit(altpath); initTime(); Rand::global.seed(); } int main(int argc, char *argv[]) { gboolean r; GTKWindow w; init(argc, argv); w.setSize(768, 480); w.setScreen(new LD22::Screen); GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "Game"); gtk_window_set_default_size(GTK_WINDOW(window), 768, 480); g_signal_connect_swapped(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL); GtkWidget *area = gtk_drawing_area_new(); gtk_container_add(GTK_CONTAINER(window), area); gtk_widget_set_can_focus(area, TRUE); unsigned mask = GDK_EXPOSURE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK; gtk_widget_set_events(area, mask); gtk_widget_show(window); gtk_widget_grab_focus(area); GdkScreen *screen = gtk_window_get_screen(GTK_WINDOW(window)); static const int ATTRIB_1[] = { GDK_GL_RGBA, GDK_GL_DOUBLEBUFFER, GDK_GL_RED_SIZE, 8, GDK_GL_BLUE_SIZE, 8, GDK_GL_GREEN_SIZE, 8, GDK_GL_ALPHA_SIZE, 8, GDK_GL_ATTRIB_LIST_NONE }; static const int ATTRIB_2[] = { GDK_GL_RGBA, GDK_GL_DOUBLEBUFFER, GDK_GL_RED_SIZE, 1, GDK_GL_BLUE_SIZE, 1, GDK_GL_GREEN_SIZE, 1, GDK_GL_ALPHA_SIZE, 1, GDK_GL_ATTRIB_LIST_NONE }; const int *attrib[] = { ATTRIB_1, ATTRIB_2, 0 }; GdkGLConfig *config = 0; for (unsigned int i = 0; !config && attrib[i]; ++i) config = gdk_gl_config_new_for_screen(screen, attrib[i]); if (!config) { fputs("Could not initialize GdkGL\n", stderr); return 1; } r = gtk_widget_set_gl_capability( area, config, NULL, TRUE, GDK_GL_RGBA_TYPE); if (!r) { fputs("Could not assign GL capability\n", stderr); return 1; } g_signal_connect(area, "event", G_CALLBACK(handle_event), &w); gtk_widget_show_all(window); g_timeout_add(10, update, area); gtk_main(); return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; int main(int argc, char **argv) { string imgadr; string guiWindowName = "Select Target Region"; if (argc > 1) { imgadr = argv[1]; } else { imgadr = "/Users/yasser/sci-repo/opencv/samples/cpp/pic4.png"; } cv::Mat img = cv::imread(imgadr, 1); if (img.empty()) { cerr << "PROB: Cannot Load File" << endl; return 1; } cv::namedWindow(guiWindowName, cv::WINDOW_AUTOSIZE); cv::imshow(guiWindowName, img); cv::moveWindow(guiWindowName, 200, 300); cv::waitKey(0); return 0; } <commit_msg>make the logic work now it is time to draw stuff actually<commit_after>#include <stdio.h> #include <stdlib.h> #include <vector> #include <map> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace std; const char MODE_NO_SELECTION = 'n'; const char MODE_SELECTION = 's'; const char MODE_DONE = 'd'; const char ACTION_UNDO = 'u'; map<char, string> *modeDescriptions = new map<char, string>; char mode = MODE_NO_SELECTION; vector<cv::Point> *points = new vector<cv::Point>(); int keyPressed = -1; char charTyped = ' '; static void onMouse(int event, int x, int y, int, void*) { switch (mode) { case MODE_NO_SELECTION: if (event == cv::EVENT_LBUTTONDOWN) { mode = MODE_SELECTION; points->push_back(cv::Point(x, y)); } break; case MODE_SELECTION: if (event == cv::EVENT_LBUTTONDOWN) { points->push_back(cv::Point(x, y)); } else if(event == cv::EVENT_RBUTTONDOWN) { mode = MODE_DONE; } break; default: break; } cout << mode << '|' << points->size() << endl; } int main(int argc, char **argv) { string imgadr; string guiWindowName = "Select Target Region"; if (argc > 1) { imgadr = argv[1]; } else { imgadr = "/Users/yasser/sci-repo/opencv/samples/cpp/pic4.png"; } cv::Mat img = cv::imread(imgadr, 1); if (img.empty()) { cerr << "PROB: Cannot Load File" << endl; return 1; } while(1) { cv::namedWindow(guiWindowName, cv::WINDOW_AUTOSIZE); cv::setMouseCallback(guiWindowName, onMouse); cv::imshow(guiWindowName, img); cv::moveWindow(guiWindowName, 200, 300); keyPressed = cv::waitKey(0); bool toExit = false; if ((keyPressed & 255) == 27) { switch (mode) { case MODE_SELECTION: case MODE_DONE: mode = MODE_NO_SELECTION; points->clear(); break; case MODE_NO_SELECTION: toExit = true; break; default: break; } if (toExit) { break; } } else { charTyped = (char) keyPressed; switch (charTyped) { case ACTION_UNDO: if (mode == MODE_SELECTION) { points->pop_back(); } break; default: break; } } // FIXME: REDRAW. } return 0; } <|endoftext|>
<commit_before>#include <QApplication> #include <QFontDatabase> #include <QtGlobal> #include <QFile> #include "neovimconnector.h" #include "mainwindow.h" /** * A log handler for Qt messages, all messages are dumped into the file * passed via the NEOVIM_QT_LOG variable. Some information is only available * in debug builds (e.g. qDebug is only called in debug builds). * * In UNIX Qt prints messages to the console output, but in Windows this is * the only way to get Qt's debug/warning messages. */ void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg) { QFile logFile(qgetenv("NEOVIM_QT_LOG")); if (logFile.open(QIODevice::Append | QIODevice::Text)) { QTextStream stream(&logFile); stream << msg << "\n"; } } /** * Neovim Qt GUI * * Usage: * nvim-qt --server <SOCKET> * nvim-qt [...] * * When --server is not provided, a Neovim instance will be spawned. All arguments * are passed to the Neovim process. */ int main(int argc, char **argv) { QApplication app(argc, argv); app.setApplicationDisplayName("Neovim"); app.setWindowIcon(QIcon(":/neovim.png")); if (!qgetenv("NEOVIM_QT_LOG").isEmpty()) { qInstallMessageHandler(logger); } // Load bundled fonts if (QFontDatabase::addApplicationFont(":/DejaVuSansMono.ttf") == -1) { qWarning("Unable to load bundled font"); } if (QFontDatabase::addApplicationFont(":/DejaVuSansMono-Bold.ttf") == -1) { qWarning("Unable to load bundled bold font"); } if (QFontDatabase::addApplicationFont(":/DejaVuSansMono-Oblique.ttf") == -1) { qWarning("Unable to load bundled italic font"); } if (QFontDatabase::addApplicationFont(":/DejaVuSansMono-BoldOblique.ttf") == -1) { qWarning("Unable to load bundled bold/italic font"); } QString server; QStringList args = app.arguments().mid(1); int serverIdx = args.indexOf("--server"); if (serverIdx != -1 && args.size() > serverIdx+1) { server = args.at(serverIdx+1); args.removeAt(serverIdx); args.removeAt(serverIdx); } NeovimQt::NeovimConnector *c; if (!server.isEmpty()) { c = NeovimQt::NeovimConnector::connectToNeovim(server); } else { c = NeovimQt::NeovimConnector::spawn(args); } #ifdef NEOVIMQT_GUI_WIDGET NeovimQt::Shell *win = new NeovimQt::Shell(c); #else NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c); #endif win->show(); return app.exec(); } <commit_msg>Rename NEOVIM_QT_LOG to NVIM_QT_LOG<commit_after>#include <QApplication> #include <QFontDatabase> #include <QtGlobal> #include <QFile> #include "neovimconnector.h" #include "mainwindow.h" /** * A log handler for Qt messages, all messages are dumped into the file * passed via the NVIM_QT_LOG variable. Some information is only available * in debug builds (e.g. qDebug is only called in debug builds). * * In UNIX Qt prints messages to the console output, but in Windows this is * the only way to get Qt's debug/warning messages. */ void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg) { QFile logFile(qgetenv("NVIM_QT_LOG")); if (logFile.open(QIODevice::Append | QIODevice::Text)) { QTextStream stream(&logFile); stream << msg << "\n"; } } /** * Neovim Qt GUI * * Usage: * nvim-qt --server <SOCKET> * nvim-qt [...] * * When --server is not provided, a Neovim instance will be spawned. All arguments * are passed to the Neovim process. */ int main(int argc, char **argv) { QApplication app(argc, argv); app.setApplicationDisplayName("Neovim"); app.setWindowIcon(QIcon(":/neovim.png")); if (!qgetenv("NVIM_QT_LOG").isEmpty()) { qInstallMessageHandler(logger); } // Load bundled fonts if (QFontDatabase::addApplicationFont(":/DejaVuSansMono.ttf") == -1) { qWarning("Unable to load bundled font"); } if (QFontDatabase::addApplicationFont(":/DejaVuSansMono-Bold.ttf") == -1) { qWarning("Unable to load bundled bold font"); } if (QFontDatabase::addApplicationFont(":/DejaVuSansMono-Oblique.ttf") == -1) { qWarning("Unable to load bundled italic font"); } if (QFontDatabase::addApplicationFont(":/DejaVuSansMono-BoldOblique.ttf") == -1) { qWarning("Unable to load bundled bold/italic font"); } QString server; QStringList args = app.arguments().mid(1); int serverIdx = args.indexOf("--server"); if (serverIdx != -1 && args.size() > serverIdx+1) { server = args.at(serverIdx+1); args.removeAt(serverIdx); args.removeAt(serverIdx); } NeovimQt::NeovimConnector *c; if (!server.isEmpty()) { c = NeovimQt::NeovimConnector::connectToNeovim(server); } else { c = NeovimQt::NeovimConnector::spawn(args); } #ifdef NEOVIMQT_GUI_WIDGET NeovimQt::Shell *win = new NeovimQt::Shell(c); #else NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c); #endif win->show(); return app.exec(); } <|endoftext|>
<commit_before><commit_msg>fixed autocomplete crash - fixes #1133<commit_after><|endoftext|>
<commit_before>/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ (test suite) | | |__ | | | | | | version 3.1.2 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT Copyright (c) 2018 Vitaliy Manushkin <[email protected]>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "catch.hpp" #include <nlohmann/json.hpp> #include <string> #include <utility> /* forward declarations */ class alt_string; bool operator<(const char* op1, const alt_string& op2); /* * This is virtually a string class. * It covers std::string under the hood. */ class alt_string { public: using value_type = std::string::value_type; alt_string(const char* str): str_impl(str) {} alt_string(const char* str, std::size_t count): str_impl(str, count) {} alt_string(size_t count, char chr): str_impl(count, chr) {} alt_string() = default; template <typename...TParams> alt_string& append(TParams&& ...params) { str_impl.append(std::forward<TParams>(params)...); return *this; } void push_back(char c) { str_impl.push_back(c); } template <typename op_type> typename std::enable_if< // disable for alt_string !std::is_same< alt_string, typename std::remove_reference<op_type>::type >::value, bool>::type operator==(op_type&& op) const { return str_impl == op; } bool operator==(const alt_string& op) const { return str_impl == op.str_impl; } template <typename op_type> typename std::enable_if< // disable for alt_string !std::is_same< alt_string, typename std::remove_reference<op_type>::type >::value, bool>::type operator!=(op_type&& op) const { return str_impl != op; } bool operator!=(const alt_string& op) const { return str_impl != op.str_impl; } std::size_t size() const noexcept { return str_impl.size(); } void resize (std::size_t n) { str_impl.resize(n); } void resize (std::size_t n, char c) { str_impl.resize(n, c); } template <typename op_type> typename std::enable_if< // disable for alt_string !std::is_same< alt_string, typename std::remove_reference<op_type>::type >::value, bool>::type operator<(op_type&& op) const { return str_impl < op; } bool operator<(const alt_string& op) const { return str_impl < op.str_impl; } const char* c_str() const { return str_impl.c_str(); } char& operator[](std::size_t index) { return str_impl[index]; } const char& operator[](std::size_t index) const { return str_impl[index]; } char& back() { return str_impl.back(); } const char& back() const { return str_impl.back(); } void clear() { str_impl.clear(); } const value_type* data() { return str_impl.data(); } private: std::string str_impl; friend bool ::operator<(const char*, const alt_string&); }; using alt_json = nlohmann::basic_json < std::map, std::vector, alt_string, bool, std::int64_t, std::uint64_t, double, std::allocator, nlohmann::adl_serializer >; bool operator<(const char* op1, const alt_string& op2) { return op1 < op2.str_impl; } TEST_CASE("alternative string type") { SECTION("dump") { { alt_json doc; doc["pi"] = 3.141; alt_string dump = doc.dump(); CHECK(dump == R"({"pi":3.141})"); } { alt_json doc; doc["happy"] = true; alt_string dump = doc.dump(); CHECK(dump == R"({"happy":true})"); } { alt_json doc; doc["name"] = "I'm Batman"; alt_string dump = doc.dump(); CHECK(dump == R"({"name":"I'm Batman"})"); } { alt_json doc; doc["nothing"] = nullptr; alt_string dump = doc.dump(); CHECK(dump == R"({"nothing":null})"); } { alt_json doc; doc["answer"]["everything"] = 42; alt_string dump = doc.dump(); CHECK(dump == R"({"answer":{"everything":42}})"); } { alt_json doc; doc["list"] = { 1, 0, 2 }; alt_string dump = doc.dump(); CHECK(dump == R"({"list":[1,0,2]})"); } { alt_json doc; doc["list"] = { 1, 0, 2 }; alt_string dump = doc.dump(); CHECK(dump == R"({"list":[1,0,2]})"); } } SECTION("parse") { auto doc = alt_json::parse("{\"foo\": \"bar\"}"); alt_string dump = doc.dump(); CHECK(dump == R"({"foo":"bar"})"); } SECTION("equality") { alt_json doc; doc["Who are you?"] = "I'm Batman"; CHECK("I'm Batman" == doc["Who are you?"]); CHECK(doc["Who are you?"] == "I'm Batman"); CHECK("I'm Bruce Wayne" != doc["Who are you?"]); CHECK(doc["Who are you?"] != "I'm Bruce Wayne"); { const alt_json& const_doc = doc; CHECK("I'm Batman" == const_doc["Who are you?"]); CHECK(const_doc["Who are you?"] == "I'm Batman"); CHECK("I'm Bruce Wayne" != const_doc["Who are you?"]); CHECK(const_doc["Who are you?"] != "I'm Bruce Wayne"); } } } <commit_msg>simplify templates for operators, add more checks<commit_after>/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ (test suite) | | |__ | | | | | | version 3.1.2 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT Copyright (c) 2018 Vitaliy Manushkin <[email protected]>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "catch.hpp" #include <nlohmann/json.hpp> #include <string> #include <utility> /* forward declarations */ class alt_string; bool operator<(const char* op1, const alt_string& op2); /* * This is virtually a string class. * It covers std::string under the hood. */ class alt_string { public: using value_type = std::string::value_type; alt_string(const char* str): str_impl(str) {} alt_string(const char* str, std::size_t count): str_impl(str, count) {} alt_string(size_t count, char chr): str_impl(count, chr) {} alt_string() = default; template <typename...TParams> alt_string& append(TParams&& ...params) { str_impl.append(std::forward<TParams>(params)...); return *this; } void push_back(char c) { str_impl.push_back(c); } template <typename op_type> bool operator==(const op_type& op) const { return str_impl == op; } bool operator==(const alt_string& op) const { return str_impl == op.str_impl; } template <typename op_type> bool operator!=(const op_type& op) const { return str_impl != op; } bool operator!=(const alt_string& op) const { return str_impl != op.str_impl; } std::size_t size() const noexcept { return str_impl.size(); } void resize (std::size_t n) { str_impl.resize(n); } void resize (std::size_t n, char c) { str_impl.resize(n, c); } template <typename op_type> bool operator<(const op_type& op) const { return str_impl < op; } bool operator<(const alt_string& op) const { return str_impl < op.str_impl; } const char* c_str() const { return str_impl.c_str(); } char& operator[](std::size_t index) { return str_impl[index]; } const char& operator[](std::size_t index) const { return str_impl[index]; } char& back() { return str_impl.back(); } const char& back() const { return str_impl.back(); } void clear() { str_impl.clear(); } const value_type* data() { return str_impl.data(); } private: std::string str_impl; friend bool ::operator<(const char*, const alt_string&); }; using alt_json = nlohmann::basic_json < std::map, std::vector, alt_string, bool, std::int64_t, std::uint64_t, double, std::allocator, nlohmann::adl_serializer >; bool operator<(const char* op1, const alt_string& op2) { return op1 < op2.str_impl; } TEST_CASE("alternative string type") { SECTION("dump") { { alt_json doc; doc["pi"] = 3.141; alt_string dump = doc.dump(); CHECK(dump == R"({"pi":3.141})"); } { alt_json doc; doc["happy"] = true; alt_string dump = doc.dump(); CHECK(dump == R"({"happy":true})"); } { alt_json doc; doc["name"] = "I'm Batman"; alt_string dump = doc.dump(); CHECK(dump == R"({"name":"I'm Batman"})"); } { alt_json doc; doc["nothing"] = nullptr; alt_string dump = doc.dump(); CHECK(dump == R"({"nothing":null})"); } { alt_json doc; doc["answer"]["everything"] = 42; alt_string dump = doc.dump(); CHECK(dump == R"({"answer":{"everything":42}})"); } { alt_json doc; doc["list"] = { 1, 0, 2 }; alt_string dump = doc.dump(); CHECK(dump == R"({"list":[1,0,2]})"); } { alt_json doc; doc["list"] = { 1, 0, 2 }; alt_string dump = doc.dump(); CHECK(dump == R"({"list":[1,0,2]})"); } } SECTION("parse") { auto doc = alt_json::parse("{\"foo\": \"bar\"}"); alt_string dump = doc.dump(); CHECK(dump == R"({"foo":"bar"})"); } SECTION("equality") { alt_json doc; doc["Who are you?"] = "I'm Batman"; CHECK("I'm Batman" == doc["Who are you?"]); CHECK(doc["Who are you?"] == "I'm Batman"); CHECK_FALSE("I'm Batman" != doc["Who are you?"]); CHECK_FALSE(doc["Who are you?"] != "I'm Batman"); CHECK("I'm Bruce Wayne" != doc["Who are you?"]); CHECK(doc["Who are you?"] != "I'm Bruce Wayne"); CHECK_FALSE("I'm Bruce Wayne" == doc["Who are you?"]); CHECK_FALSE(doc["Who are you?"] == "I'm Bruce Wayne"); { const alt_json& const_doc = doc; CHECK("I'm Batman" == const_doc["Who are you?"]); CHECK(const_doc["Who are you?"] == "I'm Batman"); CHECK_FALSE("I'm Batman" != const_doc["Who are you?"]); CHECK_FALSE(const_doc["Who are you?"] != "I'm Batman"); CHECK("I'm Bruce Wayne" != const_doc["Who are you?"]); CHECK(const_doc["Who are you?"] != "I'm Bruce Wayne"); CHECK_FALSE("I'm Bruce Wayne" == const_doc["Who are you?"]); CHECK_FALSE(const_doc["Who are you?"] == "I'm Bruce Wayne"); } } } <|endoftext|>
<commit_before>/* * Copyright 2016 Christian Lockley * * 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 "watchdogd.hpp" #include "logutils.hpp" #include "sub.hpp" int Identify(long timeout, const char * identity, const char * deviceName, bool verbose) { struct sockaddr_un address = {0}; struct identinfo buf; int fd = -1; address.sun_family = AF_UNIX; strncpy(address.sun_path, "\0watchdogd.wdt.identity", sizeof(address.sun_path)-1); fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); if (fd < 0) { goto error; } if (connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) { close(fd); goto direct; } read(fd, &buf, sizeof(buf)); close(fd); if (verbose) { printf("watchdog was set to %li seconds\n", buf.timeout); } printf("%s\n", buf.name); return 0; direct: if (verbose) { printf("watchdog was set to %li seconds\n", timeout); } printf("%s\n", identity); return 0; error: printf("%s\n", "Unable to open watchdog device"); if (fd >= 0) { close(fd); } return 0; } <commit_msg>remove dead code<commit_after>/* * Copyright 2016 Christian Lockley * * 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 "watchdogd.hpp" #include "logutils.hpp" #include "sub.hpp" int Identify(long timeout, const char * identity, const char * deviceName, bool verbose) { struct sockaddr_un address = {0}; struct identinfo buf; int fd = -1; address.sun_family = AF_UNIX; strncpy(address.sun_path, "\0watchdogd.wdt.identity", sizeof(address.sun_path)-1); fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); if (fd < 0) { goto error; } if (connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) { close(fd); goto direct; } read(fd, &buf, sizeof(buf)); close(fd); if (verbose) { printf("watchdog was set to %li seconds\n", buf.timeout); } printf("%s\n", buf.name); return 0; direct: if (verbose) { printf("watchdog was set to %li seconds\n", timeout); } printf("%s\n", identity); return 0; error: printf("%s\n", "Unable to open watchdog device"); close(fd); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2009, Piotr Korzuszek * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 "VoteSystem.h" #include <assert.h> #include <ClanLib/core.h> #include "common.h" /** Yes to No ratio that will result in succeeded voting */ const float PASS_RATIO = 1.0f * (2.0f / 3.0f) - 0.001f; /** No to Yes ratio that will result in failed voting */ const float FAIL_RATIO = 1.0f * (1.0f / 3.0f) - 0.001f; namespace Net { VoteSystem::VoteSystem() : m_state(S_HOLD) { m_timer.func_expired().set(this, &VoteSystem::onTimerExpired); } VoteSystem::~VoteSystem() { } VoteResult VoteSystem::getResult() const { assert(isFinished()); return m_result != -1 ? (VoteResult) m_result : VOTE_FAILED; } bool VoteSystem::isFinished() const { return m_state == S_FINISHED; } bool VoteSystem::isRunning() const { return m_state == S_RUNNING; } bool VoteSystem::addVote(VoteOption p_option, int p_voterId) { if(!hasVoter(p_voterId)) { switch (p_option) { case VOTE_YES: ++m_yesCount; break; case VOTE_NO: ++m_noCount; break; default: assert(0 && "unknown vote option"); } m_voters.push_back(p_voterId); // calculate result m_result = calculateResult(); if (m_result != -1) { // finished, set state and call functor m_state = S_FINISHED; m_timer.stop(); C_INVOKE_0(finished); } return true; } else { cl_log_event(LOG_WARN, "multiple vote attempt from %1", p_voterId); return false; } } void VoteSystem::start(VoteType p_type, unsigned p_voterCount, unsigned p_timeLimit) { m_type = p_type; m_voterCount = p_voterCount; m_yesCount = m_noCount = 0; m_result = -1; m_state = S_RUNNING; m_voters.clear(); m_timer.start(p_timeLimit, false); } int VoteSystem::calculateResult() const { // check if passed const float yesToAllRatio = m_yesCount / (float) m_voterCount; if (yesToAllRatio >= PASS_RATIO) { return (int) VOTE_PASSED; } // check if failed const float noToAllRatio = m_noCount / (float) m_voterCount; if (noToAllRatio > FAIL_RATIO) { return (int) VOTE_FAILED; } // not decided yet return -1; } bool VoteSystem::hasVoter(int p_id) const { foreach (int id, m_voters) { if (id == p_id) { return true; } } return false; } void VoteSystem::onTimerExpired() { if (m_state == S_RUNNING) { m_state = S_FINISHED; C_INVOKE_0(finished); } } VoteType VoteSystem::getType() const { return m_type; } } // namespace <commit_msg>Better voting rules<commit_after>/* * Copyright (c) 2009, Piotr Korzuszek * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 "VoteSystem.h" #include <assert.h> #include <ClanLib/core.h> #include "common.h" /** Yes to all ratio that will result in succeeded voting */ const float PASS_RATIO = 1.0f / 2.0f - 0.001f; /** No to all ratio that will result in failed voting */ const float FAIL_RATIO = PASS_RATIO; namespace Net { VoteSystem::VoteSystem() : m_state(S_HOLD) { m_timer.func_expired().set(this, &VoteSystem::onTimerExpired); } VoteSystem::~VoteSystem() { } VoteResult VoteSystem::getResult() const { assert(isFinished()); return m_result != -1 ? (VoteResult) m_result : VOTE_FAILED; } bool VoteSystem::isFinished() const { return m_state == S_FINISHED; } bool VoteSystem::isRunning() const { return m_state == S_RUNNING; } bool VoteSystem::addVote(VoteOption p_option, int p_voterId) { if(!hasVoter(p_voterId)) { switch (p_option) { case VOTE_YES: ++m_yesCount; break; case VOTE_NO: ++m_noCount; break; default: assert(0 && "unknown vote option"); } m_voters.push_back(p_voterId); // calculate result m_result = calculateResult(); if (m_result != -1) { // finished, set state and call functor m_state = S_FINISHED; m_timer.stop(); C_INVOKE_0(finished); } return true; } else { cl_log_event(LOG_WARN, "multiple vote attempt from %1", p_voterId); return false; } } void VoteSystem::start(VoteType p_type, unsigned p_voterCount, unsigned p_timeLimit) { m_type = p_type; m_voterCount = p_voterCount; m_yesCount = m_noCount = 0; m_result = -1; m_state = S_RUNNING; m_voters.clear(); m_timer.start(p_timeLimit, false); } int VoteSystem::calculateResult() const { // check if passed const float yesToAllRatio = m_yesCount / (float) m_voterCount; if (yesToAllRatio >= PASS_RATIO) { return (int) VOTE_PASSED; } // check if failed const float noToAllRatio = m_noCount / (float) m_voterCount; if (noToAllRatio > FAIL_RATIO) { return (int) VOTE_FAILED; } // not decided yet return -1; } bool VoteSystem::hasVoter(int p_id) const { foreach (int id, m_voters) { if (id == p_id) { return true; } } return false; } void VoteSystem::onTimerExpired() { if (m_state == S_RUNNING) { m_state = S_FINISHED; C_INVOKE_0(finished); } } VoteType VoteSystem::getType() const { return m_type; } } // namespace <|endoftext|>
<commit_before>#include "oddlib/compressiontype3ae.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <vector> #include <cassert> static Uint16 ReadUint16(Oddlib::IStream& stream) { Uint16 ret = 0; stream.ReadUInt16(ret); return ret; } static Uint32 ReadUint32(Oddlib::IStream& stream) { Uint32 ret = 0; stream.ReadUInt32(ret); return ret; } template<typename T> static void ReadNextSource(Oddlib::IStream& stream, int& control_byte, T& dstIndex) { if (control_byte) { if (control_byte == 0xE) { control_byte = 0x1Eu; dstIndex |= ReadUint16(stream) << 14; } } else { dstIndex = ReadUint32(stream); control_byte = 0x20u; } } namespace Oddlib { std::vector<Uint8> CompressionType3Ae::Decompress(IStream& stream, Uint32 size, Uint32 w, Uint32 h) { LOG_INFO("Data size is " << size); // TODO: Shouldn't need to be * 4 std::vector< unsigned char > buffer(w*h * 4); unsigned char *aDbufPtr = &buffer[0]; int control_byte; // esi@1 int dstIndex; // edx@2 unsigned char *dstPtr; // edi@2 int count; // ebx@3 unsigned char blackBytes; // al@8 unsigned int srcByte; // edx@8 int bytesToWrite; // ebx@8 int control_byte_sub6; // esi@8 int i; // ecx@9 unsigned char *dstBlackBytesPtr; // edi@9 unsigned int doubleBBytes; // ecx@9 int byteCount; // ecx@18 char dstByte; // al@23 int v18; // [sp+8h] [bp-14h]@1 int v19; // [sp+8h] [bp-14h]@8 int width; // [sp+10h] [bp-Ch]@1 int height; // [sp+14h] [bp-8h]@2 unsigned char bytes; // [sp+20h] [bp+4h]@17 control_byte = 0; width = ReadUint16(stream); v18 = 0; height = ReadUint16(stream); if (height > 0) { dstIndex = 0;// (int)aDbufPtr; dstPtr = aDbufPtr; do { count = 0; while (count < width) { ReadNextSource(stream, control_byte, dstIndex); blackBytes = dstIndex & 0x3F; control_byte_sub6 = control_byte - 6; srcByte = (unsigned int)dstIndex >> 6; v19 = v18 - 1; bytesToWrite = blackBytes + count; if (blackBytes > 0) { doubleBBytes = (unsigned int)blackBytes >> 2; memset(dstPtr, 0, 4 * doubleBBytes); dstBlackBytesPtr = &dstPtr[4 * doubleBBytes]; for (i = blackBytes & 3; i; --i) { *dstBlackBytesPtr++ = 0; } dstPtr = &aDbufPtr[blackBytes]; aDbufPtr += blackBytes; } ReadNextSource(stream, control_byte_sub6, srcByte); control_byte = control_byte_sub6 - 6; bytes = srcByte & 0x3F; dstIndex = srcByte >> 6; v18 = v19 - 1; count = bytes + bytesToWrite; if ((signed int)bytes > 0) { byteCount = bytes; v18 -= bytes; do { ReadNextSource(stream, control_byte, dstIndex); control_byte -= 6; dstByte = dstIndex & 0x3F; dstIndex = (unsigned int)dstIndex >> 6; *dstPtr++ = dstByte; --byteCount; } while (byteCount); aDbufPtr = dstPtr; } } if (count & 3) { do { ++dstPtr; ++count; } while (count & 3); aDbufPtr = dstPtr; } } while (height-- != 1); } return buffer; } } <commit_msg>unused vars removed<commit_after>#include "oddlib/compressiontype3ae.hpp" #include "oddlib/stream.hpp" #include "logger.hpp" #include <vector> #include <cassert> static Uint16 ReadUint16(Oddlib::IStream& stream) { Uint16 ret = 0; stream.ReadUInt16(ret); return ret; } static Uint32 ReadUint32(Oddlib::IStream& stream) { Uint32 ret = 0; stream.ReadUInt32(ret); return ret; } template<typename T> static void ReadNextSource(Oddlib::IStream& stream, int& control_byte, T& dstIndex) { if (control_byte) { if (control_byte == 0xE) { control_byte = 0x1Eu; dstIndex |= ReadUint16(stream) << 14; } } else { dstIndex = ReadUint32(stream); control_byte = 0x20u; } } namespace Oddlib { std::vector<Uint8> CompressionType3Ae::Decompress(IStream& stream, Uint32 size, Uint32 w, Uint32 h) { LOG_INFO("Data size is " << size); // TODO: Shouldn't need to be * 4 std::vector< unsigned char > buffer(w*h * 4); unsigned char *aDbufPtr = &buffer[0]; int control_byte; // esi@1 int dstIndex; // edx@2 unsigned char *dstPtr; // edi@2 int count; // ebx@3 unsigned char blackBytes; // al@8 unsigned int srcByte; // edx@8 int bytesToWrite; // ebx@8 int i; // ecx@9 unsigned char *dstBlackBytesPtr; // edi@9 unsigned int doubleBBytes; // ecx@9 int byteCount; // ecx@18 char dstByte; // al@23 int width; // [sp+10h] [bp-Ch]@1 int height; // [sp+14h] [bp-8h]@2 unsigned char bytes; // [sp+20h] [bp+4h]@17 control_byte = 0; width = ReadUint16(stream); height = ReadUint16(stream); if (height > 0) { dstIndex = 0;// (int)aDbufPtr; dstPtr = aDbufPtr; do { count = 0; while (count < width) { ReadNextSource(stream, control_byte, dstIndex); blackBytes = dstIndex & 0x3F; control_byte = control_byte - 6; srcByte = (unsigned int)dstIndex >> 6; bytesToWrite = blackBytes + count; if (blackBytes > 0) { doubleBBytes = (unsigned int)blackBytes >> 2; memset(dstPtr, 0, 4 * doubleBBytes); dstBlackBytesPtr = &dstPtr[4 * doubleBBytes]; for (i = blackBytes & 3; i; --i) { *dstBlackBytesPtr++ = 0; } dstPtr = &aDbufPtr[blackBytes]; aDbufPtr += blackBytes; } ReadNextSource(stream, control_byte, srcByte); control_byte = control_byte - 6; bytes = srcByte & 0x3F; dstIndex = srcByte >> 6; count = bytes + bytesToWrite; if ((signed int)bytes > 0) { byteCount = bytes; do { ReadNextSource(stream, control_byte, dstIndex); control_byte -= 6; dstByte = dstIndex & 0x3F; dstIndex = (unsigned int)dstIndex >> 6; *dstPtr++ = dstByte; --byteCount; } while (byteCount); aDbufPtr = dstPtr; } } if (count & 3) { do { ++dstPtr; ++count; } while (count & 3); aDbufPtr = dstPtr; } } while (height-- != 1); } return buffer; } } <|endoftext|>
<commit_before>// These file is designed to have no dependencies outside the C++ Standard Library #include <fstream> #include <iostream> #include <limits> #include <map> #include <string> #include <sstream> #include <vector> #include "janus_io.h" using namespace std; #define ENUM_CASE(X) case JANUS_##X: return #X; #define ENUM_COMPARE(X,Y) if (!strcmp(#X, Y)) return JANUS_##X; const char *janus_error_to_string(janus_error error) { switch (error) { ENUM_CASE(SUCCESS) ENUM_CASE(UNKNOWN_ERROR) ENUM_CASE(OUT_OF_MEMORY) ENUM_CASE(INVALID_SDK_PATH) ENUM_CASE(OPEN_ERROR) ENUM_CASE(READ_ERROR) ENUM_CASE(WRITE_ERROR) ENUM_CASE(PARSE_ERROR) ENUM_CASE(INVALID_IMAGE) ENUM_CASE(INVALID_VIDEO) ENUM_CASE(MISSING_TEMPLATE_ID) ENUM_CASE(MISSING_FILE_NAME) ENUM_CASE(NULL_ATTRIBUTE_LIST) ENUM_CASE(NUM_ERRORS) } return "UNKNOWN_ERROR"; } janus_error janus_error_from_string(const char *error) { ENUM_COMPARE(SUCCESS, error) ENUM_COMPARE(UNKNOWN_ERROR, error) ENUM_COMPARE(OUT_OF_MEMORY, error) ENUM_COMPARE(INVALID_SDK_PATH, error) ENUM_COMPARE(OPEN_ERROR, error) ENUM_COMPARE(READ_ERROR, error) ENUM_COMPARE(WRITE_ERROR, error) ENUM_COMPARE(PARSE_ERROR, error) ENUM_COMPARE(INVALID_IMAGE, error) ENUM_COMPARE(INVALID_VIDEO, error) ENUM_COMPARE(MISSING_TEMPLATE_ID, error) ENUM_COMPARE(MISSING_FILE_NAME, error) ENUM_COMPARE(NULL_ATTRIBUTE_LIST, error) ENUM_COMPARE(NUM_ERRORS, error) return JANUS_UNKNOWN_ERROR; } const char *janus_attribute_to_string(janus_attribute attribute) { switch (attribute) { ENUM_CASE(INVALID_ATTRIBUTE) ENUM_CASE(FRAME) ENUM_CASE(RIGHT_EYE_X) ENUM_CASE(RIGHT_EYE_Y) ENUM_CASE(LEFT_EYE_X) ENUM_CASE(LEFT_EYE_Y) ENUM_CASE(NOSE_BASE_X) ENUM_CASE(NOSE_BASE_Y) ENUM_CASE(NUM_ATTRIBUTES) } return "INVALID_ATTRIBUTE"; } janus_attribute janus_attribute_from_string(const char *attribute) { ENUM_COMPARE(INVALID_ATTRIBUTE, attribute) ENUM_COMPARE(FRAME, attribute) ENUM_COMPARE(RIGHT_EYE_X, attribute) ENUM_COMPARE(RIGHT_EYE_Y, attribute) ENUM_COMPARE(LEFT_EYE_X, attribute) ENUM_COMPARE(LEFT_EYE_Y, attribute) ENUM_COMPARE(NOSE_BASE_X, attribute) ENUM_COMPARE(NOSE_BASE_Y, attribute) ENUM_COMPARE(NUM_ATTRIBUTES, attribute) return JANUS_INVALID_ATTRIBUTE; } struct TemplateIterator { vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; size_t i; bool verbose; TemplateIterator(janus_metadata metadata, bool verbose) : i(0), verbose(verbose) { ifstream file(metadata); // Parse header string line; getline(file, line); istringstream attributeNames(line); string attributeName; getline(attributeNames, attributeName, ','); // TEMPLATE_ID getline(attributeNames, attributeName, ','); // FILE_NAME vector<janus_attribute> attributes; while (getline(attributeNames, attributeName, ',')) attributes.push_back(janus_attribute_from_string(attributeName.c_str())); // Parse rows while (getline(file, line)) { istringstream attributeValues(line); string templateID, fileName, attributeValue; getline(attributeValues, templateID, ','); getline(attributeValues, fileName, ','); templateIDs.push_back(atoi(templateID.c_str())); fileNames.push_back(fileName); // Construct attribute list, removing missing fields janus_attribute_list attributeList; attributeList.size = 0; attributeList.attributes = new janus_attribute[attributes.size()]; attributeList.values = new double[attributes.size()]; for (int j=2; getline(attributeValues, attributeValue, ','); j++) { if (attributeValue.empty()) continue; attributeList.attributes[attributeList.size] = attributes[j]; attributeList.values[attributeList.size] = atof(attributeValue.c_str()); attributeList.size++; } attributeLists.push_back(attributeList); } if (verbose) fprintf(stderr, "\rEnrolling %zu/%zu", i, attributeLists.size()); } janus_error next(janus_template *template_, janus_template_id *templateID) { if (i >= attributeLists.size()) { *template_ = NULL; *templateID = -1; } else { *templateID = templateIDs[i]; JANUS_CHECK(janus_initialize_template(template_)) while ((i < attributeLists.size()) && (templateIDs[i] == *templateID)) { janus_image image; JANUS_CHECK(janus_read_image(fileNames[i].c_str(), &image)) JANUS_CHECK(janus_augment(image, attributeLists[i], *template_)); janus_free_image(image); i++; if (verbose) fprintf(stderr, "\rEnrolling %zu/%zu", i, attributeLists.size()); } } return JANUS_SUCCESS; } }; janus_error janus_create_template(janus_metadata metadata, janus_template *template_, janus_template_id *template_id) { TemplateIterator ti(metadata, false); return ti.next(template_, template_id); } janus_error janus_create_gallery(janus_metadata metadata, janus_gallery gallery) { TemplateIterator ti(metadata, true); janus_template template_; janus_template_id templateID; JANUS_CHECK(ti.next(&template_, &templateID)) while (template_ != NULL) { JANUS_CHECK(janus_enroll(template_, templateID, gallery)) JANUS_CHECK(ti.next(&template_, &templateID)) } return JANUS_SUCCESS; } struct FlatTemplate { struct Data { janus_flat_template flat_template; size_t bytes, ref_count; janus_error error; } *data; FlatTemplate(janus_template template_) { data = new Data(); data->flat_template = new janus_data[janus_max_template_size()]; data->ref_count = 1; data->error = janus_finalize_template(template_, data->flat_template, &data->bytes); } FlatTemplate(const FlatTemplate& other) { *this = other; } FlatTemplate& operator=(const FlatTemplate& rhs) { data = rhs.data; data->ref_count++; return *this; } ~FlatTemplate() { data->ref_count--; if (data->ref_count == 0) { delete data->flat_template; delete data; } } janus_error compareTo(const FlatTemplate &other, float *similarity) const { double score; return janus_verify(data->flat_template, data->bytes, other.data->flat_template, other.data->bytes, &score); *similarity = score; } }; static void writeMat(void *data, int rows, int columns, bool isMask, janus_metadata target, janus_metadata query, const char *matrix) { ofstream stream(matrix); stream << "S2\n" << target << '\n' << query << '\n' << 'M' << (isMask ? 'B' : 'F') << ' ' << rows << ' ' << columns << ' '; int endian = 0x12345678; stream.write((const char*)&endian, 4); stream << '\n'; stream.write((const char*)data, rows * columns * (isMask ? 1 : 4)); } static vector<janus_template_id> getTemplateIDs(janus_metadata metadata) { vector<janus_template_id> templateIDs; TemplateIterator ti(metadata, false); for (size_t i=0; i<ti.templateIDs.size(); i++) if ((i == 0) || (templateIDs.back() != ti.templateIDs[i])) templateIDs.push_back(ti.templateIDs[i]); return templateIDs; } janus_error janus_create_mask(janus_metadata target_metadata, janus_metadata query_metadata, janus_matrix mask) { vector<janus_template_id> target = getTemplateIDs(target_metadata); vector<janus_template_id> query = getTemplateIDs(query_metadata); unsigned char *truth = new unsigned char[target.size() * query.size()]; for (size_t i=0; i<query.size(); i++) for (size_t j=0; j<target.size(); j++) truth[i*target.size()+j] = (query[i] == target[j] ? 0xff : 0x7f); writeMat(truth, query.size(), target.size(), true, target_metadata, query_metadata, mask); delete[] truth; return JANUS_SUCCESS; } static janus_error getFlatTemplates(janus_metadata metadata, vector<FlatTemplate> &flatTemplates) { TemplateIterator ti(metadata, true); janus_template template_; janus_template_id templateID; JANUS_CHECK(ti.next(&template_, &templateID)) while (template_ != NULL) { flatTemplates.push_back(template_); JANUS_CHECK(flatTemplates.back().data->error) JANUS_CHECK(ti.next(&template_, &templateID)) } return JANUS_SUCCESS; } janus_error janus_create_simmat(janus_metadata target_metadata, janus_metadata query_metadata, janus_matrix simmat) { vector<FlatTemplate> target, query; JANUS_CHECK(getFlatTemplates(target_metadata, target)) JANUS_CHECK(getFlatTemplates(query_metadata, query)) float *scores = new float[target.size() * query.size()]; for (size_t i=0; i<query.size(); i++) for (size_t j=0; j<target.size(); j++) JANUS_CHECK(query[i].compareTo(target[j], &scores[i*target.size()+j])); writeMat(scores, query.size(), target.size(), false, target_metadata, query_metadata, simmat); delete[] scores; return JANUS_SUCCESS; } <commit_msg>parsing bug fixes<commit_after>// These file is designed to have no dependencies outside the C++ Standard Library #include <algorithm> #include <fstream> #include <iostream> #include <limits> #include <map> #include <string> #include <sstream> #include <vector> #include "janus_io.h" using namespace std; #define ENUM_CASE(X) case JANUS_##X: return #X; #define ENUM_COMPARE(X,Y) if (!strcmp(#X, Y)) return JANUS_##X; const char *janus_error_to_string(janus_error error) { switch (error) { ENUM_CASE(SUCCESS) ENUM_CASE(UNKNOWN_ERROR) ENUM_CASE(OUT_OF_MEMORY) ENUM_CASE(INVALID_SDK_PATH) ENUM_CASE(OPEN_ERROR) ENUM_CASE(READ_ERROR) ENUM_CASE(WRITE_ERROR) ENUM_CASE(PARSE_ERROR) ENUM_CASE(INVALID_IMAGE) ENUM_CASE(INVALID_VIDEO) ENUM_CASE(MISSING_TEMPLATE_ID) ENUM_CASE(MISSING_FILE_NAME) ENUM_CASE(NULL_ATTRIBUTE_LIST) ENUM_CASE(NUM_ERRORS) } return "UNKNOWN_ERROR"; } janus_error janus_error_from_string(const char *error) { ENUM_COMPARE(SUCCESS, error) ENUM_COMPARE(UNKNOWN_ERROR, error) ENUM_COMPARE(OUT_OF_MEMORY, error) ENUM_COMPARE(INVALID_SDK_PATH, error) ENUM_COMPARE(OPEN_ERROR, error) ENUM_COMPARE(READ_ERROR, error) ENUM_COMPARE(WRITE_ERROR, error) ENUM_COMPARE(PARSE_ERROR, error) ENUM_COMPARE(INVALID_IMAGE, error) ENUM_COMPARE(INVALID_VIDEO, error) ENUM_COMPARE(MISSING_TEMPLATE_ID, error) ENUM_COMPARE(MISSING_FILE_NAME, error) ENUM_COMPARE(NULL_ATTRIBUTE_LIST, error) ENUM_COMPARE(NUM_ERRORS, error) return JANUS_UNKNOWN_ERROR; } const char *janus_attribute_to_string(janus_attribute attribute) { switch (attribute) { ENUM_CASE(INVALID_ATTRIBUTE) ENUM_CASE(FRAME) ENUM_CASE(RIGHT_EYE_X) ENUM_CASE(RIGHT_EYE_Y) ENUM_CASE(LEFT_EYE_X) ENUM_CASE(LEFT_EYE_Y) ENUM_CASE(NOSE_BASE_X) ENUM_CASE(NOSE_BASE_Y) ENUM_CASE(NUM_ATTRIBUTES) } return "INVALID_ATTRIBUTE"; } janus_attribute janus_attribute_from_string(const char *attribute) { ENUM_COMPARE(INVALID_ATTRIBUTE, attribute) ENUM_COMPARE(FRAME, attribute) ENUM_COMPARE(RIGHT_EYE_X, attribute) ENUM_COMPARE(RIGHT_EYE_Y, attribute) ENUM_COMPARE(LEFT_EYE_X, attribute) ENUM_COMPARE(LEFT_EYE_Y, attribute) ENUM_COMPARE(NOSE_BASE_X, attribute) ENUM_COMPARE(NOSE_BASE_Y, attribute) ENUM_COMPARE(NUM_ATTRIBUTES, attribute) return JANUS_INVALID_ATTRIBUTE; } struct TemplateIterator { vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; size_t i; bool verbose; TemplateIterator(janus_metadata metadata, bool verbose) : i(0), verbose(verbose) { ifstream file(metadata); // Parse header string line; getline(file, line); istringstream attributeNames(line); string attributeName; getline(attributeNames, attributeName, ','); // TEMPLATE_ID getline(attributeNames, attributeName, ','); // FILE_NAME vector<janus_attribute> attributes; while (getline(attributeNames, attributeName, ',')) { attributeName.erase(remove_if(attributeName.begin(), attributeName.end(), ::isspace), attributeName.end()); attributes.push_back(janus_attribute_from_string(attributeName.c_str())); } // Parse rows while (getline(file, line)) { istringstream attributeValues(line); string templateID, fileName, attributeValue; getline(attributeValues, templateID, ','); getline(attributeValues, fileName, ','); templateIDs.push_back(atoi(templateID.c_str())); fileNames.push_back(fileName); // Construct attribute list, removing missing fields janus_attribute_list attributeList; attributeList.size = 0; attributeList.attributes = new janus_attribute[attributes.size()]; attributeList.values = new double[attributes.size()]; for (int j=0; getline(attributeValues, attributeValue, ','); j++) { if (attributeValue.empty()) continue; attributeList.attributes[attributeList.size] = attributes[j]; attributeList.values[attributeList.size] = atof(attributeValue.c_str()); attributeList.size++; } attributeLists.push_back(attributeList); } if (verbose) fprintf(stderr, "\rEnrolling %zu/%zu", i, attributeLists.size()); } janus_error next(janus_template *template_, janus_template_id *templateID) { if (i >= attributeLists.size()) { *template_ = NULL; *templateID = -1; } else { *templateID = templateIDs[i]; JANUS_CHECK(janus_initialize_template(template_)) while ((i < attributeLists.size()) && (templateIDs[i] == *templateID)) { janus_image image; JANUS_CHECK(janus_read_image(fileNames[i].c_str(), &image)) JANUS_CHECK(janus_augment(image, attributeLists[i], *template_)); janus_free_image(image); i++; if (verbose) fprintf(stderr, "\rEnrolling %zu/%zu", i, attributeLists.size()); } } return JANUS_SUCCESS; } }; janus_error janus_create_template(janus_metadata metadata, janus_template *template_, janus_template_id *template_id) { TemplateIterator ti(metadata, false); return ti.next(template_, template_id); } janus_error janus_create_gallery(janus_metadata metadata, janus_gallery gallery) { TemplateIterator ti(metadata, true); janus_template template_; janus_template_id templateID; JANUS_CHECK(ti.next(&template_, &templateID)) while (template_ != NULL) { JANUS_CHECK(janus_enroll(template_, templateID, gallery)) JANUS_CHECK(ti.next(&template_, &templateID)) } return JANUS_SUCCESS; } struct FlatTemplate { struct Data { janus_flat_template flat_template; size_t bytes, ref_count; janus_error error; } *data; FlatTemplate(janus_template template_) { data = new Data(); data->flat_template = new janus_data[janus_max_template_size()]; data->ref_count = 1; data->error = janus_finalize_template(template_, data->flat_template, &data->bytes); } FlatTemplate(const FlatTemplate& other) { *this = other; } FlatTemplate& operator=(const FlatTemplate& rhs) { data = rhs.data; data->ref_count++; return *this; } ~FlatTemplate() { data->ref_count--; if (data->ref_count == 0) { delete data->flat_template; delete data; } } janus_error compareTo(const FlatTemplate &other, float *similarity) const { double score; return janus_verify(data->flat_template, data->bytes, other.data->flat_template, other.data->bytes, &score); *similarity = score; } }; static void writeMat(void *data, int rows, int columns, bool isMask, janus_metadata target, janus_metadata query, const char *matrix) { ofstream stream(matrix); stream << "S2\n" << target << '\n' << query << '\n' << 'M' << (isMask ? 'B' : 'F') << ' ' << rows << ' ' << columns << ' '; int endian = 0x12345678; stream.write((const char*)&endian, 4); stream << '\n'; stream.write((const char*)data, rows * columns * (isMask ? 1 : 4)); } static vector<janus_template_id> getTemplateIDs(janus_metadata metadata) { vector<janus_template_id> templateIDs; TemplateIterator ti(metadata, false); for (size_t i=0; i<ti.templateIDs.size(); i++) if ((i == 0) || (templateIDs.back() != ti.templateIDs[i])) templateIDs.push_back(ti.templateIDs[i]); return templateIDs; } janus_error janus_create_mask(janus_metadata target_metadata, janus_metadata query_metadata, janus_matrix mask) { vector<janus_template_id> target = getTemplateIDs(target_metadata); vector<janus_template_id> query = getTemplateIDs(query_metadata); unsigned char *truth = new unsigned char[target.size() * query.size()]; for (size_t i=0; i<query.size(); i++) for (size_t j=0; j<target.size(); j++) truth[i*target.size()+j] = (query[i] == target[j] ? 0xff : 0x7f); writeMat(truth, query.size(), target.size(), true, target_metadata, query_metadata, mask); delete[] truth; return JANUS_SUCCESS; } static janus_error getFlatTemplates(janus_metadata metadata, vector<FlatTemplate> &flatTemplates) { TemplateIterator ti(metadata, true); janus_template template_; janus_template_id templateID; JANUS_CHECK(ti.next(&template_, &templateID)) while (template_ != NULL) { flatTemplates.push_back(template_); JANUS_CHECK(flatTemplates.back().data->error) JANUS_CHECK(ti.next(&template_, &templateID)) } return JANUS_SUCCESS; } janus_error janus_create_simmat(janus_metadata target_metadata, janus_metadata query_metadata, janus_matrix simmat) { vector<FlatTemplate> target, query; JANUS_CHECK(getFlatTemplates(target_metadata, target)) JANUS_CHECK(getFlatTemplates(query_metadata, query)) float *scores = new float[target.size() * query.size()]; for (size_t i=0; i<query.size(); i++) for (size_t j=0; j<target.size(); j++) JANUS_CHECK(query[i].compareTo(target[j], &scores[i*target.size()+j])); writeMat(scores, query.size(), target.size(), false, target_metadata, query_metadata, simmat); delete[] scores; return JANUS_SUCCESS; } <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <limits> #include <string> #include <sstream> #include <vector> #include "janus_io.h" using namespace std; // These functions have no external dependencies vector<string> split(const string &str, char delim) { vector<string> elems; stringstream ss(str); string item; while (getline(ss, item, delim)) elems.push_back(item); return elems; } vector<janus_attribute> attributesFromStrings(const vector<string> &strings, int *templateIDIndex, int *fileNameIndex) { vector<janus_attribute> attributes; for (size_t i=0; i<strings.size(); i++) { const string &str = strings[i]; if (str == "Template_ID") *templateIDIndex = i; else if (str == "File_Name") *fileNameIndex = i; else if (str == "Frame") attributes.push_back(JANUS_FRAME); else if (str == "Right_Eye_X") attributes.push_back(JANUS_RIGHT_EYE_X); else if (str == "Right_Eye_Y") attributes.push_back(JANUS_RIGHT_EYE_Y); else if (str == "Left_Eye_X") attributes.push_back(JANUS_LEFT_EYE_X); else if (str == "Left_Eye_Y") attributes.push_back(JANUS_LEFT_EYE_Y); else if (str == "Nose_Base_X") attributes.push_back(JANUS_NOSE_BASE_X); else if (str == "Nose_Base_Y") attributes.push_back(JANUS_NOSE_BASE_Y); else attributes.push_back(JANUS_INVALID_ATTRIBUTE); } return attributes; } vector<float> valuesFromStrings(const vector<string> &strings, size_t templateIDIndex, size_t fileNameIndex) { vector<float> values; for (size_t i=0; i<strings.size(); i++) { if ((i == templateIDIndex) || (i == fileNameIndex)) continue; const string &str = strings[i]; if (str.empty()) values.push_back(numeric_limits<float>::quiet_NaN()); else values.push_back(atof(str.c_str())); } return values; } janus_error janus_enroll_template(const char *metadata_file, janus_template template_, size_t *bytes) { // Open file ifstream file(metadata_file); if (!file.is_open()) return JANUS_OPEN_ERROR; // Parse header string line; getline(file, line); int templateIDIndex = -1, fileNameIndex = -1; vector<janus_attribute> attributes = attributesFromStrings(split(line, ','), &templateIDIndex, &fileNameIndex); if (templateIDIndex == -1) return JANUS_MISSING_TEMPLATE_ID; if (fileNameIndex == -1) return JANUS_MISSING_FILE_NAME; // Parse rows janus_template_id template_id; vector<string> fileNames; vector<janus_attribute_list> attributeLists; while (getline(file, line)) { const vector<string> words = split(line, ','); // Make sure all files have the same template ID if (fileNames.empty()) { template_id = atoi(words[templateIDIndex].c_str()); } else { if (atoi(words[templateIDIndex].c_str()) != template_id) return JANUS_TEMPLATE_ID_MISMATCH; } fileNames.push_back(words[fileNameIndex]); vector<float> values = valuesFromStrings(words, templateIDIndex, fileNameIndex); if (values.size() != attributes.size()) return JANUS_PARSE_ERROR; const size_t n = attributes.size(); // Construct attribute list, removing missing fields janus_attribute_list attributeList; attributeList.size = 0; attributeList.attributes = new janus_attribute[n]; attributeList.values = new float[n]; for (size_t i=0; i<n; i++) { if (values[i] != values[i]) /* NaN */ continue; attributeList.attributes[attributeList.size] = attributes[i]; attributeList.values[attributeList.size] = values[i]; attributeList.size++; } attributeLists.push_back(attributeList); } janus_incomplete_template incomplete_template; JANUS_TRY(janus_initialize_template(&incomplete_template)) for (size_t i=0; i<fileNames.size(); i++) { janus_image image; JANUS_TRY(janus_read_image(fileNames[i].c_str(), &image)) JANUS_TRY(janus_add_image(image, attributeLists[i], incomplete_template)); janus_free_image(image); } JANUS_TRY(janus_finalize_template(incomplete_template, template_, bytes)); return JANUS_SUCCESS; } janus_error janus_enroll_gallery(const char *metadata_file, const char *gallery_file) { (void) metadata_file; (void) gallery_file; return JANUS_SUCCESS; } <commit_msg>factored out common metadata parsing code<commit_after>#include <fstream> #include <iostream> #include <limits> #include <string> #include <sstream> #include <vector> #include "janus_io.h" using namespace std; // These functions have no external dependencies vector<string> split(const string &str, char delim) { vector<string> elems; stringstream ss(str); string item; while (getline(ss, item, delim)) elems.push_back(item); return elems; } vector<janus_attribute> attributesFromStrings(const vector<string> &strings, int *templateIDIndex, int *fileNameIndex) { vector<janus_attribute> attributes; for (size_t i=0; i<strings.size(); i++) { const string &str = strings[i]; if (str == "Template_ID") *templateIDIndex = i; else if (str == "File_Name") *fileNameIndex = i; else if (str == "Frame") attributes.push_back(JANUS_FRAME); else if (str == "Right_Eye_X") attributes.push_back(JANUS_RIGHT_EYE_X); else if (str == "Right_Eye_Y") attributes.push_back(JANUS_RIGHT_EYE_Y); else if (str == "Left_Eye_X") attributes.push_back(JANUS_LEFT_EYE_X); else if (str == "Left_Eye_Y") attributes.push_back(JANUS_LEFT_EYE_Y); else if (str == "Nose_Base_X") attributes.push_back(JANUS_NOSE_BASE_X); else if (str == "Nose_Base_Y") attributes.push_back(JANUS_NOSE_BASE_Y); else attributes.push_back(JANUS_INVALID_ATTRIBUTE); } return attributes; } vector<float> valuesFromStrings(const vector<string> &strings, size_t templateIDIndex, size_t fileNameIndex) { vector<float> values; for (size_t i=0; i<strings.size(); i++) { if ((i == templateIDIndex) || (i == fileNameIndex)) continue; const string &str = strings[i]; if (str.empty()) values.push_back(numeric_limits<float>::quiet_NaN()); else values.push_back(atof(str.c_str())); } return values; } janus_error readMetadataFile(const char *metadata_file, vector<string> &fileNames, vector<janus_template_id> &templateIDs, vector<janus_attribute_list> &attributeLists) { // Open file ifstream file(metadata_file); if (!file.is_open()) return JANUS_OPEN_ERROR; // Parse header string line; getline(file, line); int templateIDIndex = -1, fileNameIndex = -1; vector<janus_attribute> attributes = attributesFromStrings(split(line, ','), &templateIDIndex, &fileNameIndex); if (templateIDIndex == -1) return JANUS_MISSING_TEMPLATE_ID; if (fileNameIndex == -1) return JANUS_MISSING_FILE_NAME; // Parse rows while (getline(file, line)) { const vector<string> words = split(line, ','); // Make sure all files have the same template ID fileNames.push_back(words[fileNameIndex]); templateIDs.push_back(atoi(words[templateIDIndex].c_str())); vector<float> values = valuesFromStrings(words, templateIDIndex, fileNameIndex); if (values.size() != attributes.size()) return JANUS_PARSE_ERROR; const size_t n = attributes.size(); // Construct attribute list, removing missing fields janus_attribute_list attributeList; attributeList.size = 0; attributeList.attributes = new janus_attribute[n]; attributeList.values = new float[n]; for (size_t i=0; i<n; i++) { if (values[i] != values[i]) /* NaN */ continue; attributeList.attributes[attributeList.size] = attributes[i]; attributeList.values[attributeList.size] = values[i]; attributeList.size++; } attributeLists.push_back(attributeList); } file.close(); return JANUS_SUCCESS; } janus_error janus_enroll_template(const char *metadata_file, janus_template template_, size_t *bytes) { vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; janus_error error = readMetadataFile(metadata_file, fileNames, templateIDs, attributeLists); if (error != JANUS_SUCCESS) return error; for (size_t i=1; i<templateIDs.size(); i++) if (templateIDs[i] != templateIDs[0]) return JANUS_TEMPLATE_ID_MISMATCH; janus_incomplete_template incomplete_template; JANUS_TRY(janus_initialize_template(&incomplete_template)) for (size_t i=0; i<fileNames.size(); i++) { janus_image image; JANUS_TRY(janus_read_image(fileNames[i].c_str(), &image)) JANUS_TRY(janus_add_image(image, attributeLists[i], incomplete_template)); janus_free_image(image); } JANUS_TRY(janus_finalize_template(incomplete_template, template_, bytes)); return JANUS_SUCCESS; } janus_error janus_enroll_gallery(const char *metadata_file, const char *gallery_file) { vector<string> fileNames; vector<janus_template_id> templateIDs; vector<janus_attribute_list> attributeLists; janus_error error = readMetadataFile(metadata_file, fileNames, templateIDs, attributeLists); if (error != JANUS_SUCCESS) return error; (void) gallery_file; return JANUS_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2012 Plenluno All rights reserved. #include <libj/js_array.h> #include <libj/detail/js_array.h> namespace libj { JsArray::Ptr JsArray::create() { return Ptr(new detail::JsArray<JsArray>()); } JsArray::Ptr JsArray::create(ArrayList::CPtr list) { if (!list) return null(); JsArray::Ptr ary(JsArray::create()); ary->addAll(list); return ary; } } // namespace libj <commit_msg>use '='<commit_after>// Copyright (c) 2012 Plenluno All rights reserved. #include <libj/js_array.h> #include <libj/detail/js_array.h> namespace libj { JsArray::Ptr JsArray::create() { return Ptr(new detail::JsArray<JsArray>()); } JsArray::Ptr JsArray::create(ArrayList::CPtr list) { if (!list) return null(); JsArray::Ptr ary = JsArray::create(); ary->addAll(list); return ary; } } // namespace libj <|endoftext|>
<commit_before>#pragma once #include <karl/karl.hpp> #include <karl/config.hpp> #include <karl/api/api_server.hpp> #include <supermarx/api/session_operations.hpp> #include <boost/program_options.hpp> namespace supermarx { class cli { private: struct cli_options { std::string config; bool no_perms; std::string action; }; static int read_options(cli_options& opt, int argc, char** argv) { boost::program_options::options_description o_general("Options"); o_general.add_options() ("help,h", "display this message") ("config,C", boost::program_options::value(&opt.config), "path to the configfile (default: ./config.yaml)") ("no-perms,n", "do not check permissions"); boost::program_options::variables_map vm; boost::program_options::positional_options_description pos; pos.add("action", 1); boost::program_options::options_description options("Allowed options"); options.add(o_general); options.add_options() ("action", boost::program_options::value(&opt.action)); try { boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).positional(pos).run(), vm); } catch(boost::program_options::unknown_option &e) { std::cerr << "Unknown option --" << e.get_option_name() << ", see --help." << std::endl; return EXIT_FAILURE; } try { boost::program_options::notify(vm); } catch(const boost::program_options::required_option &e) { std::cerr << "You forgot this: " << e.what() << std::endl; return EXIT_FAILURE; } if(vm.count("help")) { std::cout << "SuperMarx core daemon Karl. [https://github.com/SuperMarx/karl]" << std::endl << "Usage: ./karl [options] action" << std::endl << std::endl << "Actions:" << std::endl << " create-user create an user" << std::endl << " server [-n] serve the REST API server via fastcgi" << std::endl << " use a wrapper like `spawn-fcgi`" << std::endl << std::endl << o_general; return EXIT_FAILURE; } if(!vm.count("action")) { std::cerr << "Please specify an action, see --help." << std::endl; return EXIT_FAILURE; } if(!vm.count("config")) opt.config = "./config.yaml"; opt.no_perms = vm.count("no-perms"); return EXIT_SUCCESS; } public: cli() = delete; static int exec(int argc, char** argv) { cli_options opt; int result = read_options(opt, argc, argv); if(result != EXIT_SUCCESS) return result; supermarx::config c(opt.config); supermarx::karl karl(c.db_host, c.db_user, c.db_password, c.db_database, c.ic_path, !opt.no_perms); if(opt.action == "server") { supermarx::api_server as(karl); as.run(); } else if(opt.action == "create-user") { std::string username, password; while(username == "") { std::cerr << "Username: "; std::getline(std::cin, username); } std::cerr << "Password (leave blank for autogen): "; std::getline(std::cin, password); bool autogen_password = (password == ""); if(autogen_password) password = to_string(api::random_token()); karl.create_user(username, password); if(autogen_password) std::cerr << std::endl << "Use the following password:" << std::endl << password << std::endl << std::endl; } else if(opt.action == "test") { karl.test(); } else { std::cerr << "Unknown action '" << opt.action << "', see --help." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } }; } <commit_msg>Added missing iostream<commit_after>#pragma once #include <iostream> #include <karl/karl.hpp> #include <karl/config.hpp> #include <karl/api/api_server.hpp> #include <supermarx/api/session_operations.hpp> #include <boost/program_options.hpp> namespace supermarx { class cli { private: struct cli_options { std::string config; bool no_perms; std::string action; }; static int read_options(cli_options& opt, int argc, char** argv) { boost::program_options::options_description o_general("Options"); o_general.add_options() ("help,h", "display this message") ("config,C", boost::program_options::value(&opt.config), "path to the configfile (default: ./config.yaml)") ("no-perms,n", "do not check permissions"); boost::program_options::variables_map vm; boost::program_options::positional_options_description pos; pos.add("action", 1); boost::program_options::options_description options("Allowed options"); options.add(o_general); options.add_options() ("action", boost::program_options::value(&opt.action)); try { boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(options).positional(pos).run(), vm); } catch(boost::program_options::unknown_option &e) { std::cerr << "Unknown option --" << e.get_option_name() << ", see --help." << std::endl; return EXIT_FAILURE; } try { boost::program_options::notify(vm); } catch(const boost::program_options::required_option &e) { std::cerr << "You forgot this: " << e.what() << std::endl; return EXIT_FAILURE; } if(vm.count("help")) { std::cout << "SuperMarx core daemon Karl. [https://github.com/SuperMarx/karl]" << std::endl << "Usage: ./karl [options] action" << std::endl << std::endl << "Actions:" << std::endl << " create-user create an user" << std::endl << " server [-n] serve the REST API server via fastcgi" << std::endl << " use a wrapper like `spawn-fcgi`" << std::endl << std::endl << o_general; return EXIT_FAILURE; } if(!vm.count("action")) { std::cerr << "Please specify an action, see --help." << std::endl; return EXIT_FAILURE; } if(!vm.count("config")) opt.config = "./config.yaml"; opt.no_perms = vm.count("no-perms"); return EXIT_SUCCESS; } public: cli() = delete; static int exec(int argc, char** argv) { cli_options opt; int result = read_options(opt, argc, argv); if(result != EXIT_SUCCESS) return result; supermarx::config c(opt.config); supermarx::karl karl(c.db_host, c.db_user, c.db_password, c.db_database, c.ic_path, !opt.no_perms); if(opt.action == "server") { supermarx::api_server as(karl); as.run(); } else if(opt.action == "create-user") { std::string username, password; while(username == "") { std::cerr << "Username: "; std::getline(std::cin, username); } std::cerr << "Password (leave blank for autogen): "; std::getline(std::cin, password); bool autogen_password = (password == ""); if(autogen_password) password = to_string(api::random_token()); karl.create_user(username, password); if(autogen_password) std::cerr << std::endl << "Use the following password:" << std::endl << password << std::endl << std::endl; } else if(opt.action == "test") { karl.test(); } else { std::cerr << "Unknown action '" << opt.action << "', see --help." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } }; } <|endoftext|>
<commit_before>/* * Copyright 2009 Free Software Foundation, Inc. * Copyright 2010 Kestrel Signal Processing, Inc. * * SPDX-License-Identifier: AGPL-3.0+ * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <iterator> #include "Logger.h" extern "C" { #include <osmocom/core/msgb.h> #include <osmocom/core/talloc.h> #include <osmocom/core/application.h> #include <osmocom/core/utils.h> #include "debug.h" } #define MYCAT 0 int main(int argc, char *argv[]) { struct log_info_cat categories[1]; struct log_info linfo; categories[MYCAT] = { "MYCAT", NULL, "Whatever", LOGL_NOTICE, 1, }; linfo.cat = categories; linfo.num_cat = ARRAY_SIZE(categories); void *tall_ctx = talloc_named_const(NULL, 1, "OsmoTRX context"); msgb_talloc_ctx_init(tall_ctx, 0); osmo_init_logging2(tall_ctx, &linfo); log_set_use_color(osmo_stderr_target, 0); log_set_print_filename(osmo_stderr_target, 0); log_set_print_level(osmo_stderr_target, 1); log_set_print_category(osmo_stderr_target, 0); log_set_print_category_hex(osmo_stderr_target, 0); Log(MYCAT, LOGL_FATAL, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_ERROR, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_NOTICE, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_INFO, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_DEBUG, __BASE_FILE__, __LINE__).get() << "testing the logger."; } <commit_msg>tests: Replace deprecated API log_set_print_filename<commit_after>/* * Copyright 2009 Free Software Foundation, Inc. * Copyright 2010 Kestrel Signal Processing, Inc. * * SPDX-License-Identifier: AGPL-3.0+ * * This software is distributed under the terms of the GNU Affero Public License. * See the COPYING file in the main directory for details. * * This use of this software may be subject to additional restrictions. * See the LEGAL file in the main directory for details. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <iterator> #include "Logger.h" extern "C" { #include <osmocom/core/msgb.h> #include <osmocom/core/talloc.h> #include <osmocom/core/application.h> #include <osmocom/core/utils.h> #include "debug.h" } #define MYCAT 0 int main(int argc, char *argv[]) { struct log_info_cat categories[1]; struct log_info linfo; categories[MYCAT] = { "MYCAT", NULL, "Whatever", LOGL_NOTICE, 1, }; linfo.cat = categories; linfo.num_cat = ARRAY_SIZE(categories); void *tall_ctx = talloc_named_const(NULL, 1, "OsmoTRX context"); msgb_talloc_ctx_init(tall_ctx, 0); osmo_init_logging2(tall_ctx, &linfo); log_set_use_color(osmo_stderr_target, 0); log_set_print_filename2(osmo_stderr_target, LOG_FILENAME_NONE); log_set_print_level(osmo_stderr_target, 1); log_set_print_category(osmo_stderr_target, 0); log_set_print_category_hex(osmo_stderr_target, 0); Log(MYCAT, LOGL_FATAL, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_ERROR, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_NOTICE, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_INFO, __BASE_FILE__, __LINE__).get() << "testing the logger."; Log(MYCAT, LOGL_DEBUG, __BASE_FILE__, __LINE__).get() << "testing the logger."; } <|endoftext|>
<commit_before>#include "launcher.hpp" #include <dirent.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <pwd.h> #include <iostream> #include <sstream> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <boost/lexical_cast.hpp> #include "foreach.hpp" using std::cerr; using std::cout; using std::endl; using std::ostringstream; using std::string; using std::vector; using boost::lexical_cast; using namespace nexus; using namespace nexus::internal; using namespace nexus::internal::launcher; ExecutorLauncher::ExecutorLauncher(FrameworkID _frameworkId, const string& _executorUri, const string& _user, const string& _workDirectory, const string& _slavePid, bool _redirectIO) : frameworkId(_frameworkId), executorUri(_executorUri), user(_user), workDirectory(_workDirectory), slavePid(_slavePid), redirectIO(_redirectIO) {} ExecutorLauncher::~ExecutorLauncher() { } void ExecutorLauncher::run() { createWorkingDirectory(); // Enter working directory if (chdir(workDirectory.c_str()) < 0) fatalerror("chdir into framework working directory failed"); // Redirect output to files in working dir if required if (redirectIO) { if (freopen("stdout", "w", stdout) == NULL) fatalerror("freopen failed"); if (freopen("stderr", "w", stderr) == NULL) fatalerror("freopen failed"); } string executor = fetchExecutor(); setupEnvironment(); switchUser(); // Execute the executor execl(executor.c_str(), executor.c_str(), (char *) NULL); // If we get here, the execl call failed fatalerror("Could not execute %s", executor.c_str()); } // Create the executor's working directory and return its path. void ExecutorLauncher::createWorkingDirectory() { // Split the path into tokens by "/" and make each directory vector<string> tokens; split(workDirectory, "/", &tokens); string dir; foreach (const string& token, tokens) { if (dir != "") dir += "/"; dir += token; if (mkdir(dir.c_str(), 0755) < 0 && errno != EEXIST) fatalerror("mkdir failed"); } // TODO: chown the final directory to the framework's user } // Download the executor's binary if required and return its path. string ExecutorLauncher::fetchExecutor() { string executor = executorUri; // Some checks to make using the executor in shell commands safe; // these should be pushed into the master and reported to the user if (executor.find_first_of('\\') != string::npos || executor.find_first_of('\'') != string::npos || executor.find_first_of('\0') != string::npos) { fatal("Illegal characters in executor path"); } // Grab the executor from HDFS if its path begins with hdfs:// // TODO: Enforce some size limits on files we get from HDFS if (executor.find("hdfs://") == 0) { const char *hadoop = getenv("HADOOP"); if (!hadoop) { fatal("Cannot download executor from HDFS because the " "HADOOP environment variable is not set"); } string localFile = string("./") + basename((char *) executor.c_str()); ostringstream command; command << hadoop << " fs -copyToLocal '" << executor << "' '" << localFile << "'"; cout << "Downloading executor from " << executor << endl; cout << "HDFS command: " << command.str() << endl; int ret = system(command.str().c_str()); if (ret != 0) fatal("HDFS copyToLocal failed: return code %d", ret); executor = localFile; } // If the executor was a .tgz, untar it in the work directory. The .tgz // expected to contain a single directory. This directory should contain // a program or script called "executor" to run the executor. We chdir // into this directory and run the script from in there. if (executor.rfind(".tgz") == executor.size() - strlen(".tgz")) { string command = "tar xzf '" + executor + "'"; cout << "Untarring executor: " + command << endl; int ret = system(command.c_str()); if (ret != 0) fatal("Untar failed: return code %d", ret); // The .tgz should have contained a single directory; find it if (DIR *dir = opendir(".")) { bool found = false; string dirname = ""; while (struct dirent *ent = readdir(dir)) { if (string(".") != ent->d_name && string("..") != ent->d_name) { struct stat info; if (stat(ent->d_name, &info) == 0) { if (S_ISDIR(info.st_mode)) { if (found) // Already found a directory earlier fatal("Executor .tgz must contain a single directory"); dirname = ent->d_name; found = true; } } else { fatalerror("Stat failed on %s", ent->d_name); } } } if (!found) // No directory found fatal("Executor .tgz must contain a single directory"); if (chdir(dirname.c_str()) < 0) fatalerror("Chdir failed"); executor = "./executor"; } else { fatalerror("Failed to list work directory"); } } return executor; } // Set up environment variables for launching a framework's executor. void ExecutorLauncher::setupEnvironment() { setenv("NEXUS_SLAVE_PID", slavePid.c_str(), true); const string &nexus_framework_id = lexical_cast<string>(frameworkId); setenv("NEXUS_FRAMEWORK_ID", nexus_framework_id.c_str(), true); // Set LIBPROCESS_PORT so that we bind to a random free port. setenv("LIBPROCESS_PORT", "0", true); } void ExecutorLauncher::switchUser() { struct passwd *passwd; if ((passwd = getpwnam(user.c_str())) == NULL) fatal("failed to get username information for %s", user.c_str()); if (setgid(passwd->pw_gid) < 0) fatalerror("failed to setgid"); if (setuid(passwd->pw_uid) < 0) fatalerror("failed to setuid"); } void ExecutorLauncher::split(const string& str, const string& delims, vector<string>* tokens) { // Start and end of current token; initialize these to the first token in // the string, skipping any leading delimiters size_t start = str.find_first_not_of(delims, 0); size_t end = str.find_first_of(delims, start); while (start != string::npos || end != string::npos) { // Add current token to the vector tokens->push_back(str.substr(start, end-start)); // Advance start to first non-delimiter past the current end start = str.find_first_not_of(delims, end); // Advance end to the next delimiter after the new start end = str.find_first_of(delims, start); } } <commit_msg>If no HADOOP in environment, just use 'hadoop'.<commit_after>#include "launcher.hpp" #include <dirent.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <pwd.h> #include <iostream> #include <sstream> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <boost/lexical_cast.hpp> #include "foreach.hpp" using std::cerr; using std::cout; using std::endl; using std::ostringstream; using std::string; using std::vector; using boost::lexical_cast; using namespace nexus; using namespace nexus::internal; using namespace nexus::internal::launcher; ExecutorLauncher::ExecutorLauncher(FrameworkID _frameworkId, const string& _executorUri, const string& _user, const string& _workDirectory, const string& _slavePid, bool _redirectIO) : frameworkId(_frameworkId), executorUri(_executorUri), user(_user), workDirectory(_workDirectory), slavePid(_slavePid), redirectIO(_redirectIO) {} ExecutorLauncher::~ExecutorLauncher() { } void ExecutorLauncher::run() { createWorkingDirectory(); // Enter working directory if (chdir(workDirectory.c_str()) < 0) fatalerror("chdir into framework working directory failed"); // Redirect output to files in working dir if required if (redirectIO) { if (freopen("stdout", "w", stdout) == NULL) fatalerror("freopen failed"); if (freopen("stderr", "w", stderr) == NULL) fatalerror("freopen failed"); } string executor = fetchExecutor(); setupEnvironment(); switchUser(); // Execute the executor execl(executor.c_str(), executor.c_str(), (char *) NULL); // If we get here, the execl call failed fatalerror("Could not execute %s", executor.c_str()); } // Create the executor's working directory and return its path. void ExecutorLauncher::createWorkingDirectory() { // Split the path into tokens by "/" and make each directory vector<string> tokens; split(workDirectory, "/", &tokens); string dir; foreach (const string& token, tokens) { if (dir != "") dir += "/"; dir += token; if (mkdir(dir.c_str(), 0755) < 0 && errno != EEXIST) fatalerror("mkdir failed"); } // TODO: chown the final directory to the framework's user } // Download the executor's binary if required and return its path. string ExecutorLauncher::fetchExecutor() { string executor = executorUri; // Some checks to make using the executor in shell commands safe; // these should be pushed into the master and reported to the user if (executor.find_first_of('\\') != string::npos || executor.find_first_of('\'') != string::npos || executor.find_first_of('\0') != string::npos) { fatal("Illegal characters in executor path"); } // Grab the executor from HDFS if its path begins with hdfs:// // TODO: Enforce some size limits on files we get from HDFS if (executor.find("hdfs://") == 0) { const char *hadoop = getenv("HADOOP"); if (!hadoop) { hadoop = "hadoop"; // fatal("Cannot download executor from HDFS because the " // "HADOOP environment variable is not set"); } string localFile = string("./") + basename((char *) executor.c_str()); ostringstream command; command << hadoop << " fs -copyToLocal '" << executor << "' '" << localFile << "'"; cout << "Downloading executor from " << executor << endl; cout << "HDFS command: " << command.str() << endl; int ret = system(command.str().c_str()); if (ret != 0) fatal("HDFS copyToLocal failed: return code %d", ret); executor = localFile; } // If the executor was a .tgz, untar it in the work directory. The .tgz // expected to contain a single directory. This directory should contain // a program or script called "executor" to run the executor. We chdir // into this directory and run the script from in there. if (executor.rfind(".tgz") == executor.size() - strlen(".tgz")) { string command = "tar xzf '" + executor + "'"; cout << "Untarring executor: " + command << endl; int ret = system(command.c_str()); if (ret != 0) fatal("Untar failed: return code %d", ret); // The .tgz should have contained a single directory; find it if (DIR *dir = opendir(".")) { bool found = false; string dirname = ""; while (struct dirent *ent = readdir(dir)) { if (string(".") != ent->d_name && string("..") != ent->d_name) { struct stat info; if (stat(ent->d_name, &info) == 0) { if (S_ISDIR(info.st_mode)) { if (found) // Already found a directory earlier fatal("Executor .tgz must contain a single directory"); dirname = ent->d_name; found = true; } } else { fatalerror("Stat failed on %s", ent->d_name); } } } if (!found) // No directory found fatal("Executor .tgz must contain a single directory"); if (chdir(dirname.c_str()) < 0) fatalerror("Chdir failed"); executor = "./executor"; } else { fatalerror("Failed to list work directory"); } } return executor; } // Set up environment variables for launching a framework's executor. void ExecutorLauncher::setupEnvironment() { setenv("NEXUS_SLAVE_PID", slavePid.c_str(), true); const string &nexus_framework_id = lexical_cast<string>(frameworkId); setenv("NEXUS_FRAMEWORK_ID", nexus_framework_id.c_str(), true); // Set LIBPROCESS_PORT so that we bind to a random free port. setenv("LIBPROCESS_PORT", "0", true); } void ExecutorLauncher::switchUser() { struct passwd *passwd; if ((passwd = getpwnam(user.c_str())) == NULL) fatal("failed to get username information for %s", user.c_str()); if (setgid(passwd->pw_gid) < 0) fatalerror("failed to setgid"); if (setuid(passwd->pw_uid) < 0) fatalerror("failed to setuid"); } void ExecutorLauncher::split(const string& str, const string& delims, vector<string>* tokens) { // Start and end of current token; initialize these to the first token in // the string, skipping any leading delimiters size_t start = str.find_first_not_of(delims, 0); size_t end = str.find_first_of(delims, start); while (start != string::npos || end != string::npos) { // Add current token to the vector tokens->push_back(str.substr(start, end-start)); // Advance start to first non-delimiter past the current end start = str.find_first_not_of(delims, end); // Advance end to the next delimiter after the new start end = str.find_first_of(delims, start); } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // hash_join_test.cpp // // Identification: tests/executor/hash_join_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/common/types.h" #include "backend/executor/logical_tile.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/hash_join_executor.h" #include "backend/executor/hash_executor.h" #include "backend/executor/merge_join_executor.h" #include "backend/executor/nested_loop_join_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/tuple_value_expression.h" #include "backend/expression/expression_util.h" #include "backend/planner/hash_join_plan.h" #include "backend/planner/hash_plan.h" #include "backend/planner/merge_join_plan.h" #include "backend/planner/nested_loop_join_plan.h" #include "backend/storage/data_table.h" #include "mock_executor.h" #include "executor/executor_tests_util.h" #include "executor/join_tests_util.h" #include "harness.h" using ::testing::NotNull; using ::testing::Return; namespace peloton { namespace test { std::vector<planner::MergeJoinPlan::JoinClause> CreateJoinClauses() { std::vector<planner::MergeJoinPlan::JoinClause> join_clauses; auto left = expression::TupleValueFactory(0, 1); auto right = expression::TupleValueFactory(1, 1); bool reversed = false; join_clauses.emplace_back(left, right, reversed); return join_clauses; } std::vector<PlanNodeType> join_algorithms = { PLAN_NODE_TYPE_NESTLOOP, PLAN_NODE_TYPE_MERGEJOIN, PLAN_NODE_TYPE_HASHJOIN }; std::vector<PelotonJoinType> join_types = { JOIN_TYPE_INNER, JOIN_TYPE_LEFT, JOIN_TYPE_RIGHT, JOIN_TYPE_OUTER }; void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type); TEST(JoinTests, JoinPredicateTest) { // Go over all join algorithms for(auto join_algorithm : join_algorithms) { std::cout << "JOIN ALGORITHM :: " << PlanNodeTypeToString(join_algorithm) << "\n"; // Go over all join types for(auto join_type : join_types) { std::cout << "JOIN TYPE :: " << join_type << "\n"; // Execute the join test ExecuteJoinTest(join_algorithm, join_type); } } } void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type) { //===--------------------------------------------------------------------===// // Mock table scan executors //===--------------------------------------------------------------------===// MockExecutor left_table_scan_executor, right_table_scan_executor; // Create a table and wrap it in logical tile size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP; size_t left_table_tile_group_count = 3; size_t right_table_tile_group_count = 2; // Left table has 3 tile groups std::unique_ptr<storage::DataTable> left_table( ExecutorTestsUtil::CreateTable(tile_group_size)); ExecutorTestsUtil::PopulateTable(left_table.get(), tile_group_size * left_table_tile_group_count, false, false, false); //std::cout << (*left_table); // Right table has 2 tile groups std::unique_ptr<storage::DataTable> right_table( ExecutorTestsUtil::CreateTable(tile_group_size)); ExecutorTestsUtil::PopulateTable(right_table.get(), tile_group_size * right_table_tile_group_count, false, false, false); //std::cout << (*right_table); // Wrap the input tables with logical tiles std::unique_ptr<executor::LogicalTile> left_table_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> left_table_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1))); std::unique_ptr<executor::LogicalTile> left_table_logical_tile3( executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(2))); std::unique_ptr<executor::LogicalTile> right_table_logical_tile1( executor::LogicalTileFactory::WrapTileGroup( right_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> right_table_logical_tile2( executor::LogicalTileFactory::WrapTileGroup( right_table->GetTileGroup(1))); // Left scan executor returns logical tiles from the left table EXPECT_CALL(left_table_scan_executor, DInit()) .WillOnce(Return(true)); EXPECT_CALL(left_table_scan_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_CALL(left_table_scan_executor, GetOutput()) .WillOnce(Return(left_table_logical_tile1.release())) .WillOnce(Return(left_table_logical_tile2.release())) .WillOnce(Return(left_table_logical_tile3.release())); // Right scan executor returns logical tiles from the right table EXPECT_CALL(right_table_scan_executor, DInit()) .WillOnce(Return(true)); EXPECT_CALL(right_table_scan_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_CALL(right_table_scan_executor, GetOutput()) .WillOnce(Return(right_table_logical_tile1.release())) .WillOnce(Return(right_table_logical_tile2.release())); //===--------------------------------------------------------------------===// // Setup join plan nodes and executors and run them //===--------------------------------------------------------------------===// auto result_tuple_count = 0; auto projection = JoinTestsUtil::CreateProjection(); // Construct predicate expression::AbstractExpression *predicate = JoinTestsUtil::CreateJoinPredicate(); // Differ based on join algorithm switch(join_algorithm) { case PLAN_NODE_TYPE_NESTLOOP: { // Create nested loop join plan node. planner::NestedLoopJoinPlan nested_loop_join_node(join_type, predicate, projection); // Run the nested loop join executor executor::NestedLoopJoinExecutor nested_loop_join_executor(&nested_loop_join_node, nullptr); // Construct the executor tree nested_loop_join_executor.AddChild(&left_table_scan_executor); nested_loop_join_executor.AddChild(&right_table_scan_executor); // Run the nested loop join executor EXPECT_TRUE(nested_loop_join_executor.Init()); while(nested_loop_join_executor.Execute() == true) { std::unique_ptr<executor::LogicalTile> result_logical_tile(nested_loop_join_executor.GetOutput()); if(result_logical_tile != nullptr) { result_tuple_count += result_logical_tile->GetTupleCount(); } } } break; case PLAN_NODE_TYPE_MERGEJOIN: { // Create join clauses std::vector<planner::MergeJoinPlan::JoinClause> join_clauses; join_clauses = CreateJoinClauses(); // Create merge join plan node planner::MergeJoinPlan merge_join_node(join_type, predicate, projection, join_clauses); // Construct the merge join executor executor::MergeJoinExecutor merge_join_executor(&merge_join_node, nullptr); // Construct the executor tree merge_join_executor.AddChild(&left_table_scan_executor); merge_join_executor.AddChild(&right_table_scan_executor); // Run the merge join executor EXPECT_TRUE(merge_join_executor.Init()); while(merge_join_executor.Execute() == true) { std::unique_ptr<executor::LogicalTile> result_logical_tile(merge_join_executor.GetOutput()); if(result_logical_tile != nullptr) { result_tuple_count += result_logical_tile->GetTupleCount(); //std::cout << (*result_logical_tile); } } } break; case PLAN_NODE_TYPE_HASHJOIN: { // Create hash plan node expression::AbstractExpression *right_table_attr_1 = new expression::TupleValueExpression(1, 1); std::vector<std::unique_ptr<const expression::AbstractExpression> > hash_keys; hash_keys.emplace_back(right_table_attr_1); // Create hash plan node planner::HashPlan hash_plan_node(hash_keys); // Construct the hash executor executor::HashExecutor hash_executor(&hash_plan_node, nullptr); // Create hash join plan node. planner::HashJoinPlan hash_join_plan_node(join_type, predicate, projection); // Construct the hash join executor executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr); // Construct the executor tree hash_join_executor.AddChild(&left_table_scan_executor); hash_join_executor.AddChild(&hash_executor); hash_executor.AddChild(&right_table_scan_executor); // Run the hash_join_executor EXPECT_TRUE(hash_join_executor.Init()); while(hash_join_executor.Execute() == true) { std::unique_ptr<executor::LogicalTile> result_logical_tile(hash_join_executor.GetOutput()); if(result_logical_tile != nullptr) { result_tuple_count += result_logical_tile->GetTupleCount(); //std::cout << (*result_logical_tile); } } } break; default: throw Exception("Unsupported join algorithm : " + std::to_string(join_algorithm)); break; } //===--------------------------------------------------------------------===// // Execute test //===--------------------------------------------------------------------===// // Check output switch(join_type) { case JOIN_TYPE_INNER: EXPECT_EQ(result_tuple_count, 2 * tile_group_size); break; case JOIN_TYPE_LEFT: EXPECT_EQ(result_tuple_count, 3 * tile_group_size); break; case JOIN_TYPE_RIGHT: EXPECT_EQ(result_tuple_count, 2 * tile_group_size); break; case JOIN_TYPE_OUTER: EXPECT_EQ(result_tuple_count, 3 * tile_group_size); break; default: throw Exception("Unsupported join type : " + std::to_string(join_type)); break; } } } // namespace test } // namespace peloton <commit_msg>Updated the join test<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // hash_join_test.cpp // // Identification: tests/executor/hash_join_test.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "backend/common/types.h" #include "backend/executor/logical_tile.h" #include "backend/executor/logical_tile_factory.h" #include "backend/executor/hash_join_executor.h" #include "backend/executor/hash_executor.h" #include "backend/executor/merge_join_executor.h" #include "backend/executor/nested_loop_join_executor.h" #include "backend/expression/abstract_expression.h" #include "backend/expression/tuple_value_expression.h" #include "backend/expression/expression_util.h" #include "backend/planner/hash_join_plan.h" #include "backend/planner/hash_plan.h" #include "backend/planner/merge_join_plan.h" #include "backend/planner/nested_loop_join_plan.h" #include "backend/storage/data_table.h" #include "mock_executor.h" #include "executor/executor_tests_util.h" #include "executor/join_tests_util.h" #include "harness.h" using ::testing::NotNull; using ::testing::Return; namespace peloton { namespace test { std::vector<planner::MergeJoinPlan::JoinClause> CreateJoinClauses() { std::vector<planner::MergeJoinPlan::JoinClause> join_clauses; auto left = expression::TupleValueFactory(0, 1); auto right = expression::TupleValueFactory(1, 1); bool reversed = false; join_clauses.emplace_back(left, right, reversed); return join_clauses; } std::vector<PlanNodeType> join_algorithms = { PLAN_NODE_TYPE_NESTLOOP, PLAN_NODE_TYPE_MERGEJOIN, PLAN_NODE_TYPE_HASHJOIN }; std::vector<PelotonJoinType> join_types = { JOIN_TYPE_INNER, JOIN_TYPE_LEFT, JOIN_TYPE_RIGHT, JOIN_TYPE_OUTER }; void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type); oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile); TEST(JoinTests, JoinPredicateTest) { // Go over all join algorithms for(auto join_algorithm : join_algorithms) { std::cout << "JOIN ALGORITHM :: " << PlanNodeTypeToString(join_algorithm) << "\n"; // Go over all join types for(auto join_type : join_types) { std::cout << "JOIN TYPE :: " << join_type << "\n"; // Execute the join test ExecuteJoinTest(join_algorithm, join_type); } } } void ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type) { //===--------------------------------------------------------------------===// // Mock table scan executors //===--------------------------------------------------------------------===// MockExecutor left_table_scan_executor, right_table_scan_executor; // Create a table and wrap it in logical tile size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP; size_t left_table_tile_group_count = 3; size_t right_table_tile_group_count = 2; // Left table has 3 tile groups std::unique_ptr<storage::DataTable> left_table( ExecutorTestsUtil::CreateTable(tile_group_size)); ExecutorTestsUtil::PopulateTable(left_table.get(), tile_group_size * left_table_tile_group_count, false, false, false); //std::cout << (*left_table); // Right table has 2 tile groups std::unique_ptr<storage::DataTable> right_table( ExecutorTestsUtil::CreateTable(tile_group_size)); ExecutorTestsUtil::PopulateTable(right_table.get(), tile_group_size * right_table_tile_group_count, false, false, false); //std::cout << (*right_table); // Wrap the input tables with logical tiles std::unique_ptr<executor::LogicalTile> left_table_logical_tile1( executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> left_table_logical_tile2( executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1))); std::unique_ptr<executor::LogicalTile> left_table_logical_tile3( executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(2))); std::unique_ptr<executor::LogicalTile> right_table_logical_tile1( executor::LogicalTileFactory::WrapTileGroup( right_table->GetTileGroup(0))); std::unique_ptr<executor::LogicalTile> right_table_logical_tile2( executor::LogicalTileFactory::WrapTileGroup( right_table->GetTileGroup(1))); // Left scan executor returns logical tiles from the left table EXPECT_CALL(left_table_scan_executor, DInit()) .WillOnce(Return(true)); EXPECT_CALL(left_table_scan_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_CALL(left_table_scan_executor, GetOutput()) .WillOnce(Return(left_table_logical_tile1.release())) .WillOnce(Return(left_table_logical_tile2.release())) .WillOnce(Return(left_table_logical_tile3.release())); // Right scan executor returns logical tiles from the right table EXPECT_CALL(right_table_scan_executor, DInit()) .WillOnce(Return(true)); EXPECT_CALL(right_table_scan_executor, DExecute()) .WillOnce(Return(true)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_CALL(right_table_scan_executor, GetOutput()) .WillOnce(Return(right_table_logical_tile1.release())) .WillOnce(Return(right_table_logical_tile2.release())); //===--------------------------------------------------------------------===// // Setup join plan nodes and executors and run them //===--------------------------------------------------------------------===// oid_t result_tuple_count = 0; oid_t tuples_with_null = 0; auto projection = JoinTestsUtil::CreateProjection(); // Construct predicate expression::AbstractExpression *predicate = JoinTestsUtil::CreateJoinPredicate(); // Differ based on join algorithm switch(join_algorithm) { case PLAN_NODE_TYPE_NESTLOOP: { // Create nested loop join plan node. planner::NestedLoopJoinPlan nested_loop_join_node(join_type, predicate, projection); // Run the nested loop join executor executor::NestedLoopJoinExecutor nested_loop_join_executor(&nested_loop_join_node, nullptr); // Construct the executor tree nested_loop_join_executor.AddChild(&left_table_scan_executor); nested_loop_join_executor.AddChild(&right_table_scan_executor); // Run the nested loop join executor EXPECT_TRUE(nested_loop_join_executor.Init()); while(nested_loop_join_executor.Execute() == true) { std::unique_ptr<executor::LogicalTile> result_logical_tile(nested_loop_join_executor.GetOutput()); if(result_logical_tile != nullptr) { result_tuple_count += result_logical_tile->GetTupleCount(); tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get()); } } } break; case PLAN_NODE_TYPE_MERGEJOIN: { // Create join clauses std::vector<planner::MergeJoinPlan::JoinClause> join_clauses; join_clauses = CreateJoinClauses(); // Create merge join plan node planner::MergeJoinPlan merge_join_node(join_type, predicate, projection, join_clauses); // Construct the merge join executor executor::MergeJoinExecutor merge_join_executor(&merge_join_node, nullptr); // Construct the executor tree merge_join_executor.AddChild(&left_table_scan_executor); merge_join_executor.AddChild(&right_table_scan_executor); // Run the merge join executor EXPECT_TRUE(merge_join_executor.Init()); while(merge_join_executor.Execute() == true) { std::unique_ptr<executor::LogicalTile> result_logical_tile(merge_join_executor.GetOutput()); if(result_logical_tile != nullptr) { result_tuple_count += result_logical_tile->GetTupleCount(); tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get()); //std::cout << (*result_logical_tile); } } } break; case PLAN_NODE_TYPE_HASHJOIN: { // Create hash plan node expression::AbstractExpression *right_table_attr_1 = new expression::TupleValueExpression(1, 1); std::vector<std::unique_ptr<const expression::AbstractExpression> > hash_keys; hash_keys.emplace_back(right_table_attr_1); // Create hash plan node planner::HashPlan hash_plan_node(hash_keys); // Construct the hash executor executor::HashExecutor hash_executor(&hash_plan_node, nullptr); // Create hash join plan node. planner::HashJoinPlan hash_join_plan_node(join_type, predicate, projection); // Construct the hash join executor executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr); // Construct the executor tree hash_join_executor.AddChild(&left_table_scan_executor); hash_join_executor.AddChild(&hash_executor); hash_executor.AddChild(&right_table_scan_executor); // Run the hash_join_executor EXPECT_TRUE(hash_join_executor.Init()); while(hash_join_executor.Execute() == true) { std::unique_ptr<executor::LogicalTile> result_logical_tile(hash_join_executor.GetOutput()); if(result_logical_tile != nullptr) { result_tuple_count += result_logical_tile->GetTupleCount(); tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get()); //std::cout << (*result_logical_tile); } } } break; default: throw Exception("Unsupported join algorithm : " + std::to_string(join_algorithm)); break; } //===--------------------------------------------------------------------===// // Execute test //===--------------------------------------------------------------------===// // Check output switch(join_type) { case JOIN_TYPE_INNER: EXPECT_EQ(result_tuple_count, 2 * tile_group_size); EXPECT_EQ(tuples_with_null, 0 * tile_group_size); break; case JOIN_TYPE_LEFT: EXPECT_EQ(result_tuple_count, 3 * tile_group_size); EXPECT_EQ(tuples_with_null, 1 * tile_group_size); break; case JOIN_TYPE_RIGHT: EXPECT_EQ(result_tuple_count, 2 * tile_group_size); EXPECT_EQ(tuples_with_null, 0 * tile_group_size); break; case JOIN_TYPE_OUTER: EXPECT_EQ(result_tuple_count, 3 * tile_group_size); EXPECT_EQ(tuples_with_null, 1 * tile_group_size); break; default: throw Exception("Unsupported join type : " + std::to_string(join_type)); break; } } oid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile) { assert(logical_tile); // Get column count auto column_count = logical_tile->GetColumnCount(); oid_t tuples_with_null = 0; // Go over the tile for (auto logical_tile_itr : *logical_tile) { const expression::ContainerTuple<executor::LogicalTile> left_tuple( logical_tile, logical_tile_itr); // Go over all the fields and check for null values for(oid_t col_itr = 0; col_itr < column_count; col_itr++) { auto val = left_tuple.GetValue(col_itr); if(val.IsNull()) { tuples_with_null++; break; } } } return tuples_with_null; } } // namespace test } // namespace peloton <|endoftext|>
<commit_before>#include "basewindow.hpp" #include "singletons/settingsmanager.hpp" #include "util/nativeeventhelper.hpp" #include "widgets/tooltipwidget.hpp" #include <QApplication> #include <QDebug> #include <QIcon> #ifdef USEWINSDK #include <dwmapi.h> #include <gdiplus.h> #include <objidl.h> #include <windows.h> #include <windowsx.h> #pragma comment(lib, "Dwmapi.lib") #include <QHBoxLayout> #include <QVBoxLayout> #include "widgets/helper/rippleeffectlabel.hpp" #define WM_DPICHANGED 0x02E0 #endif namespace chatterino { namespace widgets { BaseWindow::BaseWindow(singletons::ThemeManager &_themeManager, QWidget *parent, bool _enableCustomFrame) : BaseWidget(_themeManager, parent, Qt::Window) , enableCustomFrame(_enableCustomFrame) { this->init(); } BaseWindow::BaseWindow(BaseWidget *parent, bool _enableCustomFrame) : BaseWidget(parent, Qt::Window) , enableCustomFrame(_enableCustomFrame) { this->init(); } BaseWindow::BaseWindow(QWidget *parent, bool _enableCustomFrame) : BaseWidget(parent, Qt::Window) , enableCustomFrame(_enableCustomFrame) { this->init(); } void BaseWindow::init() { this->setWindowIcon(QIcon(":/images/icon.png")); #ifdef USEWINSDK if (this->hasCustomWindowFrame()) { // CUSTOM WINDOW FRAME QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(1); this->setLayout(layout); { QHBoxLayout *buttons = this->titlebarBox = new QHBoxLayout; buttons->setMargin(0); layout->addLayout(buttons); // title QLabel *titleLabel = new QLabel("Chatterino"); buttons->addWidget(titleLabel); this->titleLabel = titleLabel; // buttons RippleEffectLabel *min = new RippleEffectLabel; min->getLabel().setText("min"); min->setFixedSize(46, 30); RippleEffectLabel *max = new RippleEffectLabel; max->setFixedSize(46, 30); max->getLabel().setText("max"); RippleEffectLabel *exit = new RippleEffectLabel; exit->setFixedSize(46, 30); exit->getLabel().setText("exit"); this->minButton = min; this->maxButton = max; this->exitButton = exit; this->widgets.push_back(min); this->widgets.push_back(max); this->widgets.push_back(exit); buttons->addStretch(1); buttons->addWidget(min); buttons->addWidget(max); buttons->addWidget(exit); } this->layoutBase = new QWidget(this); this->widgets.push_back(this->layoutBase); layout->addWidget(this->layoutBase); } // DPI auto dpi = util::getWindowDpi(this->winId()); if (dpi) { this->dpiMultiplier = dpi.value() / 96.f; } this->dpiMultiplierChanged(1, this->dpiMultiplier); #endif if (singletons::SettingManager::getInstance().windowTopMost.getValue()) { this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint); } } QWidget *BaseWindow::getLayoutContainer() { if (this->enableCustomFrame) { return this->layoutBase; } else { return this; } } bool BaseWindow::hasCustomWindowFrame() { #ifdef Q_OS_WIN return this->enableCustomFrame; #else return false; #endif } void BaseWindow::refreshTheme() { QPalette palette; palette.setColor(QPalette::Background, this->themeManager.windowBg); palette.setColor(QPalette::Foreground, this->themeManager.windowText); this->setPalette(palette); } void BaseWindow::addTitleBarButton(const QString &text) { RippleEffectLabel *label = new RippleEffectLabel; label->getLabel().setText(text); this->widgets.push_back(label); this->titlebarBox->insertWidget(2, label); } void BaseWindow::changeEvent(QEvent *) { TooltipWidget::getInstance()->hide(); } void BaseWindow::leaveEvent(QEvent *) { TooltipWidget::getInstance()->hide(); } #ifdef USEWINSDK bool BaseWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) { MSG *msg = reinterpret_cast<MSG *>(message); switch (msg->message) { case WM_DPICHANGED: { qDebug() << "dpi changed"; int dpi = HIWORD(msg->wParam); float oldDpiMultiplier = this->dpiMultiplier; this->dpiMultiplier = dpi / 96.f; float scale = this->dpiMultiplier / oldDpiMultiplier; this->dpiMultiplierChanged(oldDpiMultiplier, this->dpiMultiplier); this->resize(static_cast<int>(this->width() * scale), static_cast<int>(this->height() * scale)); return true; } case WM_NCCALCSIZE: { if (this->hasCustomWindowFrame()) { // this kills the window frame and title bar we added with // WS_THICKFRAME and WS_CAPTION *result = 0; return true; } else { return QWidget::nativeEvent(eventType, message, result); } break; } case WM_NCHITTEST: { if (this->hasCustomWindowFrame()) { *result = 0; const LONG border_width = 8; // in pixels RECT winrect; GetWindowRect((HWND)winId(), &winrect); long x = GET_X_LPARAM(msg->lParam); long y = GET_Y_LPARAM(msg->lParam); bool resizeWidth = minimumWidth() != maximumWidth(); bool resizeHeight = minimumHeight() != maximumHeight(); if (resizeWidth) { // left border if (x >= winrect.left && x < winrect.left + border_width) { *result = HTLEFT; } // right border if (x < winrect.right && x >= winrect.right - border_width) { *result = HTRIGHT; } } if (resizeHeight) { // bottom border if (y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOM; } // top border if (y >= winrect.top && y < winrect.top + border_width) { *result = HTTOP; } } if (resizeWidth && resizeHeight) { // bottom left corner if (x >= winrect.left && x < winrect.left + border_width && y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOMLEFT; } // bottom right corner if (x < winrect.right && x >= winrect.right - border_width && y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOMRIGHT; } // top left corner if (x >= winrect.left && x < winrect.left + border_width && y >= winrect.top && y < winrect.top + border_width) { *result = HTTOPLEFT; } // top right corner if (x < winrect.right && x >= winrect.right - border_width && y >= winrect.top && y < winrect.top + border_width) { *result = HTTOPRIGHT; } } if (*result == 0) { bool client = false; QPoint point(x - winrect.left, y - winrect.top); for (QWidget *widget : this->widgets) { if (widget->geometry().contains(point)) { client = true; } } if (client) { *result = HTCLIENT; } else { *result = HTCAPTION; } } qDebug() << *result; return true; } else { return QWidget::nativeEvent(eventType, message, result); } break; } // end case WM_NCHITTEST case WM_CLOSE: { if (this->enableCustomFrame) { return close(); } break; } default: return QWidget::nativeEvent(eventType, message, result); } } void BaseWindow::showEvent(QShowEvent *) { if (this->isVisible() && this->hasCustomWindowFrame()) { SetWindowLongPtr((HWND)this->winId(), GWL_STYLE, WS_POPUP | WS_CAPTION | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX); const MARGINS shadow = {1, 1, 1, 1}; DwmExtendFrameIntoClientArea((HWND)this->winId(), &shadow); SetWindowPos((HWND)this->winId(), 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); } } void BaseWindow::paintEvent(QPaintEvent *event) { BaseWidget::paintEvent(event); if (this->hasCustomWindowFrame()) { QPainter painter(this); bool windowFocused = this->window() == QApplication::activeWindow(); if (windowFocused) { painter.setPen(this->themeManager.tabs.selected.backgrounds.regular.color()); } else { painter.setPen(this->themeManager.tabs.selected.backgrounds.unfocused.color()); } painter.drawRect(0, 0, this->width() - 1, this->height() - 1); } } #endif } // namespace widgets } // namespace chatterino <commit_msg>disabled custom window frame for now<commit_after>#include "basewindow.hpp" #include "singletons/settingsmanager.hpp" #include "util/nativeeventhelper.hpp" #include "widgets/tooltipwidget.hpp" #include <QApplication> #include <QDebug> #include <QIcon> #ifdef USEWINSDK #include <dwmapi.h> #include <gdiplus.h> #include <objidl.h> #include <windows.h> #include <windowsx.h> #pragma comment(lib, "Dwmapi.lib") #include <QHBoxLayout> #include <QVBoxLayout> #include "widgets/helper/rippleeffectlabel.hpp" #define WM_DPICHANGED 0x02E0 #endif namespace chatterino { namespace widgets { BaseWindow::BaseWindow(singletons::ThemeManager &_themeManager, QWidget *parent, bool _enableCustomFrame) : BaseWidget(_themeManager, parent, Qt::Window) , enableCustomFrame(_enableCustomFrame) { this->init(); } BaseWindow::BaseWindow(BaseWidget *parent, bool _enableCustomFrame) : BaseWidget(parent, Qt::Window) , enableCustomFrame(_enableCustomFrame) { this->init(); } BaseWindow::BaseWindow(QWidget *parent, bool _enableCustomFrame) : BaseWidget(parent, Qt::Window) , enableCustomFrame(_enableCustomFrame) { this->init(); } void BaseWindow::init() { this->setWindowIcon(QIcon(":/images/icon.png")); #ifdef USEWINSDK if (this->hasCustomWindowFrame()) { // CUSTOM WINDOW FRAME QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(1); this->setLayout(layout); { QHBoxLayout *buttons = this->titlebarBox = new QHBoxLayout; buttons->setMargin(0); layout->addLayout(buttons); // title QLabel *titleLabel = new QLabel("Chatterino"); buttons->addWidget(titleLabel); this->titleLabel = titleLabel; // buttons RippleEffectLabel *min = new RippleEffectLabel; min->getLabel().setText("min"); min->setFixedSize(46, 30); RippleEffectLabel *max = new RippleEffectLabel; max->setFixedSize(46, 30); max->getLabel().setText("max"); RippleEffectLabel *exit = new RippleEffectLabel; exit->setFixedSize(46, 30); exit->getLabel().setText("exit"); this->minButton = min; this->maxButton = max; this->exitButton = exit; this->widgets.push_back(min); this->widgets.push_back(max); this->widgets.push_back(exit); buttons->addStretch(1); buttons->addWidget(min); buttons->addWidget(max); buttons->addWidget(exit); } this->layoutBase = new QWidget(this); this->widgets.push_back(this->layoutBase); layout->addWidget(this->layoutBase); } // DPI auto dpi = util::getWindowDpi(this->winId()); if (dpi) { this->dpiMultiplier = dpi.value() / 96.f; } this->dpiMultiplierChanged(1, this->dpiMultiplier); #endif if (singletons::SettingManager::getInstance().windowTopMost.getValue()) { this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint); } } QWidget *BaseWindow::getLayoutContainer() { if (this->enableCustomFrame) { return this->layoutBase; } else { return this; } } bool BaseWindow::hasCustomWindowFrame() { #ifdef Q_OS_WIN // return this->enableCustomFrame; return false; #else return false; #endif } void BaseWindow::refreshTheme() { QPalette palette; palette.setColor(QPalette::Background, this->themeManager.windowBg); palette.setColor(QPalette::Foreground, this->themeManager.windowText); this->setPalette(palette); } void BaseWindow::addTitleBarButton(const QString &text) { RippleEffectLabel *label = new RippleEffectLabel; label->getLabel().setText(text); this->widgets.push_back(label); this->titlebarBox->insertWidget(2, label); } void BaseWindow::changeEvent(QEvent *) { TooltipWidget::getInstance()->hide(); } void BaseWindow::leaveEvent(QEvent *) { TooltipWidget::getInstance()->hide(); } #ifdef USEWINSDK bool BaseWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) { MSG *msg = reinterpret_cast<MSG *>(message); switch (msg->message) { case WM_DPICHANGED: { qDebug() << "dpi changed"; int dpi = HIWORD(msg->wParam); float oldDpiMultiplier = this->dpiMultiplier; this->dpiMultiplier = dpi / 96.f; float scale = this->dpiMultiplier / oldDpiMultiplier; this->dpiMultiplierChanged(oldDpiMultiplier, this->dpiMultiplier); this->resize(static_cast<int>(this->width() * scale), static_cast<int>(this->height() * scale)); return true; } case WM_NCCALCSIZE: { if (this->hasCustomWindowFrame()) { // this kills the window frame and title bar we added with // WS_THICKFRAME and WS_CAPTION *result = 0; return true; } else { return QWidget::nativeEvent(eventType, message, result); } break; } case WM_NCHITTEST: { if (this->hasCustomWindowFrame()) { *result = 0; const LONG border_width = 8; // in pixels RECT winrect; GetWindowRect((HWND)winId(), &winrect); long x = GET_X_LPARAM(msg->lParam); long y = GET_Y_LPARAM(msg->lParam); bool resizeWidth = minimumWidth() != maximumWidth(); bool resizeHeight = minimumHeight() != maximumHeight(); if (resizeWidth) { // left border if (x >= winrect.left && x < winrect.left + border_width) { *result = HTLEFT; } // right border if (x < winrect.right && x >= winrect.right - border_width) { *result = HTRIGHT; } } if (resizeHeight) { // bottom border if (y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOM; } // top border if (y >= winrect.top && y < winrect.top + border_width) { *result = HTTOP; } } if (resizeWidth && resizeHeight) { // bottom left corner if (x >= winrect.left && x < winrect.left + border_width && y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOMLEFT; } // bottom right corner if (x < winrect.right && x >= winrect.right - border_width && y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOMRIGHT; } // top left corner if (x >= winrect.left && x < winrect.left + border_width && y >= winrect.top && y < winrect.top + border_width) { *result = HTTOPLEFT; } // top right corner if (x < winrect.right && x >= winrect.right - border_width && y >= winrect.top && y < winrect.top + border_width) { *result = HTTOPRIGHT; } } if (*result == 0) { bool client = false; QPoint point(x - winrect.left, y - winrect.top); for (QWidget *widget : this->widgets) { if (widget->geometry().contains(point)) { client = true; } } if (client) { *result = HTCLIENT; } else { *result = HTCAPTION; } } qDebug() << *result; return true; } else { return QWidget::nativeEvent(eventType, message, result); } break; } // end case WM_NCHITTEST case WM_CLOSE: { if (this->enableCustomFrame) { return close(); } break; } default: return QWidget::nativeEvent(eventType, message, result); } } void BaseWindow::showEvent(QShowEvent *) { if (this->isVisible() && this->hasCustomWindowFrame()) { SetWindowLongPtr((HWND)this->winId(), GWL_STYLE, WS_POPUP | WS_CAPTION | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX); const MARGINS shadow = {1, 1, 1, 1}; DwmExtendFrameIntoClientArea((HWND)this->winId(), &shadow); SetWindowPos((HWND)this->winId(), 0, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); } } void BaseWindow::paintEvent(QPaintEvent *event) { BaseWidget::paintEvent(event); if (this->hasCustomWindowFrame()) { QPainter painter(this); bool windowFocused = this->window() == QApplication::activeWindow(); if (windowFocused) { painter.setPen(this->themeManager.tabs.selected.backgrounds.regular.color()); } else { painter.setPen(this->themeManager.tabs.selected.backgrounds.unfocused.color()); } painter.drawRect(0, 0, this->width() - 1, this->height() - 1); } } #endif } // namespace widgets } // namespace chatterino <|endoftext|>
<commit_before>#include "win_window_capture.h" WinWindowCapture::WinWindowCapture(const string& windowName) :name(windowName) { } HWND WinWindowCapture::FindHWND() { return FindWindowA(NULL, "Hearthstone"); } RECT WinWindowCapture::GetRect() { RECT rect = { 0 }; if(HWND hwnd = FindHWND()) { GetClientRect(hwnd, &rect); } return rect; } bool WinWindowCapture::WindowFound() { return FindHWND() != NULL; } int WinWindowCapture::GetWidth() { RECT rect = GetRect(); return rect.right - rect.left; } int WinWindowCapture::GetHeight() { RECT rect = GetRect(); return rect.bottom - rect.top; } QPixmap WinWindowCapture::Capture(int x, int y, int w, int h) { HWND hwnd = FindHWND(); QPixmap pixmap; if(hwnd) { HDC hDCWindow = GetDC(hwnd); HDC hDCMem = CreateCompatibleDC(hDCWindow); HBITMAP hBitmap = CreateCompatibleBitmap(hDCWindow, w, h); SelectObject(hDCMem, hBitmap); BitBlt(hDCMem, 0, 0, w, h, hDCWindow, x, y, SRCCOPY); pixmap = QPixmap::fromWinHBITMAP(hBitmap); ReleaseDC(hwnd, hDCWindow); DeleteDC(hDCMem); DeleteObject(hBitmap); } return pixmap; } <commit_msg>fix windows capture<commit_after>#include "win_window_capture.h" WinWindowCapture::WinWindowCapture(const string& windowName) :name(windowName) { } HWND WinWindowCapture::FindHWND() { return FindWindowA(NULL, name.c_str()); } RECT WinWindowCapture::GetRect() { RECT rect = { 0 }; if(HWND hwnd = FindHWND()) { GetClientRect(hwnd, &rect); } return rect; } bool WinWindowCapture::WindowFound() { return FindHWND() != NULL; } int WinWindowCapture::GetWidth() { RECT rect = GetRect(); return rect.right - rect.left; } int WinWindowCapture::GetHeight() { RECT rect = GetRect(); return rect.bottom - rect.top; } QPixmap WinWindowCapture::Capture(int x, int y, int w, int h) { HWND hwnd = FindHWND(); QPixmap pixmap; if(hwnd) { HDC hDCWindow = GetDC(hwnd); HDC hDCMem = CreateCompatibleDC(hDCWindow); HBITMAP hBitmap = CreateCompatibleBitmap(hDCWindow, w, h); SelectObject(hDCMem, hBitmap); BitBlt(hDCMem, 0, 0, w, h, hDCWindow, x, y, SRCCOPY); pixmap = QPixmap::fromWinHBITMAP(hBitmap); ReleaseDC(hwnd, hDCWindow); DeleteDC(hDCMem); DeleteObject(hBitmap); } return pixmap; } <|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. */ /* * Modified by Cloudius Systems * Copyright 2015 Cloudius Systems */ #pragma once #include "core/shared_ptr.hh" #include "types.hh" #include "keys.hh" #include "sstables/key.hh" #include <memory> #include <random> namespace dht { // // Origin uses a complex class hierarchy where Token is an abstract class, // and various subclasses use different implementations (LongToken vs. // BigIntegerToken vs. StringToken), plus other variants to to signify the // the beginning of the token space etc. // // We'll fold all of that into the token class and push all of the variations // into its users. class decorated_key; class token; class token { public: enum class kind { before_all_keys, key, after_all_keys, }; kind _kind; // _data can be interpreted as a big endian binary fraction // in the range [0.0, 1.0). // // So, [] == 0.0 // [0x00] == 0.0 // [0x80] == 0.5 // [0x00, 0x80] == 1/512 // [0xff, 0x80] == 1 - 1/512 bytes _data; token(kind k, bytes d) : _kind(k), _data(d) { } }; token midpoint(const token& t1, const token& t2); token minimum_token(); token maximum_token(); bool operator==(const token& t1, const token& t2); bool operator<(const token& t1, const token& t2); std::ostream& operator<<(std::ostream& out, const token& t); template <typename T> inline auto get_random_number() { static thread_local std::random_device rd; static thread_local std::default_random_engine re(rd()); static thread_local std::uniform_int_distribution<T> dist{}; return dist(re); } // Wraps partition_key with its corresponding token. // // Total ordering defined by comparators is compatible with Origin's ordering. class decorated_key { public: token _token; partition_key _key; struct less_comparator { schema_ptr s; less_comparator(schema_ptr s); bool operator()(const decorated_key& k1, const decorated_key& k2) const; }; bool equal(const schema& s, const decorated_key& other) const; bool less_compare(const schema& s, const decorated_key& other) const; int tri_compare(const schema& s, const decorated_key& other) const; }; class i_partitioner { public: virtual ~i_partitioner() {} /** * Transform key to object representation of the on-disk format. * * @param key the raw, client-facing key * @return decorated version of key */ decorated_key decorate_key(const schema& s, const partition_key& key) { return { get_token(s, key), key }; } /** * Transform key to object representation of the on-disk format. * * @param key the raw, client-facing key * @return decorated version of key */ decorated_key decorate_key(const schema& s, partition_key&& key) { auto token = get_token(s, key); return { std::move(token), std::move(key) }; } /** * Calculate a token representing the approximate "middle" of the given * range. * * @return The approximate midpoint between left and right. */ token midpoint(const token& left, const token& right) { return dht::midpoint(left, right); } /** * @return A token smaller than all others in the range that is being partitioned. * Not legal to assign to a node or key. (But legal to use in range scans.) */ token get_minimum_token() { return dht::minimum_token(); } /** * @return a token that can be used to route a given key * (This is NOT a method to create a token from its string representation; * for that, use tokenFactory.fromString.) */ virtual token get_token(const schema& s, partition_key_view key) = 0; virtual token get_token(const sstables::key_view& key) = 0; /** * @return a randomly generated token */ virtual token get_random_token() = 0; // FIXME: token.tokenFactory //virtual token.tokenFactory gettokenFactory() = 0; /** * @return True if the implementing class preserves key order in the tokens * it generates. */ virtual bool preserves_order() = 0; /** * Calculate the deltas between tokens in the ring in order to compare * relative sizes. * * @param sortedtokens a sorted List of tokens * @return the mapping from 'token' to 'percentage of the ring owned by that token'. */ virtual std::map<token, float> describe_ownership(const std::vector<token>& sorted_tokens) = 0; virtual data_type get_token_validator() = 0; /** * @return name of partitioner. */ virtual const bytes name() = 0; protected: /** * @return true if t1's _data array is equal t2's. _kind comparison should be done separately. */ virtual bool is_equal(const token& t1, const token& t2); /** * @return true if t1's _data array is less then t2's. _kind comparison should be done separately. */ virtual bool is_less(const token& t1, const token& t2); friend bool operator==(const token& t1, const token& t2); friend bool operator<(const token& t1, const token& t2); }; std::ostream& operator<<(std::ostream& out, const token& t); std::ostream& operator<<(std::ostream& out, const decorated_key& t); i_partitioner& global_partitioner(); } // dht namespace std { template<> struct hash<dht::token> { size_t operator()(const dht::token& t) const { return (t._kind == dht::token::kind::key) ? std::hash<bytes>()(t._data) : 0; } }; } <commit_msg>dht: Do move in token constructor<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. */ /* * Modified by Cloudius Systems * Copyright 2015 Cloudius Systems */ #pragma once #include "core/shared_ptr.hh" #include "types.hh" #include "keys.hh" #include "sstables/key.hh" #include <memory> #include <random> namespace dht { // // Origin uses a complex class hierarchy where Token is an abstract class, // and various subclasses use different implementations (LongToken vs. // BigIntegerToken vs. StringToken), plus other variants to to signify the // the beginning of the token space etc. // // We'll fold all of that into the token class and push all of the variations // into its users. class decorated_key; class token; class token { public: enum class kind { before_all_keys, key, after_all_keys, }; kind _kind; // _data can be interpreted as a big endian binary fraction // in the range [0.0, 1.0). // // So, [] == 0.0 // [0x00] == 0.0 // [0x80] == 0.5 // [0x00, 0x80] == 1/512 // [0xff, 0x80] == 1 - 1/512 bytes _data; token(kind k, bytes d) : _kind(std::move(k)), _data(std::move(d)) { } }; token midpoint(const token& t1, const token& t2); token minimum_token(); token maximum_token(); bool operator==(const token& t1, const token& t2); bool operator<(const token& t1, const token& t2); std::ostream& operator<<(std::ostream& out, const token& t); template <typename T> inline auto get_random_number() { static thread_local std::random_device rd; static thread_local std::default_random_engine re(rd()); static thread_local std::uniform_int_distribution<T> dist{}; return dist(re); } // Wraps partition_key with its corresponding token. // // Total ordering defined by comparators is compatible with Origin's ordering. class decorated_key { public: token _token; partition_key _key; struct less_comparator { schema_ptr s; less_comparator(schema_ptr s); bool operator()(const decorated_key& k1, const decorated_key& k2) const; }; bool equal(const schema& s, const decorated_key& other) const; bool less_compare(const schema& s, const decorated_key& other) const; int tri_compare(const schema& s, const decorated_key& other) const; }; class i_partitioner { public: virtual ~i_partitioner() {} /** * Transform key to object representation of the on-disk format. * * @param key the raw, client-facing key * @return decorated version of key */ decorated_key decorate_key(const schema& s, const partition_key& key) { return { get_token(s, key), key }; } /** * Transform key to object representation of the on-disk format. * * @param key the raw, client-facing key * @return decorated version of key */ decorated_key decorate_key(const schema& s, partition_key&& key) { auto token = get_token(s, key); return { std::move(token), std::move(key) }; } /** * Calculate a token representing the approximate "middle" of the given * range. * * @return The approximate midpoint between left and right. */ token midpoint(const token& left, const token& right) { return dht::midpoint(left, right); } /** * @return A token smaller than all others in the range that is being partitioned. * Not legal to assign to a node or key. (But legal to use in range scans.) */ token get_minimum_token() { return dht::minimum_token(); } /** * @return a token that can be used to route a given key * (This is NOT a method to create a token from its string representation; * for that, use tokenFactory.fromString.) */ virtual token get_token(const schema& s, partition_key_view key) = 0; virtual token get_token(const sstables::key_view& key) = 0; /** * @return a randomly generated token */ virtual token get_random_token() = 0; // FIXME: token.tokenFactory //virtual token.tokenFactory gettokenFactory() = 0; /** * @return True if the implementing class preserves key order in the tokens * it generates. */ virtual bool preserves_order() = 0; /** * Calculate the deltas between tokens in the ring in order to compare * relative sizes. * * @param sortedtokens a sorted List of tokens * @return the mapping from 'token' to 'percentage of the ring owned by that token'. */ virtual std::map<token, float> describe_ownership(const std::vector<token>& sorted_tokens) = 0; virtual data_type get_token_validator() = 0; /** * @return name of partitioner. */ virtual const bytes name() = 0; protected: /** * @return true if t1's _data array is equal t2's. _kind comparison should be done separately. */ virtual bool is_equal(const token& t1, const token& t2); /** * @return true if t1's _data array is less then t2's. _kind comparison should be done separately. */ virtual bool is_less(const token& t1, const token& t2); friend bool operator==(const token& t1, const token& t2); friend bool operator<(const token& t1, const token& t2); }; std::ostream& operator<<(std::ostream& out, const token& t); std::ostream& operator<<(std::ostream& out, const decorated_key& t); i_partitioner& global_partitioner(); } // dht namespace std { template<> struct hash<dht::token> { size_t operator()(const dht::token& t) const { return (t._kind == dht::token::kind::key) ? std::hash<bytes>()(t._data) : 0; } }; } <|endoftext|>
<commit_before>#include "../stdafx.h" #include "signer.h" void Signer::setCertificate(Handle<Certificate> cert){ LOGGER_FN(); LOGGER_OPENSSL("CMS_SignerInfo_cert_cmp"); if (CMS_SignerInfo_cert_cmp(this->internal(), cert->internal()) != 0){ THROW_EXCEPTION(0, Signer, NULL, "Certificate has differents with Signer certificate id"); } LOGGER_OPENSSL("CMS_SignerInfo_set1_signer_cert"); CMS_SignerInfo_set1_signer_cert(this->internal(), cert->internal()); } Handle<Certificate> Signer::getCertificate(){ LOGGER_FN(); X509 *cert; LOGGER_OPENSSL("CMS_SignerInfo_get0_algs"); CMS_SignerInfo_get0_algs(this->internal(), NULL, &cert, NULL, NULL); if (!cert){ THROW_EXCEPTION(0, Signer, NULL, "Signer hasn't got Certificate"); } return new Certificate(cert, this->handle()); } Handle<std::string> Signer::getSignature(){ LOGGER_FN(); LOGGER_OPENSSL("CMS_SignerInfo_get0_signature"); ASN1_OCTET_STRING *sign = CMS_SignerInfo_get0_signature(this->internal()); if (!sign){ THROW_EXCEPTION(0, Signer, NULL, "Has no signature value"); } char *buf = reinterpret_cast<char*>(sign->data); return new std::string(buf, sign->length); } Handle<SignerAttributeCollection> Signer::signedAttributes(){ LOGGER_FN(); Handle<SignerAttributeCollection> attrs = new SignerAttributeCollection(new Signer(this->internal(), this->handle()), true); return attrs; } Handle<Attribute> Signer::signedAttributes(int index){ LOGGER_FN(); return this->signedAttributes()->items(index); } Handle<Attribute> Signer::signedAttributes(int index, int location){ LOGGER_FN(); return this->signedAttributes()->items(index, location); } Handle<Attribute> Signer::signedAttributes(Handle<OID> oid){ LOGGER_FN(); return this->signedAttributes()->items(oid); } Handle<Attribute> Signer::signedAttributes(Handle<OID> oid, int location){ LOGGER_FN(); return this->signedAttributes()->items(oid, location); } Handle<SignerAttributeCollection> Signer::unsignedAttributes(){ LOGGER_FN(); Handle<SignerAttributeCollection> attrs = new SignerAttributeCollection(this, false); return attrs; } Handle<Attribute> Signer::unsignedAttributes(int index){ LOGGER_FN(); return this->unsignedAttributes()->items(index); } Handle<Attribute> Signer::unsignedAttributes(int index, int location){ LOGGER_FN(); return this->unsignedAttributes()->items(index, location); } Handle<Attribute> Signer::unsignedAttributes(Handle<OID> oid){ LOGGER_FN(); return this->unsignedAttributes()->items(oid); } Handle<Attribute> Signer::unsignedAttributes(Handle<OID> oid, int location){ LOGGER_FN(); return this->unsignedAttributes()->items(oid, location); } void Signer::sign(){ LOGGER_FN(); LOGGER_OPENSSL("CMS_SignerInfo_sign"); if (CMS_SignerInfo_sign(this->internal()) < 1){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_sign"); } } bool Signer::verify(){ LOGGER_FN(); try { LOGGER_OPENSSL("CMS_signed_get_attr_count"); if (CMS_signed_get_attr_count(this->internal()) < 0) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "No sign attributes"); } LOGGER_OPENSSL("CMS_SignerInfo_verify"); int res = CMS_SignerInfo_verify(this->internal()); if (res == -1){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_verify"); } return res == 1; } catch (Handle<Exception> e) { THROW_EXCEPTION(0, Signer, e, "Error verify signer info"); } } bool Signer::verify(Handle<Bio> content){ LOGGER_FN(); try { EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX* pctx = NULL; const EVP_MD *md = NULL; const char * digestName; Handle<std::string> signature; char *data; long datalen; int res = 0; if ( !(pkey = this->getCertificate()->getPublicKey()->internal()) ) { THROW_EXCEPTION(0, Signer, NULL, "Error get public key"); } if (!(digestName = this->getDigestAlgorithm()->getName()->c_str())) { THROW_EXCEPTION(0, Signer, NULL, "Error get digest name"); } LOGGER_OPENSSL("EVP_get_digestbyobj"); if ( !(md = EVP_get_digestbyobj(this->getDigestAlgorithm()->getTypeId()->internal())) ) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "EVP_get_digestbyobj"); } LOGGER_OPENSSL("EVP_MD_CTX_create"); mctx = EVP_MD_CTX_create(); pctx = nullptr; LOGGER_OPENSSL("EVP_DigestVerifyInit"); if (!mctx || !EVP_DigestVerifyInit(mctx, &pctx, md, nullptr, pkey)) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "EVP_DigestVerifyInit"); } if ((signature = this->getSignature()).isEmpty()) { THROW_EXCEPTION(0, Signer, NULL, "Error get signature"); } LOGGER_OPENSSL("BIO_get_mem_data"); datalen = BIO_get_mem_data(content->internal(), &data); LOGGER_OPENSSL("EVP_DigestVerifyUpdate"); if (!EVP_DigestVerifyUpdate(mctx, data, datalen)) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "EVP_DigestVerifyUpdate"); } LOGGER_OPENSSL("EVP_DigestVerifyFinal"); res = EVP_DigestVerifyFinal(mctx, (const unsigned char *)signature->c_str(), signature->length()); if (res < 0) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_verify_content"); } if (pctx) { LOGGER_OPENSSL("EVP_PKEY_CTX_free"); EVP_PKEY_CTX_free(pctx); } return res == 1; } catch (Handle<Exception> e) { THROW_EXCEPTION(0, Signer, e, "Error verify signer content"); } } Handle<SignerId> Signer::getSignerId(){ LOGGER_FN(); ASN1_OCTET_STRING *keyid = NULL; ASN1_INTEGER *sn = NULL; X509_NAME *issuerName = NULL; try { LOGGER_OPENSSL("CMS_SignerInfo_get0_signer_id"); if (CMS_SignerInfo_get0_signer_id(this->internal(), &keyid, &issuerName, &sn) < 1){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_get0_signer_id"); } Handle<SignerId> certId = new SignerId(); if (keyid){ Handle<std::string> keyid_str = new std::string((char*)keyid->data, keyid->length); certId->setKeyId(keyid_str); } if (sn){ LOGGER_OPENSSL(BIO_new); BIO * bioSerial = BIO_new(BIO_s_mem()); LOGGER_OPENSSL(i2a_ASN1_INTEGER); if (i2a_ASN1_INTEGER(bioSerial, sn) < 0){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "i2a_ASN1_INTEGER", NULL); } int contlen; char * cont; LOGGER_OPENSSL(BIO_get_mem_data); contlen = BIO_get_mem_data(bioSerial, &cont); Handle<std::string> sn_str = new std::string(cont, contlen); BIO_free(bioSerial); certId->setSerialNumber(sn_str); } if (issuerName){ LOGGER_OPENSSL(X509_NAME_oneline_ex); std::string str_name = X509_NAME_oneline_ex(issuerName); Handle<std::string> res = new std::string(str_name.c_str(), str_name.length()); certId->setIssuerName(res); } return certId; } catch (Handle<Exception> e) { THROW_EXCEPTION(0, Signer, e, "Error get signer identifier information"); } } Handle<Algorithm> Signer::getSignatureAlgorithm(){ LOGGER_FN(); X509_ALGOR *alg; LOGGER_OPENSSL("CMS_SignerInfo_get0_algs"); CMS_SignerInfo_get0_algs(this->internal(), NULL, NULL, NULL, &alg); if (!alg){ THROW_EXCEPTION(0, Signer, NULL, "Signer hasn't got signature algorithm"); } return new Algorithm(alg, this->handle()); } Handle<Algorithm> Signer::getDigestAlgorithm(){ LOGGER_FN(); X509_ALGOR *alg; LOGGER_OPENSSL("CMS_SignerInfo_get0_algs"); CMS_SignerInfo_get0_algs(this->internal(), NULL, NULL, &alg, NULL); if (!alg){ THROW_EXCEPTION(0, Signer, NULL, "Signer hasn't got digest algorithm"); } return new Algorithm(alg, this->handle()); } <commit_msg>Fix verify signer content<commit_after>#include "../stdafx.h" #include "signer.h" void Signer::setCertificate(Handle<Certificate> cert){ LOGGER_FN(); LOGGER_OPENSSL("CMS_SignerInfo_cert_cmp"); if (CMS_SignerInfo_cert_cmp(this->internal(), cert->internal()) != 0){ THROW_EXCEPTION(0, Signer, NULL, "Certificate has differents with Signer certificate id"); } LOGGER_OPENSSL("CMS_SignerInfo_set1_signer_cert"); CMS_SignerInfo_set1_signer_cert(this->internal(), cert->internal()); } Handle<Certificate> Signer::getCertificate(){ LOGGER_FN(); X509 *cert; LOGGER_OPENSSL("CMS_SignerInfo_get0_algs"); CMS_SignerInfo_get0_algs(this->internal(), NULL, &cert, NULL, NULL); if (!cert){ THROW_EXCEPTION(0, Signer, NULL, "Signer hasn't got Certificate"); } return new Certificate(cert, this->handle()); } Handle<std::string> Signer::getSignature(){ LOGGER_FN(); LOGGER_OPENSSL("CMS_SignerInfo_get0_signature"); ASN1_OCTET_STRING *sign = CMS_SignerInfo_get0_signature(this->internal()); if (!sign){ THROW_EXCEPTION(0, Signer, NULL, "Has no signature value"); } char *buf = reinterpret_cast<char*>(sign->data); return new std::string(buf, sign->length); } Handle<SignerAttributeCollection> Signer::signedAttributes(){ LOGGER_FN(); Handle<SignerAttributeCollection> attrs = new SignerAttributeCollection(new Signer(this->internal(), this->handle()), true); return attrs; } Handle<Attribute> Signer::signedAttributes(int index){ LOGGER_FN(); return this->signedAttributes()->items(index); } Handle<Attribute> Signer::signedAttributes(int index, int location){ LOGGER_FN(); return this->signedAttributes()->items(index, location); } Handle<Attribute> Signer::signedAttributes(Handle<OID> oid){ LOGGER_FN(); return this->signedAttributes()->items(oid); } Handle<Attribute> Signer::signedAttributes(Handle<OID> oid, int location){ LOGGER_FN(); return this->signedAttributes()->items(oid, location); } Handle<SignerAttributeCollection> Signer::unsignedAttributes(){ LOGGER_FN(); Handle<SignerAttributeCollection> attrs = new SignerAttributeCollection(this, false); return attrs; } Handle<Attribute> Signer::unsignedAttributes(int index){ LOGGER_FN(); return this->unsignedAttributes()->items(index); } Handle<Attribute> Signer::unsignedAttributes(int index, int location){ LOGGER_FN(); return this->unsignedAttributes()->items(index, location); } Handle<Attribute> Signer::unsignedAttributes(Handle<OID> oid){ LOGGER_FN(); return this->unsignedAttributes()->items(oid); } Handle<Attribute> Signer::unsignedAttributes(Handle<OID> oid, int location){ LOGGER_FN(); return this->unsignedAttributes()->items(oid, location); } void Signer::sign(){ LOGGER_FN(); LOGGER_OPENSSL("CMS_SignerInfo_sign"); if (CMS_SignerInfo_sign(this->internal()) < 1){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_sign"); } } bool Signer::verify(){ LOGGER_FN(); try { LOGGER_OPENSSL("CMS_signed_get_attr_count"); if (CMS_signed_get_attr_count(this->internal()) < 0) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "No sign attributes"); } LOGGER_OPENSSL("CMS_SignerInfo_verify"); int res = CMS_SignerInfo_verify(this->internal()); if (res == -1){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_verify"); } return res == 1; } catch (Handle<Exception> e) { THROW_EXCEPTION(0, Signer, e, "Error verify signer info"); } } bool Signer::verify(Handle<Bio> content){ LOGGER_FN(); try { ASN1_OCTET_STRING *os = NULL; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX* pctx = NULL; unsigned char mval[EVP_MAX_MD_SIZE]; unsigned int mlen; const EVP_MD *md = NULL; const char * digestName; Handle<std::string> signature; char *data; long datalen; int res = 0; LOGGER_OPENSSL("CMS_signed_get_attr_count"); if (CMS_signed_get_attr_count(this->internal()) >= 0) { LOGGER_OPENSSL("CMS_signed_get0_data_by_OBJ"); os = (ASN1_OCTET_STRING *)CMS_signed_get0_data_by_OBJ(this->internal(), OBJ_nid2obj(NID_pkcs9_messageDigest), -3, V_ASN1_OCTET_STRING); if (!os) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "Error reading messagedigest attribute"); } } if ( !(pkey = this->getCertificate()->getPublicKey()->internal()) ) { THROW_EXCEPTION(0, Signer, NULL, "Error get public key"); } if (!(digestName = this->getDigestAlgorithm()->getName()->c_str())) { THROW_EXCEPTION(0, Signer, NULL, "Error get digest name"); } LOGGER_OPENSSL("EVP_get_digestbyobj"); if ( !(md = EVP_get_digestbyobj(this->getDigestAlgorithm()->getTypeId()->internal())) ) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "EVP_get_digestbyobj"); } LOGGER_OPENSSL("EVP_MD_CTX_create"); mctx = EVP_MD_CTX_create(); pctx = nullptr; LOGGER_OPENSSL("EVP_DigestVerifyInit"); if (!mctx || !EVP_DigestVerifyInit(mctx, &pctx, md, nullptr, pkey)) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "EVP_DigestVerifyInit"); } if ((signature = this->getSignature()).isEmpty()) { THROW_EXCEPTION(0, Signer, NULL, "Error get signature"); } LOGGER_OPENSSL("BIO_get_mem_data"); datalen = BIO_get_mem_data(content->internal(), &data); LOGGER_OPENSSL("EVP_DigestVerifyUpdate"); if (!EVP_DigestVerifyUpdate(mctx, data, datalen)) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "EVP_DigestVerifyUpdate"); } if (EVP_DigestFinal_ex(mctx, mval, &mlen) <= 0) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "Unable to finalize context"); } if (os) { if (mlen != (unsigned int)os->length) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "Messagedigest attribute wrong length"); } if (memcmp(mval, os->data, mlen)) { CMSerr(CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT, CMS_R_VERIFICATION_FAILURE); res = 0; } else res = 1; } else { LOGGER_OPENSSL("EVP_PKEY_verify"); res = EVP_PKEY_verify(pctx, (const unsigned char *)signature->c_str(), signature->length(), mval, mlen); if (res < 0) { THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_verify_content"); } } if (pctx) { LOGGER_OPENSSL("EVP_PKEY_CTX_free"); EVP_PKEY_CTX_free(pctx); } return res == 1; } catch (Handle<Exception> e) { THROW_EXCEPTION(0, Signer, e, "Error verify signer content"); } } Handle<SignerId> Signer::getSignerId(){ LOGGER_FN(); ASN1_OCTET_STRING *keyid = NULL; ASN1_INTEGER *sn = NULL; X509_NAME *issuerName = NULL; try { LOGGER_OPENSSL("CMS_SignerInfo_get0_signer_id"); if (CMS_SignerInfo_get0_signer_id(this->internal(), &keyid, &issuerName, &sn) < 1){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "CMS_SignerInfo_get0_signer_id"); } Handle<SignerId> certId = new SignerId(); if (keyid){ Handle<std::string> keyid_str = new std::string((char*)keyid->data, keyid->length); certId->setKeyId(keyid_str); } if (sn){ LOGGER_OPENSSL(BIO_new); BIO * bioSerial = BIO_new(BIO_s_mem()); LOGGER_OPENSSL(i2a_ASN1_INTEGER); if (i2a_ASN1_INTEGER(bioSerial, sn) < 0){ THROW_OPENSSL_EXCEPTION(0, Signer, NULL, "i2a_ASN1_INTEGER", NULL); } int contlen; char * cont; LOGGER_OPENSSL(BIO_get_mem_data); contlen = BIO_get_mem_data(bioSerial, &cont); Handle<std::string> sn_str = new std::string(cont, contlen); BIO_free(bioSerial); certId->setSerialNumber(sn_str); } if (issuerName){ LOGGER_OPENSSL(X509_NAME_oneline_ex); std::string str_name = X509_NAME_oneline_ex(issuerName); Handle<std::string> res = new std::string(str_name.c_str(), str_name.length()); certId->setIssuerName(res); } return certId; } catch (Handle<Exception> e) { THROW_EXCEPTION(0, Signer, e, "Error get signer identifier information"); } } Handle<Algorithm> Signer::getSignatureAlgorithm(){ LOGGER_FN(); X509_ALGOR *alg; LOGGER_OPENSSL("CMS_SignerInfo_get0_algs"); CMS_SignerInfo_get0_algs(this->internal(), NULL, NULL, NULL, &alg); if (!alg){ THROW_EXCEPTION(0, Signer, NULL, "Signer hasn't got signature algorithm"); } return new Algorithm(alg, this->handle()); } Handle<Algorithm> Signer::getDigestAlgorithm(){ LOGGER_FN(); X509_ALGOR *alg; LOGGER_OPENSSL("CMS_SignerInfo_get0_algs"); CMS_SignerInfo_get0_algs(this->internal(), NULL, NULL, &alg, NULL); if (!alg){ THROW_EXCEPTION(0, Signer, NULL, "Signer hasn't got digest algorithm"); } return new Algorithm(alg, this->handle()); } <|endoftext|>
<commit_before>/* Copyright 2013 Roman Kurbatov * * 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. * * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime * project. See git revision history for detailed changes. */ #include "trikGuiApplication.h" #include <QtGui/QKeyEvent> #include <QtCore/QProcess> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QWidget> #else #include <QtWidgets/QWidget> #endif #include "backgroundWidget.h" using namespace trikGui; TrikGuiApplication::TrikGuiApplication(int &argc, char **argv) : QApplication(argc, argv) { connect(&mPowerButtonPressedTimer, SIGNAL(timeout()), this, SLOT(shutdown())); } bool TrikGuiApplication::notify(QObject *receiver, QEvent *event) { if (event->type() == QEvent::KeyPress) { refreshWidgets(); QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_PowerOff && keyEvent->isAutoRepeat() && !mPowerButtonPressedTimer.isActive()) { mPowerButtonPressedTimer.start(3000); } } else if (event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_PowerOff && !keyEvent->isAutoRepeat()) { mPowerButtonPressedTimer.stop(); } } return QApplication::notify(receiver, event); } void TrikGuiApplication::refreshWidgets() { if (dynamic_cast<BackgroundWidget *>(QApplication::activeWindow())) { for (const auto widget : QApplication::allWidgets()) { widget->update(); } } } void TrikGuiApplication::shutdown() { if (!mIsShuttingDown) { QProcess::startDetached("/bin/sh", {"-c", "halt"}); mIsShuttingDown = true; } } <commit_msg>No flashing on powerOff<commit_after>/* Copyright 2013 Roman Kurbatov * * 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. * * This file was modified by Yurii Litvinov to make it comply with the requirements of trikRuntime * project. See git revision history for detailed changes. */ #include "trikGuiApplication.h" #include <QtGui/QKeyEvent> #include <QtCore/QProcess> #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) #include <QtGui/QWidget> #else #include <QtWidgets/QWidget> #endif #include "backgroundWidget.h" using namespace trikGui; TrikGuiApplication::TrikGuiApplication(int &argc, char **argv) : QApplication(argc, argv) { connect(&mPowerButtonPressedTimer, SIGNAL(timeout()), this, SLOT(shutdown())); } bool TrikGuiApplication::notify(QObject *receiver, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_PowerOff) { if (keyEvent->isAutoRepeat()) { if (!mPowerButtonPressedTimer.isActive()) { mPowerButtonPressedTimer.start(3000); } } else { refreshWidgets(); // refresh display if not auto-repeat } } } else if (event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_PowerOff && !keyEvent->isAutoRepeat()) { mPowerButtonPressedTimer.stop(); } } return QApplication::notify(receiver, event); } void TrikGuiApplication::refreshWidgets() { if (dynamic_cast<BackgroundWidget *>(QApplication::activeWindow())) { for (const auto widget : QApplication::allWidgets()) { widget->update(); } } } void TrikGuiApplication::shutdown() { if (!mIsShuttingDown) { QString cmd = "'sync ; sync ; shutdown -h -P -t 2 now'"; QProcess::startDetached("/bin/sh", {"-c", cmd}); QApplication::exit(0); mIsShuttingDown = true; } } <|endoftext|>
<commit_before>/* Copyright (C) 2012 Alexander Overvoorde 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 <GL/Window/Window.hpp> #ifdef OOGL_PLATFORM_WINDOWS namespace GL { Window::Window( uint width, uint height, const std::string& title, WindowStyle::window_style_t style ) { // Create class for OpenGL window WNDCLASS wc = { 0 }; wc.lpfnWndProc = WindowEventHandler; wc.hInstance = GetModuleHandle( NULL ); wc.hIcon = LoadIcon( NULL, IDI_APPLICATION ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH ); wc.lpszClassName = "OOGL_WINDOW"; wc.style = CS_OWNDC; RegisterClass( &wc ); // Configure window style ulong windowStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_VISIBLE; if ( style & WindowStyle::Close ) windowStyle |= WS_SYSMENU; if ( style & WindowStyle::Resize ) windowStyle |= WS_SYSMENU | WS_THICKFRAME | WS_MAXIMIZEBOX; int x = 0; int y = 0; if ( !( style & WindowStyle::Fullscreen ) ) { // Calculate window size for requested client size RECT rect = { 0, 0, width, height }; AdjustWindowRect( &rect, windowStyle, false ); width = rect.right - rect.left; height = rect.bottom - rect.top; // Center window on screen GetClientRect( GetDesktopWindow(), &rect ); x = ( rect.right - rect.left - width ) / 2; y = ( rect.bottom - rect.top - height ) / 2; } // Create window HWND window = CreateWindow( "OOGL_WINDOW", title.c_str(), windowStyle, x, y, width, height, NULL, NULL, GetModuleHandle( NULL ), this ); // Initialize fullscreen mode if ( style & WindowStyle::Fullscreen ) { DEVMODE dm; dm.dmSize = sizeof( dm ); dm.dmPelsWidth = width; dm.dmPelsHeight = height; dm.dmBitsPerPel = 32; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL; ChangeDisplaySettings( &dm, CDS_FULLSCREEN ); SetWindowLong( window, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS ); SetWindowLong( window, GWL_EXSTYLE, WS_EX_APPWINDOW ); SetWindowPos( window, HWND_TOP, 0, 0, width, height, SWP_FRAMECHANGED ); ShowWindow( window, SW_SHOW ); } // Initialize window properties RECT rect; GetWindowRect( window, &rect ); this->x = rect.left; this->y = rect.top; GetClientRect( window, &rect ); this->width = rect.right - rect.left; this->height = rect.bottom - rect.top; this->open = true; this->style = windowStyle; this->mousex = 0; this->mousey = 0; memset( this->mouse, 0, sizeof( this->mouse ) ); memset( this->keys, 0, sizeof( this->keys ) ); this->context = 0; } Window::~Window() { if ( context ) delete context; DestroyWindow( window ); UnregisterClass( "OGLWINDOW", GetModuleHandle( NULL ) ); } void Window::SetPos( int x, int y ) { if ( !open ) return; SetWindowPos( window, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER ); } void Window::SetSize( uint width, uint height ) { if ( !open ) return; RECT rect = { 0, 0, width, height }; AdjustWindowRect( &rect, style, false ); SetWindowPos( window, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOMOVE | SWP_NOZORDER ); } void Window::SetTitle( const std::string& title ) { if ( !open ) return; SetWindowText( window, title.c_str() ); } void Window::SetVisible( bool visible ) { if ( !open ) return; ShowWindow( window, visible ? SW_SHOW : SW_HIDE ); } void Window::Close() { CloseWindow( window ); open = false; } bool Window::GetEvent( Event& ev ) { // Fetch new events MSG msg; while ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } // Return oldest event - if available if ( events.empty() ) return false; ev = events.front(); events.pop(); return true; } Context& Window::GetContext( uchar color, uchar depth, uchar stencil, uchar antialias ) { if ( context ) return *context; else return *( context = new Context( color, depth, stencil, antialias, GetDC( window ) ) ); } void Window::Present() { if ( !context ) return; context->Activate(); SwapBuffers( GetDC( window ) ); } LRESULT Window::WindowEvent( UINT msg, WPARAM wParam, LPARAM lParam ) { Event ev; ev.Type = Event::Unknown; // Translate message to Event switch ( msg ) { case WM_CLOSE: Close(); ev.Type = Event::Close; break; case WM_SIZE: width = GET_X_LPARAM( lParam ); height = GET_Y_LPARAM( lParam ); if ( events.empty() ) { ev.Type = Event::Resize; ev.Window.Width = width; ev.Window.Height = height; } else if ( events.back().Type == Event::Resize ) { events.back().Window.Width = width; events.back().Window.Height = height; } break; case WM_MOVE: RECT rect; GetWindowRect( window, &rect ); x = rect.left; y = rect.top; if ( events.empty() ) { ev.Type = Event::Move; ev.Window.X = x; ev.Window.Y = y; } else if ( events.back().Type == Event::Move ) { events.back().Window.X = x; events.back().Window.Y = y; } break; case WM_ACTIVATE: if ( wParam == WA_INACTIVE ) { ev.Type = Event::Blur; focus = false; } else { ev.Type = Event::Focus; focus = true; } break; case WM_KEYDOWN: case WM_SYSKEYDOWN: ev.Type = Event::KeyDown; ev.Key.Code = TranslateKey( wParam ); ev.Key.Alt = HIWORD( GetAsyncKeyState( VK_MENU ) ) != 0; ev.Key.Control = HIWORD( GetAsyncKeyState( VK_CONTROL ) ) != 0; ev.Key.Shift = HIWORD( GetAsyncKeyState( VK_SHIFT ) ) != 0; keys[ev.Key.Code] = true; break; case WM_KEYUP: case WM_SYSKEYUP: ev.Type = Event::KeyUp; ev.Key.Code = TranslateKey( wParam ); ev.Key.Alt = HIWORD( GetAsyncKeyState( VK_MENU ) ) != 0; ev.Key.Control = HIWORD( GetAsyncKeyState( VK_CONTROL ) ) != 0; ev.Key.Shift = HIWORD( GetAsyncKeyState( VK_SHIFT ) ) != 0; keys[ev.Key.Code] = false; break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); if ( msg == WM_LBUTTONDOWN ) ev.Mouse.Button = MouseButton::Left; else if ( msg == WM_RBUTTONDOWN ) ev.Mouse.Button = MouseButton::Right; else if ( msg == WM_MBUTTONDOWN ) ev.Mouse.Button = MouseButton::Middle; else break; ev.Type = Event::MouseDown; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; mouse[ev.Mouse.Button] = true; break; case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); if ( msg == WM_LBUTTONUP ) ev.Mouse.Button = MouseButton::Left; else if ( msg == WM_LBUTTONUP ) ev.Mouse.Button = MouseButton::Right; else if ( msg == WM_LBUTTONUP ) ev.Mouse.Button = MouseButton::Middle; else break; ev.Type = Event::MouseUp; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; mouse[ev.Mouse.Button] = false; break; case WM_MOUSEWHEEL: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); ev.Type = Event::MouseWheel; ev.Mouse.Delta = GET_WHEEL_DELTA_WPARAM( wParam ) > 0 ? 1 : -1; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; break; case WM_MOUSEMOVE: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); ev.Type = Event::MouseMove; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; break; default: return DefWindowProc( window, msg, wParam, lParam ); } // Add event to internal queue if ( ev.Type != Event::Unknown ) events.push( ev ); return 0; } LRESULT CALLBACK Window::WindowEventHandler( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { Window* window; if ( msg == WM_NCCREATE ) { // Store pointer to associated Window class as userdata in Win32 window window = reinterpret_cast<Window*>( ( (LPCREATESTRUCT)lParam )->lpCreateParams ); window->window = hwnd; SetWindowLong( hwnd, GWL_USERDATA, reinterpret_cast<long>( window ) ); return DefWindowProc( hwnd, msg, wParam, lParam ); } else { window = reinterpret_cast<Window*>( GetWindowLong( hwnd, GWL_USERDATA ) ); if( window != nullptr ) return window->WindowEvent( msg, wParam, lParam ); else return DefWindowProc( hwnd, msg, wParam, lParam ); } } Key::key_t Window::TranslateKey( uint code ) { switch ( code ) { case VK_SHIFT: return Key::Shift; case VK_MENU: return Key::Alt; case VK_CONTROL: return Key::Control; case VK_OEM_1: return Key::Semicolon; case VK_OEM_2: return Key::Slash; case VK_OEM_PLUS: return Key::Equals; case VK_OEM_MINUS: return Key::Hyphen; case VK_OEM_4: return Key::LeftBracket; case VK_OEM_6: return Key::RightBracket; case VK_OEM_COMMA: return Key::Comma; case VK_OEM_PERIOD: return Key::Period; case VK_OEM_7: return Key::Quote; case VK_OEM_5: return Key::Backslash; case VK_OEM_3: return Key::Tilde; case VK_ESCAPE: return Key::Escape; case VK_SPACE: return Key::Space; case VK_RETURN: return Key::Enter; case VK_BACK: return Key::Backspace; case VK_TAB: return Key::Tab; case VK_PRIOR: return Key::PageUp; case VK_NEXT: return Key::PageDown; case VK_END: return Key::End; case VK_HOME: return Key::Home; case VK_INSERT: return Key::Insert; case VK_DELETE: return Key::Delete; case VK_ADD: return Key::Add; case VK_SUBTRACT: return Key::Subtract; case VK_MULTIPLY: return Key::Multiply; case VK_DIVIDE: return Key::Divide; case VK_PAUSE: return Key::Pause; case VK_LEFT: return Key::Left; case VK_RIGHT: return Key::Right; case VK_UP: return Key::Up; case VK_DOWN: return Key::Down; default: if ( code >= VK_F1 && code <= VK_F12 ) return (Key::key_t)( Key::F1 + code - VK_F1 ); else if ( code >= VK_NUMPAD0 && code <= VK_NUMPAD9 ) return (Key::key_t)( Key::Numpad0 + code - VK_NUMPAD0 ); else if ( code >= 'A' && code <= 'Z' ) return (Key::key_t)( Key::A + code - 'A' ); else if ( code >= '0' && code <= '9' ) return (Key::key_t)( Key::Num0 + code - '0' ); } return Key::Unknown; } } #endif<commit_msg>Fixed mouse up events not being fired for some mouse buttons.<commit_after>/* Copyright (C) 2012 Alexander Overvoorde 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 <GL/Window/Window.hpp> #ifdef OOGL_PLATFORM_WINDOWS namespace GL { Window::Window( uint width, uint height, const std::string& title, WindowStyle::window_style_t style ) { // Create class for OpenGL window WNDCLASS wc = { 0 }; wc.lpfnWndProc = WindowEventHandler; wc.hInstance = GetModuleHandle( NULL ); wc.hIcon = LoadIcon( NULL, IDI_APPLICATION ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH ); wc.lpszClassName = "OOGL_WINDOW"; wc.style = CS_OWNDC; RegisterClass( &wc ); // Configure window style ulong windowStyle = WS_CAPTION | WS_MINIMIZEBOX | WS_VISIBLE; if ( style & WindowStyle::Close ) windowStyle |= WS_SYSMENU; if ( style & WindowStyle::Resize ) windowStyle |= WS_SYSMENU | WS_THICKFRAME | WS_MAXIMIZEBOX; int x = 0; int y = 0; if ( !( style & WindowStyle::Fullscreen ) ) { // Calculate window size for requested client size RECT rect = { 0, 0, width, height }; AdjustWindowRect( &rect, windowStyle, false ); width = rect.right - rect.left; height = rect.bottom - rect.top; // Center window on screen GetClientRect( GetDesktopWindow(), &rect ); x = ( rect.right - rect.left - width ) / 2; y = ( rect.bottom - rect.top - height ) / 2; } // Create window HWND window = CreateWindow( "OOGL_WINDOW", title.c_str(), windowStyle, x, y, width, height, NULL, NULL, GetModuleHandle( NULL ), this ); // Initialize fullscreen mode if ( style & WindowStyle::Fullscreen ) { DEVMODE dm; dm.dmSize = sizeof( dm ); dm.dmPelsWidth = width; dm.dmPelsHeight = height; dm.dmBitsPerPel = 32; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL; ChangeDisplaySettings( &dm, CDS_FULLSCREEN ); SetWindowLong( window, GWL_STYLE, WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS ); SetWindowLong( window, GWL_EXSTYLE, WS_EX_APPWINDOW ); SetWindowPos( window, HWND_TOP, 0, 0, width, height, SWP_FRAMECHANGED ); ShowWindow( window, SW_SHOW ); } // Initialize window properties RECT rect; GetWindowRect( window, &rect ); this->x = rect.left; this->y = rect.top; GetClientRect( window, &rect ); this->width = rect.right - rect.left; this->height = rect.bottom - rect.top; this->open = true; this->style = windowStyle; this->mousex = 0; this->mousey = 0; memset( this->mouse, 0, sizeof( this->mouse ) ); memset( this->keys, 0, sizeof( this->keys ) ); this->context = 0; } Window::~Window() { if ( context ) delete context; DestroyWindow( window ); UnregisterClass( "OGLWINDOW", GetModuleHandle( NULL ) ); } void Window::SetPos( int x, int y ) { if ( !open ) return; SetWindowPos( window, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER ); } void Window::SetSize( uint width, uint height ) { if ( !open ) return; RECT rect = { 0, 0, width, height }; AdjustWindowRect( &rect, style, false ); SetWindowPos( window, NULL, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOMOVE | SWP_NOZORDER ); } void Window::SetTitle( const std::string& title ) { if ( !open ) return; SetWindowText( window, title.c_str() ); } void Window::SetVisible( bool visible ) { if ( !open ) return; ShowWindow( window, visible ? SW_SHOW : SW_HIDE ); } void Window::Close() { CloseWindow( window ); open = false; } bool Window::GetEvent( Event& ev ) { // Fetch new events MSG msg; while ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } // Return oldest event - if available if ( events.empty() ) return false; ev = events.front(); events.pop(); return true; } Context& Window::GetContext( uchar color, uchar depth, uchar stencil, uchar antialias ) { if ( context ) return *context; else return *( context = new Context( color, depth, stencil, antialias, GetDC( window ) ) ); } void Window::Present() { if ( !context ) return; context->Activate(); SwapBuffers( GetDC( window ) ); } LRESULT Window::WindowEvent( UINT msg, WPARAM wParam, LPARAM lParam ) { Event ev; ev.Type = Event::Unknown; // Translate message to Event switch ( msg ) { case WM_CLOSE: Close(); ev.Type = Event::Close; break; case WM_SIZE: width = GET_X_LPARAM( lParam ); height = GET_Y_LPARAM( lParam ); if ( events.empty() ) { ev.Type = Event::Resize; ev.Window.Width = width; ev.Window.Height = height; } else if ( events.back().Type == Event::Resize ) { events.back().Window.Width = width; events.back().Window.Height = height; } break; case WM_MOVE: RECT rect; GetWindowRect( window, &rect ); x = rect.left; y = rect.top; if ( events.empty() ) { ev.Type = Event::Move; ev.Window.X = x; ev.Window.Y = y; } else if ( events.back().Type == Event::Move ) { events.back().Window.X = x; events.back().Window.Y = y; } break; case WM_ACTIVATE: if ( wParam == WA_INACTIVE ) { ev.Type = Event::Blur; focus = false; } else { ev.Type = Event::Focus; focus = true; } break; case WM_KEYDOWN: case WM_SYSKEYDOWN: ev.Type = Event::KeyDown; ev.Key.Code = TranslateKey( wParam ); ev.Key.Alt = HIWORD( GetAsyncKeyState( VK_MENU ) ) != 0; ev.Key.Control = HIWORD( GetAsyncKeyState( VK_CONTROL ) ) != 0; ev.Key.Shift = HIWORD( GetAsyncKeyState( VK_SHIFT ) ) != 0; keys[ev.Key.Code] = true; break; case WM_KEYUP: case WM_SYSKEYUP: ev.Type = Event::KeyUp; ev.Key.Code = TranslateKey( wParam ); ev.Key.Alt = HIWORD( GetAsyncKeyState( VK_MENU ) ) != 0; ev.Key.Control = HIWORD( GetAsyncKeyState( VK_CONTROL ) ) != 0; ev.Key.Shift = HIWORD( GetAsyncKeyState( VK_SHIFT ) ) != 0; keys[ev.Key.Code] = false; break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); if ( msg == WM_LBUTTONDOWN ) ev.Mouse.Button = MouseButton::Left; else if ( msg == WM_RBUTTONDOWN ) ev.Mouse.Button = MouseButton::Right; else if ( msg == WM_MBUTTONDOWN ) ev.Mouse.Button = MouseButton::Middle; else break; ev.Type = Event::MouseDown; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; mouse[ev.Mouse.Button] = true; break; case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); if ( msg == WM_LBUTTONUP ) ev.Mouse.Button = MouseButton::Left; else if ( msg == WM_RBUTTONUP ) ev.Mouse.Button = MouseButton::Right; else if ( msg == WM_MBUTTONUP ) ev.Mouse.Button = MouseButton::Middle; else break; ev.Type = Event::MouseUp; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; mouse[ev.Mouse.Button] = false; break; case WM_MOUSEWHEEL: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); ev.Type = Event::MouseWheel; ev.Mouse.Delta = GET_WHEEL_DELTA_WPARAM( wParam ) > 0 ? 1 : -1; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; break; case WM_MOUSEMOVE: mousex = GET_X_LPARAM( lParam ); mousey = GET_Y_LPARAM( lParam ); ev.Type = Event::MouseMove; ev.Mouse.X = mousex; ev.Mouse.Y = mousey; break; default: return DefWindowProc( window, msg, wParam, lParam ); } // Add event to internal queue if ( ev.Type != Event::Unknown ) events.push( ev ); return 0; } LRESULT CALLBACK Window::WindowEventHandler( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) { Window* window; if ( msg == WM_NCCREATE ) { // Store pointer to associated Window class as userdata in Win32 window window = reinterpret_cast<Window*>( ( (LPCREATESTRUCT)lParam )->lpCreateParams ); window->window = hwnd; SetWindowLong( hwnd, GWL_USERDATA, reinterpret_cast<long>( window ) ); return DefWindowProc( hwnd, msg, wParam, lParam ); } else { window = reinterpret_cast<Window*>( GetWindowLong( hwnd, GWL_USERDATA ) ); if( window != nullptr ) return window->WindowEvent( msg, wParam, lParam ); else return DefWindowProc( hwnd, msg, wParam, lParam ); } } Key::key_t Window::TranslateKey( uint code ) { switch ( code ) { case VK_SHIFT: return Key::Shift; case VK_MENU: return Key::Alt; case VK_CONTROL: return Key::Control; case VK_OEM_1: return Key::Semicolon; case VK_OEM_2: return Key::Slash; case VK_OEM_PLUS: return Key::Equals; case VK_OEM_MINUS: return Key::Hyphen; case VK_OEM_4: return Key::LeftBracket; case VK_OEM_6: return Key::RightBracket; case VK_OEM_COMMA: return Key::Comma; case VK_OEM_PERIOD: return Key::Period; case VK_OEM_7: return Key::Quote; case VK_OEM_5: return Key::Backslash; case VK_OEM_3: return Key::Tilde; case VK_ESCAPE: return Key::Escape; case VK_SPACE: return Key::Space; case VK_RETURN: return Key::Enter; case VK_BACK: return Key::Backspace; case VK_TAB: return Key::Tab; case VK_PRIOR: return Key::PageUp; case VK_NEXT: return Key::PageDown; case VK_END: return Key::End; case VK_HOME: return Key::Home; case VK_INSERT: return Key::Insert; case VK_DELETE: return Key::Delete; case VK_ADD: return Key::Add; case VK_SUBTRACT: return Key::Subtract; case VK_MULTIPLY: return Key::Multiply; case VK_DIVIDE: return Key::Divide; case VK_PAUSE: return Key::Pause; case VK_LEFT: return Key::Left; case VK_RIGHT: return Key::Right; case VK_UP: return Key::Up; case VK_DOWN: return Key::Down; default: if ( code >= VK_F1 && code <= VK_F12 ) return (Key::key_t)( Key::F1 + code - VK_F1 ); else if ( code >= VK_NUMPAD0 && code <= VK_NUMPAD9 ) return (Key::key_t)( Key::Numpad0 + code - VK_NUMPAD0 ); else if ( code >= 'A' && code <= 'Z' ) return (Key::key_t)( Key::A + code - 'A' ); else if ( code >= '0' && code <= '9' ) return (Key::key_t)( Key::Num0 + code - '0' ); } return Key::Unknown; } } #endif<|endoftext|>
<commit_before>#include "FilterDockWidget.h" #include "Settings.h" #include <QCheckBox> #include <QFileInfo> #include <QFileDialog> #include <QInputDialog> FilterDockWidget::FilterDockWidget(QWidget *parent) : QDockWidget(parent) , ui_() { ui_.setupUi(this); connect(ui_.maf, SIGNAL(valueChanged(double)), this, SIGNAL(filtersChanged())); connect(ui_.maf_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.impact, SIGNAL(currentIndexChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.impact_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.ihdb, SIGNAL(valueChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.ihdb_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.vus, SIGNAL(currentIndexChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.vus_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.geno, SIGNAL(currentIndexChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.geno_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.quality_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.trio_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.important_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.roi_add, SIGNAL(clicked()), this, SLOT(addRoi())); connect(ui_.roi_add_temp, SIGNAL(clicked()), this, SLOT(addRoiTemp())); connect(ui_.roi_remove, SIGNAL(clicked()), this, SLOT(removeRoi())); connect(ui_.rois, SIGNAL(currentIndexChanged(int)), this, SLOT(roiSelectionChanged(int))); connect(ui_.ref_add, SIGNAL(clicked()), this, SLOT(addRef())); connect(ui_.ref_remove, SIGNAL(clicked()), this, SLOT(removeRef())); connect(ui_.refs, SIGNAL(currentIndexChanged(int)), this, SLOT(referenceSampleChanged(int))); connect(ui_.gene, SIGNAL(editingFinished()), this, SLOT(geneChanged())); loadROIFilters(); loadReferenceFiles(); reset(); } void FilterDockWidget::loadROIFilters() { ui_.rois->blockSignals(true); //store old selection QString current = ui_.rois->currentText(); //load from settings ui_.rois->clear(); ui_.rois->addItem("none", ""); QStringList rois = Settings::stringList("target_regions"); rois.sort(); //note: path is included in order! foreach(const QString& roi_file, rois) { QFileInfo info(roi_file); ui_.rois->addItem(info.fileName(), roi_file); } //restore old selection int current_index = ui_.rois->findText(current); if (current_index==-1) current_index = 0; ui_.rois->setCurrentIndex(current_index); ui_.rois->blockSignals(false); } void FilterDockWidget::loadReferenceFiles() { //store old selection QString current = ui_.rois->currentText(); //load from settings ui_.refs->clear(); ui_.refs->addItem("none", ""); QStringList refs = Settings::stringList("reference_files"); foreach(const QString& roi_file, refs) { QStringList parts = roi_file.split("\t"); ui_.refs->addItem(parts[0], parts[1]); } //restore old selection int current_index = ui_.refs->findText(current); if (current_index==-1) current_index = 0; ui_.refs->setCurrentIndex(current_index); } void FilterDockWidget::reset() { blockSignals(true); //annotations ui_.maf_enabled->setChecked(false); ui_.maf->setValue(1.0); ui_.impact_enabled->setChecked(false); ui_.impact->setCurrentText("HIGH,MODERATE,LOW"); ui_.ihdb_enabled->setChecked(false); ui_.ihdb->setValue(5); ui_.vus_enabled->setChecked(false); ui_.vus->setCurrentText("3"); ui_.geno_enabled->setChecked(false); ui_.geno->setCurrentText("hom"); ui_.important_enabled->setChecked(false); ui_.quality_enabled->setChecked(false); ui_.trio_enabled->setChecked(false); //rois ui_.rois->setCurrentIndex(0); ui_.rois->setToolTip(""); //refs ui_.refs->setCurrentIndex(0); ui_.refs->setToolTip(""); //gene last_genes_.clear(); ui_.gene->clear(); blockSignals(false); } void FilterDockWidget::applyDefaultFilters() { //block signals to avoid 10 updates of GUI blockSignals(true); //enable default filters ui_.maf_enabled->setChecked(true); ui_.maf->setValue(1.0); ui_.impact_enabled->setChecked(true); ui_.impact->setCurrentText("HIGH,MODERATE,LOW"); ui_.ihdb_enabled->setChecked(true); ui_.ihdb->setValue(5); ui_.vus_enabled->setChecked(true); ui_.vus->setCurrentText("3"); ui_.geno_enabled->setChecked(false); ui_.geno->setCurrentText("hom"); ui_.important_enabled->setChecked(true); ui_.quality_enabled->setChecked(false); ui_.trio_enabled->setChecked(false); //re-enable signals blockSignals(false); //emit signal to update GUI emit filtersChanged(); } bool FilterDockWidget::applyMaf() const { return ui_.maf_enabled->isChecked(); } double FilterDockWidget::mafPerc() const { return ui_.maf->value(); } bool FilterDockWidget::applyImpact() const { return ui_.impact_enabled->isChecked(); } QStringList FilterDockWidget::impact() const { return ui_.impact->currentText().split(","); } bool FilterDockWidget::applyVus() const { return ui_.vus_enabled->isChecked(); } int FilterDockWidget::vus() const { return ui_.vus->currentText().toInt(); } bool FilterDockWidget::applyGenotype() const { return ui_.geno_enabled->isChecked(); } QString FilterDockWidget::genotype() const { return ui_.geno->currentText(); } bool FilterDockWidget::applyIhdb() const { return ui_.ihdb_enabled->isChecked(); } int FilterDockWidget::ihdb() const { return ui_.ihdb->value(); } bool FilterDockWidget::applyQuality() const { return ui_.quality_enabled->isChecked(); } bool FilterDockWidget::applyTrio() const { return ui_.trio_enabled->isChecked(); } bool FilterDockWidget::keepImportant() const { return ui_.important_enabled->isChecked(); } QString FilterDockWidget::targetRegion() const { return ui_.rois->toolTip(); } QStringList FilterDockWidget::genes() const { QStringList genes = ui_.gene->text().split(',', QString::SkipEmptyParts); for(int i=0; i<genes.count(); ++i) { genes[i] = genes[i].trimmed().toUpper(); } return genes; } QString FilterDockWidget::referenceSample() const { return ui_.refs->toolTip(); } QMap<QString, QString> FilterDockWidget::appliedFilters() const { QMap<QString, QString> output; if (applyMaf()) output.insert("maf", QString::number(mafPerc(), 'f', 2) + "%"); if (applyImpact()) output.insert("impact", impact().join(",")); if (applyIhdb()) output.insert("ihdb", QString::number(ihdb())); if (applyVus()) output.insert("classification", QString::number(vus())); if (applyGenotype()) output.insert("genotype" , genotype()); if (keepImportant()) output.insert("keep_important", ""); if (applyQuality()) output.insert("quality", ""); if (applyTrio()) output.insert("trio", ""); return output; } void FilterDockWidget::addRoi() { //get file to open QString path = Settings::path("path_regions"); QString filename = QFileDialog::getOpenFileName(this, "Select target region file", path, "BED files (*.bed);;All files (*.*)"); if (filename=="") return; //store open path Settings::setPath("path_regions", filename); //update settings QStringList rois = Settings::stringList("target_regions"); rois.append(filename); rois.sort(Qt::CaseInsensitive); rois.removeDuplicates(); Settings::setStringList("target_regions", rois); //update GUI loadROIFilters(); } void FilterDockWidget::addRoiTemp() { //get file to open QString path = Settings::path("path_regions"); QString filename = QFileDialog::getOpenFileName(this, "Select target region file", path, "BED files (*.bed);;All files (*.*)"); if (filename=="") return; //add to list ui_.rois->addItem(QFileInfo(filename).fileName(), filename); } void FilterDockWidget::removeRoi() { QString filename = ui_.rois->itemData(ui_.rois->currentIndex()).toString(); if (filename=="") return; //update settings QStringList rois = Settings::stringList("target_regions"); rois.removeOne(filename); Settings::setStringList("target_regions", rois); //update GUI loadROIFilters(); emit filtersChanged(); } void FilterDockWidget::roiSelectionChanged(int index) { ui_.rois->setToolTip(ui_.rois->itemData(index).toString()); emit filtersChanged(); } void FilterDockWidget::referenceSampleChanged(int index) { ui_.refs->setToolTip(ui_.refs->itemData(index).toString()); } void FilterDockWidget::geneChanged() { if (genes()!=last_genes_) { last_genes_ = genes(); emit filtersChanged(); } } void FilterDockWidget::addRef() { //get file to open QString path = Settings::path("path_variantlists"); QString filename = QFileDialog::getOpenFileName(this, "Select reference file", path, "BAM files (*.bam);;All files (*.*)"); if (filename=="") return; //get name QString name = QInputDialog::getText(this, "Reference file name", "Display name:"); if (name=="") return; //update settings QStringList refs = Settings::stringList("reference_files"); refs.append(name + "\t" + filename); refs.sort(Qt::CaseInsensitive); refs.removeDuplicates(); Settings::setStringList("reference_files", refs); //update GUI loadReferenceFiles(); } void FilterDockWidget::removeRef() { QString name = ui_.refs->itemText(ui_.refs->currentIndex()); QString filename = ui_.refs->itemData(ui_.refs->currentIndex()).toString(); if (filename=="") return; //update settings QStringList refs = Settings::stringList("reference_files"); refs.removeOne(name + "\t" + filename); Settings::setStringList("reference_files", refs); //update GUI loadReferenceFiles(); } <commit_msg>GSvar: fixed target region list sort order.<commit_after>#include "FilterDockWidget.h" #include "Settings.h" #include <QCheckBox> #include <QFileInfo> #include <QFileDialog> #include <QInputDialog> FilterDockWidget::FilterDockWidget(QWidget *parent) : QDockWidget(parent) , ui_() { ui_.setupUi(this); connect(ui_.maf, SIGNAL(valueChanged(double)), this, SIGNAL(filtersChanged())); connect(ui_.maf_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.impact, SIGNAL(currentIndexChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.impact_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.ihdb, SIGNAL(valueChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.ihdb_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.vus, SIGNAL(currentIndexChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.vus_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.geno, SIGNAL(currentIndexChanged(int)), this, SIGNAL(filtersChanged())); connect(ui_.geno_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.quality_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.trio_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.important_enabled, SIGNAL(toggled(bool)), this, SIGNAL(filtersChanged())); connect(ui_.roi_add, SIGNAL(clicked()), this, SLOT(addRoi())); connect(ui_.roi_add_temp, SIGNAL(clicked()), this, SLOT(addRoiTemp())); connect(ui_.roi_remove, SIGNAL(clicked()), this, SLOT(removeRoi())); connect(ui_.rois, SIGNAL(currentIndexChanged(int)), this, SLOT(roiSelectionChanged(int))); connect(ui_.ref_add, SIGNAL(clicked()), this, SLOT(addRef())); connect(ui_.ref_remove, SIGNAL(clicked()), this, SLOT(removeRef())); connect(ui_.refs, SIGNAL(currentIndexChanged(int)), this, SLOT(referenceSampleChanged(int))); connect(ui_.gene, SIGNAL(editingFinished()), this, SLOT(geneChanged())); loadROIFilters(); loadReferenceFiles(); reset(); } void FilterDockWidget::loadROIFilters() { ui_.rois->blockSignals(true); //store old selection QString current = ui_.rois->currentText(); //load from settings ui_.rois->clear(); ui_.rois->addItem("none", ""); QStringList rois = Settings::stringList("target_regions"); std::sort(rois.begin(), rois.end(), [](const QString& a, const QString& b){return QFileInfo(a).fileName().toUpper() < QFileInfo(b).fileName().toUpper();}); foreach(const QString& roi_file, rois) { QFileInfo info(roi_file); ui_.rois->addItem(info.fileName(), roi_file); } //restore old selection int current_index = ui_.rois->findText(current); if (current_index==-1) current_index = 0; ui_.rois->setCurrentIndex(current_index); ui_.rois->blockSignals(false); } void FilterDockWidget::loadReferenceFiles() { //store old selection QString current = ui_.rois->currentText(); //load from settings ui_.refs->clear(); ui_.refs->addItem("none", ""); QStringList refs = Settings::stringList("reference_files"); foreach(const QString& roi_file, refs) { QStringList parts = roi_file.split("\t"); ui_.refs->addItem(parts[0], parts[1]); } //restore old selection int current_index = ui_.refs->findText(current); if (current_index==-1) current_index = 0; ui_.refs->setCurrentIndex(current_index); } void FilterDockWidget::reset() { blockSignals(true); //annotations ui_.maf_enabled->setChecked(false); ui_.maf->setValue(1.0); ui_.impact_enabled->setChecked(false); ui_.impact->setCurrentText("HIGH,MODERATE,LOW"); ui_.ihdb_enabled->setChecked(false); ui_.ihdb->setValue(5); ui_.vus_enabled->setChecked(false); ui_.vus->setCurrentText("3"); ui_.geno_enabled->setChecked(false); ui_.geno->setCurrentText("hom"); ui_.important_enabled->setChecked(false); ui_.quality_enabled->setChecked(false); ui_.trio_enabled->setChecked(false); //rois ui_.rois->setCurrentIndex(0); ui_.rois->setToolTip(""); //refs ui_.refs->setCurrentIndex(0); ui_.refs->setToolTip(""); //gene last_genes_.clear(); ui_.gene->clear(); blockSignals(false); } void FilterDockWidget::applyDefaultFilters() { //block signals to avoid 10 updates of GUI blockSignals(true); //enable default filters ui_.maf_enabled->setChecked(true); ui_.maf->setValue(1.0); ui_.impact_enabled->setChecked(true); ui_.impact->setCurrentText("HIGH,MODERATE,LOW"); ui_.ihdb_enabled->setChecked(true); ui_.ihdb->setValue(5); ui_.vus_enabled->setChecked(true); ui_.vus->setCurrentText("3"); ui_.geno_enabled->setChecked(false); ui_.geno->setCurrentText("hom"); ui_.important_enabled->setChecked(true); ui_.quality_enabled->setChecked(false); ui_.trio_enabled->setChecked(false); //re-enable signals blockSignals(false); //emit signal to update GUI emit filtersChanged(); } bool FilterDockWidget::applyMaf() const { return ui_.maf_enabled->isChecked(); } double FilterDockWidget::mafPerc() const { return ui_.maf->value(); } bool FilterDockWidget::applyImpact() const { return ui_.impact_enabled->isChecked(); } QStringList FilterDockWidget::impact() const { return ui_.impact->currentText().split(","); } bool FilterDockWidget::applyVus() const { return ui_.vus_enabled->isChecked(); } int FilterDockWidget::vus() const { return ui_.vus->currentText().toInt(); } bool FilterDockWidget::applyGenotype() const { return ui_.geno_enabled->isChecked(); } QString FilterDockWidget::genotype() const { return ui_.geno->currentText(); } bool FilterDockWidget::applyIhdb() const { return ui_.ihdb_enabled->isChecked(); } int FilterDockWidget::ihdb() const { return ui_.ihdb->value(); } bool FilterDockWidget::applyQuality() const { return ui_.quality_enabled->isChecked(); } bool FilterDockWidget::applyTrio() const { return ui_.trio_enabled->isChecked(); } bool FilterDockWidget::keepImportant() const { return ui_.important_enabled->isChecked(); } QString FilterDockWidget::targetRegion() const { return ui_.rois->toolTip(); } QStringList FilterDockWidget::genes() const { QStringList genes = ui_.gene->text().split(',', QString::SkipEmptyParts); for(int i=0; i<genes.count(); ++i) { genes[i] = genes[i].trimmed().toUpper(); } return genes; } QString FilterDockWidget::referenceSample() const { return ui_.refs->toolTip(); } QMap<QString, QString> FilterDockWidget::appliedFilters() const { QMap<QString, QString> output; if (applyMaf()) output.insert("maf", QString::number(mafPerc(), 'f', 2) + "%"); if (applyImpact()) output.insert("impact", impact().join(",")); if (applyIhdb()) output.insert("ihdb", QString::number(ihdb())); if (applyVus()) output.insert("classification", QString::number(vus())); if (applyGenotype()) output.insert("genotype" , genotype()); if (keepImportant()) output.insert("keep_important", ""); if (applyQuality()) output.insert("quality", ""); if (applyTrio()) output.insert("trio", ""); return output; } void FilterDockWidget::addRoi() { //get file to open QString path = Settings::path("path_regions"); QString filename = QFileDialog::getOpenFileName(this, "Select target region file", path, "BED files (*.bed);;All files (*.*)"); if (filename=="") return; //store open path Settings::setPath("path_regions", filename); //update settings QStringList rois = Settings::stringList("target_regions"); rois.append(filename); rois.sort(Qt::CaseInsensitive); rois.removeDuplicates(); Settings::setStringList("target_regions", rois); //update GUI loadROIFilters(); } void FilterDockWidget::addRoiTemp() { //get file to open QString path = Settings::path("path_regions"); QString filename = QFileDialog::getOpenFileName(this, "Select target region file", path, "BED files (*.bed);;All files (*.*)"); if (filename=="") return; //add to list ui_.rois->addItem(QFileInfo(filename).fileName(), filename); } void FilterDockWidget::removeRoi() { QString filename = ui_.rois->itemData(ui_.rois->currentIndex()).toString(); if (filename=="") return; //update settings QStringList rois = Settings::stringList("target_regions"); rois.removeOne(filename); Settings::setStringList("target_regions", rois); //update GUI loadROIFilters(); emit filtersChanged(); } void FilterDockWidget::roiSelectionChanged(int index) { ui_.rois->setToolTip(ui_.rois->itemData(index).toString()); emit filtersChanged(); } void FilterDockWidget::referenceSampleChanged(int index) { ui_.refs->setToolTip(ui_.refs->itemData(index).toString()); } void FilterDockWidget::geneChanged() { if (genes()!=last_genes_) { last_genes_ = genes(); emit filtersChanged(); } } void FilterDockWidget::addRef() { //get file to open QString path = Settings::path("path_variantlists"); QString filename = QFileDialog::getOpenFileName(this, "Select reference file", path, "BAM files (*.bam);;All files (*.*)"); if (filename=="") return; //get name QString name = QInputDialog::getText(this, "Reference file name", "Display name:"); if (name=="") return; //update settings QStringList refs = Settings::stringList("reference_files"); refs.append(name + "\t" + filename); refs.sort(Qt::CaseInsensitive); refs.removeDuplicates(); Settings::setStringList("reference_files", refs); //update GUI loadReferenceFiles(); } void FilterDockWidget::removeRef() { QString name = ui_.refs->itemText(ui_.refs->currentIndex()); QString filename = ui_.refs->itemData(ui_.refs->currentIndex()).toString(); if (filename=="") return; //update settings QStringList refs = Settings::stringList("reference_files"); refs.removeOne(name + "\t" + filename); Settings::setStringList("reference_files", refs); //update GUI loadReferenceFiles(); } <|endoftext|>
<commit_before>/** * Copyright (C) 2011 Trever Fischer <[email protected]> * * 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 * 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 Lesser GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "logmodel.h" #include "refreshjob.h" #include "DataModel/subject.h" #include <QtCore/QDebug> #include <QtCore/QUrl> namespace QZeitgeist { LogModel::LogModel(QObject *parent) : QAbstractItemModel(parent) , m_monitor(0) { m_log = new QZeitgeist::Log(this); m_storageState = QZeitgeist::Log::Any; m_range = QZeitgeist::DataModel::TimeRange::always(); m_eventTemplates << QZeitgeist::DataModel::Event(); m_type = QZeitgeist::Log::MostRecentSubjects; m_pool = new QThreadPool(this); } LogModel::~LogModel() { } void LogModel::diffEvents(const QZeitgeist::DataModel::EventList &events) { //TODO: Implement dyanmic programming for a proper diff algorithm. //This probably depends on the datamodel objects not being QObjects. QZeitgeist::DataModel::EventList newEvents = events; QZeitgeist::DataModel::EventList::iterator currentIt = m_events.begin(); QZeitgeist::DataModel::EventList::iterator newIt = newEvents.begin(); int currentRow = 0; while(currentIt != m_events.end() && newIt != newEvents.end()) { if (newIt->id() == currentIt->id()) { newIt++; currentIt++; currentRow++; } else if (newIt->timestamp() >= currentIt->timestamp()) { beginInsertRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.insert(currentIt, *newIt); endInsertRows(); newIt = newEvents.erase(newIt); currentIt++; currentRow++; } else if (newIt->timestamp() < currentIt->timestamp()) { beginRemoveRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.erase(currentIt); endRemoveRows(); } } if (newIt != newEvents.end()) { beginInsertRows(QModelIndex(), currentRow, currentRow+newEvents.size()-1); while(newIt != newEvents.end()) { currentIt = m_events.insert(currentIt, *newIt); currentRow++; currentIt++; newIt++; } endInsertRows(); } if (currentIt != m_events.end()) { beginRemoveRows(QModelIndex(), currentRow, m_events.size()-1); while(currentIt != m_events.end()) { currentIt = m_events.erase(currentIt); } endRemoveRows(); } } void LogModel::refresh() { RefreshJob *refreshJob = new RefreshJob(m_range, m_eventTemplates, m_storageState, 10000, m_type, m_log, this); connect(refreshJob, SIGNAL(done(QZeitgeist::DataModel::EventList)), this, SLOT(refreshDone(QZeitgeist::DataModel::EventList))); m_pool->start(refreshJob); if (m_monitor) m_log->removeMonitor(m_monitor); m_monitor = m_log->installMonitor(m_range, m_eventTemplates); connect(m_monitor, SIGNAL(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList)), this, SLOT(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList))); connect(m_monitor, SIGNAL(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList&)), this, SLOT(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList))); } void LogModel::eventsInserted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(QZeitgeist::DataModel::Event evt, events) { oldEvents << evt; } diffEvents(oldEvents); } void LogModel::eventsDeleted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventIdList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(int id, events) { foreach(QZeitgeist::DataModel::Event evt, oldEvents) { if (evt.id() == id) oldEvents.removeOne(evt); } } diffEvents(oldEvents); } void LogModel::refreshDone(const QZeitgeist::DataModel::EventList &results) { diffEvents(results); } int LogModel::rowCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return m_events.size(); } int LogModel::columnCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return 1; } QModelIndex LogModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } QVariant LogModel::data(const QModelIndex &idx, int role) const { if (idx.isValid() && idx.row() >= 0 && idx.row() < rowCount() && idx.column() == 0) { QZeitgeist::DataModel::Event event = m_events[idx.row()]; switch(role) { case Qt::DisplayRole: return event.subjects()[0].text(); case Qt::DecorationRole: return iconForEvent(event); case EventRole: return QVariant::fromValue<QZeitgeist::DataModel::Event>(event); case TimeRole: return event.timestamp(); case IDRole: return event.id(); case URLRole: return event.subjects()[0].uri(); case MimeRole: return event.subjects()[0].mimeType(); case ActorRole: return event.actor(); default: return QVariant(); } } return QVariant(); } QIcon LogModel::iconForEvent(const QZeitgeist::DataModel::Event &event) const { QUrl actor(event.actor()); QString desktopFile = actor.authority().section('.', 0, 0); if (!m_iconCache.contains(desktopFile)) return QIcon(); return QIcon(m_iconCache[desktopFile]); //return KIcon(m_iconCache[desktopFile], NULL, eventIconOverlays(event)); } QModelIndex LogModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount() && column == 0) return createIndex(row, column); return QModelIndex(); } void LogModel::setRange(const QZeitgeist::DataModel::TimeRange &range) { m_range = range; refresh(); } Qt::ItemFlags LogModel::flags(const QModelIndex &index) const { if (index.isValid() && index.row() >= 0 && index.row() < rowCount() && index.column() == 0) return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return 0; } QStringList LogModel::eventIconOverlays(const QZeitgeist::DataModel::Event &event) const { QStringList overlays; QZeitgeist::DataModel::Subject subject = event.subjects()[0]; /*switch(subject.interpretation()) { case QZeitgeist::Interpretation::Subject::NFOAudio: overlays << "applications-m }*/ QString mime = subject.mimeType(); overlays << mime.replace('/', '-'); return overlays; } QZeitgeist::DataModel::TimeRange LogModel::range() const { return m_range; } void LogModel::setResultType(QZeitgeist::Log::ResultType type) { m_type = type; refresh(); } QZeitgeist::Log::ResultType LogModel::resultType() const { return m_type; } void LogModel::setEventTemplates(const QZeitgeist::DataModel::EventList &templates) { m_eventTemplates = templates; refresh(); } DataModel::EventList LogModel::eventTemplates() const { return m_eventTemplates; } } // namespace QZeitgeist #include "logmodel.moc" <commit_msg>krazy: Use const foreach iterators<commit_after>/** * Copyright (C) 2011 Trever Fischer <[email protected]> * * 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 * 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 Lesser GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "logmodel.h" #include "refreshjob.h" #include "DataModel/subject.h" #include <QtCore/QDebug> #include <QtCore/QUrl> namespace QZeitgeist { LogModel::LogModel(QObject *parent) : QAbstractItemModel(parent) , m_monitor(0) { m_log = new QZeitgeist::Log(this); m_storageState = QZeitgeist::Log::Any; m_range = QZeitgeist::DataModel::TimeRange::always(); m_eventTemplates << QZeitgeist::DataModel::Event(); m_type = QZeitgeist::Log::MostRecentSubjects; m_pool = new QThreadPool(this); } LogModel::~LogModel() { } void LogModel::diffEvents(const QZeitgeist::DataModel::EventList &events) { //TODO: Implement dyanmic programming for a proper diff algorithm. //This probably depends on the datamodel objects not being QObjects. QZeitgeist::DataModel::EventList newEvents = events; QZeitgeist::DataModel::EventList::iterator currentIt = m_events.begin(); QZeitgeist::DataModel::EventList::iterator newIt = newEvents.begin(); int currentRow = 0; while(currentIt != m_events.end() && newIt != newEvents.end()) { if (newIt->id() == currentIt->id()) { newIt++; currentIt++; currentRow++; } else if (newIt->timestamp() >= currentIt->timestamp()) { beginInsertRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.insert(currentIt, *newIt); endInsertRows(); newIt = newEvents.erase(newIt); currentIt++; currentRow++; } else if (newIt->timestamp() < currentIt->timestamp()) { beginRemoveRows(QModelIndex(), currentRow, currentRow); currentIt = m_events.erase(currentIt); endRemoveRows(); } } if (newIt != newEvents.end()) { beginInsertRows(QModelIndex(), currentRow, currentRow+newEvents.size()-1); while(newIt != newEvents.end()) { currentIt = m_events.insert(currentIt, *newIt); currentRow++; currentIt++; newIt++; } endInsertRows(); } if (currentIt != m_events.end()) { beginRemoveRows(QModelIndex(), currentRow, m_events.size()-1); while(currentIt != m_events.end()) { currentIt = m_events.erase(currentIt); } endRemoveRows(); } } void LogModel::refresh() { RefreshJob *refreshJob = new RefreshJob(m_range, m_eventTemplates, m_storageState, 10000, m_type, m_log, this); connect(refreshJob, SIGNAL(done(QZeitgeist::DataModel::EventList)), this, SLOT(refreshDone(QZeitgeist::DataModel::EventList))); m_pool->start(refreshJob); if (m_monitor) m_log->removeMonitor(m_monitor); m_monitor = m_log->installMonitor(m_range, m_eventTemplates); connect(m_monitor, SIGNAL(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList)), this, SLOT(eventsInserted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventList))); connect(m_monitor, SIGNAL(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList&)), this, SLOT(eventsDeleted(QZeitgeist::DataModel::TimeRange,QZeitgeist::DataModel::EventIdList))); } void LogModel::eventsInserted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(const QZeitgeist::DataModel::Event &evt, events) { oldEvents << evt; } diffEvents(oldEvents); } void LogModel::eventsDeleted(const QZeitgeist::DataModel::TimeRange &range, const QZeitgeist::DataModel::EventIdList &events) { QZeitgeist::DataModel::EventList oldEvents = m_events; foreach(int id, events) { foreach(const QZeitgeist::DataModel::Event &evt, oldEvents) { if (evt.id() == id) oldEvents.removeOne(evt); } } diffEvents(oldEvents); } void LogModel::refreshDone(const QZeitgeist::DataModel::EventList &results) { diffEvents(results); } int LogModel::rowCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return m_events.size(); } int LogModel::columnCount(const QModelIndex &idx) const { if (idx.isValid()) return 0; return 1; } QModelIndex LogModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } QVariant LogModel::data(const QModelIndex &idx, int role) const { if (idx.isValid() && idx.row() >= 0 && idx.row() < rowCount() && idx.column() == 0) { QZeitgeist::DataModel::Event event = m_events[idx.row()]; switch(role) { case Qt::DisplayRole: return event.subjects()[0].text(); case Qt::DecorationRole: return iconForEvent(event); case EventRole: return QVariant::fromValue<QZeitgeist::DataModel::Event>(event); case TimeRole: return event.timestamp(); case IDRole: return event.id(); case URLRole: return event.subjects()[0].uri(); case MimeRole: return event.subjects()[0].mimeType(); case ActorRole: return event.actor(); default: return QVariant(); } } return QVariant(); } QIcon LogModel::iconForEvent(const QZeitgeist::DataModel::Event &event) const { QUrl actor(event.actor()); QString desktopFile = actor.authority().section('.', 0, 0); if (!m_iconCache.contains(desktopFile)) return QIcon(); return QIcon(m_iconCache[desktopFile]); //return KIcon(m_iconCache[desktopFile], NULL, eventIconOverlays(event)); } QModelIndex LogModel::index(int row, int column, const QModelIndex &parent) const { if (!parent.isValid() && row >= 0 && row < rowCount() && column == 0) return createIndex(row, column); return QModelIndex(); } void LogModel::setRange(const QZeitgeist::DataModel::TimeRange &range) { m_range = range; refresh(); } Qt::ItemFlags LogModel::flags(const QModelIndex &index) const { if (index.isValid() && index.row() >= 0 && index.row() < rowCount() && index.column() == 0) return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return 0; } QStringList LogModel::eventIconOverlays(const QZeitgeist::DataModel::Event &event) const { QStringList overlays; QZeitgeist::DataModel::Subject subject = event.subjects()[0]; /*switch(subject.interpretation()) { case QZeitgeist::Interpretation::Subject::NFOAudio: overlays << "applications-m }*/ QString mime = subject.mimeType(); overlays << mime.replace('/', '-'); return overlays; } QZeitgeist::DataModel::TimeRange LogModel::range() const { return m_range; } void LogModel::setResultType(QZeitgeist::Log::ResultType type) { m_type = type; refresh(); } QZeitgeist::Log::ResultType LogModel::resultType() const { return m_type; } void LogModel::setEventTemplates(const QZeitgeist::DataModel::EventList &templates) { m_eventTemplates = templates; refresh(); } DataModel::EventList LogModel::eventTemplates() const { return m_eventTemplates; } } // namespace QZeitgeist #include "logmodel.moc" <|endoftext|>
<commit_before>#pragma once /** @file @brief generic function for each N @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <mcl/op.hpp> #include <mcl/util.hpp> #include <cybozu/bit_operation.hpp> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace mcl { namespace fp { template<size_t N> static void shr1T(Unit *y, const Unit *x) { bint::shrT<N>(y, x, 1); } template<size_t N> void addModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::addT<N>(z, x, y)) { bint::subT<N>(z, z, p); return; } Unit tmp[N]; if (bint::subT<N>(tmp, z, p) == 0) { bint::copyT<N>(z, tmp); } } template<size_t N> void addModNFT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { bint::addNFT<N>(z, x, y); Unit tmp[N]; if (bint::subNFT<N>(tmp, z, p) == 0) { bint::copyT<N>(z, tmp); } } template<size_t N> void subModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::subT<N>(z, x, y)) { bint::addT<N>(z, z, p); } } template<size_t N> void subModNFT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::subNFT<N>(z, x, y)) { bint::addNFT<N>(z, z, p); } } // y[N] <- (-x[N]) % p[N] template<size_t N> static void negT(Unit *y, const Unit *x, const Unit *p) { if (bint::isZeroT<N>(x)) { if (x != y) bint::clearT<N>(y); return; } bint::subT<N>(y, p, x); } // z[N + 1] <- x[N] * y template<size_t N> static void mulUnitPreT(Unit *z, const Unit *x, Unit y) { z[N] = bint::mulUnitT<N>(z, x, y); } // z[N] <- (x[N] * y) % p[N] template<size_t N> static void mulUnitModT(Unit *z, const Unit *x, Unit y, const Unit *p) { Unit xy[N + 1]; mulUnitPreT<N>(xy, x, y); size_t n = bint::div(0, 0, xy, N + 1, p, N); bint::copyN(z, xy, n); bint::clearN(z + n, N - n); } // z[N] <- x[N * 2] % p[N] template<size_t N> static void fpDblModT(Unit *y, const Unit *x, const Unit *p) { Unit t[N * 2]; bint::copyN(t, x, N * 2); size_t n = bint::div(0, 0, t, N * 2, p, N); bint::copyN(y, t, n); bint::clearN(y + n, N - n); } // z[N * 2] <- (x[N * 2] + y[N * 2]) mod p[N] << (N * UnitBitSize) template<size_t N> static void fpDblAddModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::addT<N * 2>(z, x, y)) { bint::subT<N>(z + N, z + N, p); return; } Unit tmp[N]; if (bint::subT<N>(tmp, z + N, p) == 0) { bint::copyN(z + N, tmp, N); } } // z[N * 2] <- (x[N * 2] - y[N * 2]) mod p[N] << (N * UnitBitSize) template<size_t N> static void fpDblSubModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::subT<N * 2>(z, x, y)) { bint::addT<N>(z + N, z + N, p); } } /* z[N] <- montRed(xy[N * 2], p[N]) REMARK : assume p[-1] = rp */ template<size_t N> static void modRedT(Unit *z, const Unit *xy, const Unit *p) { const Unit rp = p[-1]; Unit pq[N + 1]; Unit buf[N * 2 + 1]; bint::copyT<N - 1>(buf + N + 1, xy + N + 1); buf[N * 2] = 0; Unit q = xy[0] * rp; pq[N] = bint::mulUnitT<N>(pq, p, q); Unit up = bint::addT<N + 1>(buf, xy, pq); if (up) { buf[N * 2] = bint::addUnit(buf + N + 1, N - 1, 1); } Unit *c = buf + 1; for (size_t i = 1; i < N; i++) { q = c[0] * rp; pq[N] = bint::mulUnitT<N>(pq, p, q); up = bint::addT<N + 1>(c, c, pq); if (up) { bint::addUnit(c + N + 1, N - i, 1); } c++; } if (c[N]) { bint::subT<N>(z, c, p); } else { if (bint::subT<N>(z, c, p)) { bint::copyT<N>(z, c); } } } // [return:z[N+1]] = z[N+1] + x[N] * y + (CF << (N * UnitBitSize)) template<size_t N> Unit mulUnitAddWithCF(Unit z[N + 1], const Unit x[N], Unit y, Unit CF) { Unit H = bint::mulUnitAddT<N>(z, x, y); H += CF; Unit v = z[N]; v += H; z[N] = v; return v < H; } template<size_t N> static void modRedNFT(Unit *z, const Unit *xy, const Unit *p) { const Unit rp = p[-1]; Unit buf[N * 2]; bint::copyT<N * 2>(buf, xy); Unit CF = 0; for (size_t i = 0; i < N; i++) { Unit q = buf[i] * rp; CF = mulUnitAddWithCF<N>(buf + i, p, q, CF); } if (bint::subT<N>(z, buf + N, p)) { bint::copyT<N>(z, buf + N); } } // update z[N + 1] template<size_t N> static Unit mulUnitAddFull(Unit *z, const Unit *x, Unit y) { Unit v1 = z[N]; Unit v2 = v1 + bint::mulUnitAddT<N>(z, x, y); z[N] = v2; return v2 < v1; } /* z[N] <- Montgomery(x[N], y[N], p[N]) REMARK : assume p[-1] = rp */ template<size_t N> static void mulMontT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { const Unit rp = p[-1]; Unit buf[N * 2 + 1]; buf[N] = bint::mulUnitT<N>(buf, x, y[0]); Unit q = buf[0] * rp; buf[N + 1] = mulUnitAddFull<N>(buf, p, q); for (size_t i = 1; i < N; i++) { buf[N + 1 + i] = mulUnitAddFull<N>(buf + i, x, y[i]); q = buf[i] * rp; buf[N + 1 + i] += mulUnitAddFull<N>(buf + i, p, q); } if (buf[N + N]) { bint::subT<N>(z, buf + N, p); } else { if (bint::subT<N>(z, buf + N, p)) { bint::copyT<N>(z, buf + N); } } } template<size_t N> static void mulMontNFT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { const Unit rp = p[-1]; /* R = 1 << 64 L % 64 = 63 ; not full bit F = 1 << (L + 1) max p = (1 << L) - 1 x, y <= p - 1 max x * y[0], p * q <= ((1 << L) - 1)(R - 1) t = x * y[i] + p * q <= 2((1 << L) - 1)(R - 1) = (F - 2)(R - 1) t >> 64 <= (F - 2)(R - 1)/R = (F - 2) - (F - 2)/R t + (t >> 64) = (F - 2)R - (F - 2)/R < FR */ Unit buf[N * 2]; buf[N] = bint::mulUnitT<N>(buf, x, y[0]); Unit q = buf[0] * rp; buf[N] += bint::mulUnitAddT<N>(buf, p, q); for (size_t i = 1; i < N; i++) { buf[N + i] = bint::mulUnitAddT<N>(buf + i, x, y[i]); q = buf[i] * rp; buf[N + i] += bint::mulUnitAddT<N>(buf + i, p, q); } if (bint::subT<N>(z, buf + N, p)) { bint::copyT<N>(z, buf + N); } } // z[N] <- Montgomery(x[N], x[N], p[N]) template<size_t N> static void sqrMontT(Unit *y, const Unit *x, const Unit *p) { mulMontT<N>(y, x, x, p); } template<size_t N> static void sqrMontNFT(Unit *y, const Unit *x, const Unit *p) { mulMontNFT<N>(y, x, x, p); } // z[N] <- (x[N] * y[N]) % p[N] template<size_t N> static void mulModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { Unit xy[N * 2]; bint::mulT<N>(xy, x, y); fpDblModT<N>(z, xy, p); } // y[N] <- (x[N] * x[N]) % p[N] template<size_t N> static void sqrModT(Unit *y, const Unit *x, const Unit *p) { Unit xx[N * 2]; bint::sqrT<N>(xx, x); fpDblModT<N>(y, xx, p); } } } // mcl::fp #ifdef _MSC_VER #pragma warning(pop) #endif <commit_msg>remove c<commit_after>#pragma once /** @file @brief generic function for each N @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <mcl/op.hpp> #include <mcl/util.hpp> #include <cybozu/bit_operation.hpp> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4127) #endif namespace mcl { namespace fp { template<size_t N> static void shr1T(Unit *y, const Unit *x) { bint::shrT<N>(y, x, 1); } template<size_t N> void addModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::addT<N>(z, x, y)) { bint::subT<N>(z, z, p); return; } Unit tmp[N]; if (bint::subT<N>(tmp, z, p) == 0) { bint::copyT<N>(z, tmp); } } template<size_t N> void addModNFT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { bint::addNFT<N>(z, x, y); Unit tmp[N]; if (bint::subNFT<N>(tmp, z, p) == 0) { bint::copyT<N>(z, tmp); } } template<size_t N> void subModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::subT<N>(z, x, y)) { bint::addT<N>(z, z, p); } } template<size_t N> void subModNFT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::subNFT<N>(z, x, y)) { bint::addNFT<N>(z, z, p); } } // y[N] <- (-x[N]) % p[N] template<size_t N> static void negT(Unit *y, const Unit *x, const Unit *p) { if (bint::isZeroT<N>(x)) { if (x != y) bint::clearT<N>(y); return; } bint::subT<N>(y, p, x); } // z[N + 1] <- x[N] * y template<size_t N> static void mulUnitPreT(Unit *z, const Unit *x, Unit y) { z[N] = bint::mulUnitT<N>(z, x, y); } // z[N] <- (x[N] * y) % p[N] template<size_t N> static void mulUnitModT(Unit *z, const Unit *x, Unit y, const Unit *p) { Unit xy[N + 1]; mulUnitPreT<N>(xy, x, y); size_t n = bint::div(0, 0, xy, N + 1, p, N); bint::copyN(z, xy, n); bint::clearN(z + n, N - n); } // z[N] <- x[N * 2] % p[N] template<size_t N> static void fpDblModT(Unit *y, const Unit *x, const Unit *p) { Unit t[N * 2]; bint::copyN(t, x, N * 2); size_t n = bint::div(0, 0, t, N * 2, p, N); bint::copyN(y, t, n); bint::clearN(y + n, N - n); } // z[N * 2] <- (x[N * 2] + y[N * 2]) mod p[N] << (N * UnitBitSize) template<size_t N> static void fpDblAddModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::addT<N * 2>(z, x, y)) { bint::subT<N>(z + N, z + N, p); return; } Unit tmp[N]; if (bint::subT<N>(tmp, z + N, p) == 0) { bint::copyN(z + N, tmp, N); } } // z[N * 2] <- (x[N * 2] - y[N * 2]) mod p[N] << (N * UnitBitSize) template<size_t N> static void fpDblSubModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { if (bint::subT<N * 2>(z, x, y)) { bint::addT<N>(z + N, z + N, p); } } /* z[N] <- montRed(xy[N * 2], p[N]) REMARK : assume p[-1] = rp */ template<size_t N> static void modRedT(Unit *z, const Unit *xy, const Unit *p) { const Unit rp = p[-1]; Unit pq[N + 1]; Unit buf[N * 2 + 1]; bint::copyT<N - 1>(buf + N + 1, xy + N + 1); buf[N * 2] = 0; Unit q = xy[0] * rp; pq[N] = bint::mulUnitT<N>(pq, p, q); Unit CF = bint::addT<N + 1>(buf, xy, pq); if (CF) { buf[N * 2] = bint::addUnit(buf + N + 1, N - 1, 1); } for (size_t i = 1; i < N; i++) { q = buf[i] * rp; pq[N] = bint::mulUnitT<N>(pq, p, q); CF = bint::addT<N + 1>(buf + i, buf + i, pq); if (CF) { bint::addUnit(buf + i + N + 1, N - i, 1); } } if (buf[N + N]) { bint::subT<N>(z, buf + N, p); } else { if (bint::subT<N>(z, buf + N, p)) { bint::copyT<N>(z, buf + N); } } } // [return:z[N+1]] = z[N+1] + x[N] * y + (CF << (N * UnitBitSize)) template<size_t N> Unit mulUnitAddWithCF(Unit z[N + 1], const Unit x[N], Unit y, Unit CF) { Unit H = bint::mulUnitAddT<N>(z, x, y); H += CF; Unit v = z[N]; v += H; z[N] = v; return v < H; } template<size_t N> static void modRedNFT(Unit *z, const Unit *xy, const Unit *p) { const Unit rp = p[-1]; Unit buf[N * 2]; bint::copyT<N * 2>(buf, xy); Unit CF = 0; for (size_t i = 0; i < N; i++) { Unit q = buf[i] * rp; CF = mulUnitAddWithCF<N>(buf + i, p, q, CF); } if (bint::subT<N>(z, buf + N, p)) { bint::copyT<N>(z, buf + N); } } // update z[N + 1] template<size_t N> static Unit mulUnitAddFull(Unit *z, const Unit *x, Unit y) { Unit v1 = z[N]; Unit v2 = v1 + bint::mulUnitAddT<N>(z, x, y); z[N] = v2; return v2 < v1; } /* z[N] <- Montgomery(x[N], y[N], p[N]) REMARK : assume p[-1] = rp */ template<size_t N> static void mulMontT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { const Unit rp = p[-1]; Unit buf[N * 2 + 1]; buf[N] = bint::mulUnitT<N>(buf, x, y[0]); Unit q = buf[0] * rp; buf[N + 1] = mulUnitAddFull<N>(buf, p, q); for (size_t i = 1; i < N; i++) { buf[N + 1 + i] = mulUnitAddFull<N>(buf + i, x, y[i]); q = buf[i] * rp; buf[N + 1 + i] += mulUnitAddFull<N>(buf + i, p, q); } if (buf[N + N]) { bint::subT<N>(z, buf + N, p); } else { if (bint::subT<N>(z, buf + N, p)) { bint::copyT<N>(z, buf + N); } } } template<size_t N> static void mulMontNFT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { const Unit rp = p[-1]; /* R = 1 << 64 L % 64 = 63 ; not full bit F = 1 << (L + 1) max p = (1 << L) - 1 x, y <= p - 1 max x * y[0], p * q <= ((1 << L) - 1)(R - 1) t = x * y[i] + p * q <= 2((1 << L) - 1)(R - 1) = (F - 2)(R - 1) t >> 64 <= (F - 2)(R - 1)/R = (F - 2) - (F - 2)/R t + (t >> 64) = (F - 2)R - (F - 2)/R < FR */ Unit buf[N * 2]; buf[N] = bint::mulUnitT<N>(buf, x, y[0]); Unit q = buf[0] * rp; buf[N] += bint::mulUnitAddT<N>(buf, p, q); for (size_t i = 1; i < N; i++) { buf[N + i] = bint::mulUnitAddT<N>(buf + i, x, y[i]); q = buf[i] * rp; buf[N + i] += bint::mulUnitAddT<N>(buf + i, p, q); } if (bint::subT<N>(z, buf + N, p)) { bint::copyT<N>(z, buf + N); } } // z[N] <- Montgomery(x[N], x[N], p[N]) template<size_t N> static void sqrMontT(Unit *y, const Unit *x, const Unit *p) { mulMontT<N>(y, x, x, p); } template<size_t N> static void sqrMontNFT(Unit *y, const Unit *x, const Unit *p) { mulMontNFT<N>(y, x, x, p); } // z[N] <- (x[N] * y[N]) % p[N] template<size_t N> static void mulModT(Unit *z, const Unit *x, const Unit *y, const Unit *p) { Unit xy[N * 2]; bint::mulT<N>(xy, x, y); fpDblModT<N>(z, xy, p); } // y[N] <- (x[N] * x[N]) % p[N] template<size_t N> static void sqrModT(Unit *y, const Unit *x, const Unit *p) { Unit xx[N * 2]; bint::sqrT<N>(xx, x); fpDblModT<N>(y, xx, p); } } } // mcl::fp #ifdef _MSC_VER #pragma warning(pop) #endif <|endoftext|>
<commit_before>/**************************************************************************** * * This file is part of the QtMediaHub project on http://www.gitorious.org. * * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* * All rights reserved. * * Contact: Nokia Corporation ([email protected])** * * You may use this file under the terms of the BSD license as follows: * * "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 Nokia Corporation and its Subsidiary(-ies) 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 "appstore.h" #include <QDeclarativeComponent> AppStore::AppStore(QDeclarativeItem *parent) : QDeclarativeItem(parent) { installer = new AppInstallerInterface("com.nokia.appstore.installer", "/", QDBusConnection::sessionBus(), this); connect(installer, SIGNAL(installAppFinished(quint32,QString)), this, SIGNAL(installAppFinished(quint32,QString))); connect(installer, SIGNAL(installAppFailed(quint32,QString,QString)), this, SIGNAL(installAppFailed(quint32,QString,QString))); connect(installer, SIGNAL(installAppProgress(quint32,QString,int)), this, SIGNAL(installAppProgress(quint32,QString,int))); connect(installer, SIGNAL(installAppFinished(quint32,QString)), this, SLOT(refresh())); refresh(); } void AppStore::installApp(const QString &name, const QString &appUuidStr, const QString &uri) { installer->installApp(getuid(), appUuidStr, uri, name, 0, QStringList()); } void AppStore::deleteApp(const QString &name, const QString &appUuidStr, bool keepDocuments) { installer->deleteApp(getuid(), appUuidStr, keepDocuments); } void AppStore::refresh() { QDir appsDir("/home/jzellner/projects/qtmediahub/hub/resources/apps/"); appsDir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs | QDir::NoSymLinks); // empty list while (!mApps.isEmpty()) delete mApps.takeFirst(); QDirIterator it(appsDir); while (it.hasNext()) { it.next(); QFileInfo fileInfo= it.fileInfo(); AppInfo *info = readApplicationFolder(fileInfo); if (info) mApps << info; } emit appsChanged(); } AppInfo * AppStore::readApplicationFolder(const QFileInfo &fileInfo) { QFileInfo desktopFile = fileInfo.absoluteFilePath() + "/app.desktop"; if (!desktopFile.exists()) { qDebug("[AppStore] [%s] app.desktop does not exist", fileInfo.absoluteFilePath().toLocal8Bit().constData()); return 0; } QSettings content(desktopFile.absoluteFilePath(), QSettings::IniFormat); // sanity checks if (!content.childGroups().contains("Desktop Entry")) { qDebug("[AppStore] [%s] app.desktop does not seem to be a desktop-file", fileInfo.absoluteFilePath().toLocal8Bit().constData()); return 0; } content.beginGroup("Desktop Entry"); if (!content.contains("Name") || !content.contains("Icon") || !content.contains("Exec")) { qDebug("[AppStore] [%s] app.desktop does not contain needed values", fileInfo.absoluteFilePath().toLocal8Bit().constData()); return 0; } AppInfo *appInfo = new AppInfo(fileInfo.absoluteFilePath() , content.value("Name", "").toString() , content.value("Icon", "").toString() , content.value("Comment", "").toString() , content.value("Version", "").toString() , content.value("Exec", "").toString() , content.value("Uuid", "").toString() , content.value("Categories", "").toString() ); return appInfo; } <commit_msg>appstore: ignore tmp folders<commit_after>/**************************************************************************** * * This file is part of the QtMediaHub project on http://www.gitorious.org. * * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).* * All rights reserved. * * Contact: Nokia Corporation ([email protected])** * * You may use this file under the terms of the BSD license as follows: * * "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 Nokia Corporation and its Subsidiary(-ies) 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 "appstore.h" #include <QDeclarativeComponent> AppStore::AppStore(QDeclarativeItem *parent) : QDeclarativeItem(parent) { installer = new AppInstallerInterface("com.nokia.appstore.installer", "/", QDBusConnection::sessionBus(), this); connect(installer, SIGNAL(installAppFinished(quint32,QString)), this, SIGNAL(installAppFinished(quint32,QString))); connect(installer, SIGNAL(installAppFailed(quint32,QString,QString)), this, SIGNAL(installAppFailed(quint32,QString,QString))); connect(installer, SIGNAL(installAppProgress(quint32,QString,int)), this, SIGNAL(installAppProgress(quint32,QString,int))); connect(installer, SIGNAL(installAppFinished(quint32,QString)), this, SLOT(refresh())); refresh(); } void AppStore::installApp(const QString &name, const QString &appUuidStr, const QString &uri) { installer->installApp(getuid(), appUuidStr, uri, name, 0, QStringList()); } void AppStore::deleteApp(const QString &name, const QString &appUuidStr, bool keepDocuments) { installer->deleteApp(getuid(), appUuidStr, keepDocuments); } void AppStore::refresh() { QDir appsDir("/home/jzellner/projects/qtmediahub/hub/resources/apps/"); appsDir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs | QDir::NoSymLinks); // empty list while (!mApps.isEmpty()) delete mApps.takeFirst(); QDirIterator it(appsDir); while (it.hasNext()) { it.next(); QFileInfo fileInfo = it.fileInfo(); // ignore tmp folders if (fileInfo.fileName().endsWith('-') || fileInfo.fileName().endsWith('+')) continue; AppInfo *info = readApplicationFolder(fileInfo); if (info) mApps << info; } emit appsChanged(); } AppInfo * AppStore::readApplicationFolder(const QFileInfo &fileInfo) { QFileInfo desktopFile = fileInfo.absoluteFilePath() + "/app.desktop"; if (!desktopFile.exists()) { qDebug("[AppStore] [%s] app.desktop does not exist", fileInfo.absoluteFilePath().toLocal8Bit().constData()); return 0; } QSettings content(desktopFile.absoluteFilePath(), QSettings::IniFormat); // sanity checks if (!content.childGroups().contains("Desktop Entry")) { qDebug("[AppStore] [%s] app.desktop does not seem to be a desktop-file", fileInfo.absoluteFilePath().toLocal8Bit().constData()); return 0; } content.beginGroup("Desktop Entry"); if (!content.contains("Name") || !content.contains("Icon") || !content.contains("Exec")) { qDebug("[AppStore] [%s] app.desktop does not contain needed values", fileInfo.absoluteFilePath().toLocal8Bit().constData()); return 0; } AppInfo *appInfo = new AppInfo(fileInfo.absoluteFilePath() , content.value("Name", "").toString() , content.value("Icon", "").toString() , content.value("Comment", "").toString() , content.value("Version", "").toString() , content.value("Exec", "").toString() , content.value("Uuid", "").toString() , content.value("Categories", "").toString() ); return appInfo; } <|endoftext|>
<commit_before>/* Copyright (C) 2008-2016 The Communi Project You may use this file under the terms of BSD license as follows: 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 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 HOLDERS 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 "gnomeplugin.h" #include "gnomemenu.h" #include "x11helper.h" #include "themeinfo.h" #include <QSystemTrayIcon> #include <QMainWindow> #include <QAction> #include <QDebug> #include <QGuiApplication> GnomePlugin::GnomePlugin(QObject* parent) : QObject(parent) { d.mute = 0; d.window = 0; d.theme = 0; d.isActive = (qgetenv("XDG_CURRENT_DESKTOP") == "GNOME"); d.isRunningX11 = (static_cast<QGuiApplication*>(QCoreApplication::instance())->platformName() == "xcb"); } void GnomePlugin::windowCreated(QMainWindow* window) { if (!d.isActive) return; d.window = window; #ifdef COMMUNI_HAVE_GIO GnomeMenu *section1 = new GnomeMenu(window); section1->addSimpleItem("showConnect", "Connect...", window, "doConnect"); section1->addSimpleItem("showSettings", "Settings", window, "showSettings"); section1->addSimpleItem("showHelp", "Help", window, "showHelp"); GnomeMenu *section2 = new GnomeMenu(window); section2->addToggleItem("toggleMute", "Mute", d.mute->isChecked(), d.mute, "toggle"); GnomeMenu *section3 = new GnomeMenu(window); section3->addSimpleItem("quit", "Quit", window, "close"); GnomeMenu *builder = new GnomeMenu(window); builder->addSection(section1); builder->addSection(section2); builder->addSection(section3); builder->setMenuToWindow(window->winId(), "/org/communi/gnomeintegration"); #endif // COMMUNI_HAVE_GIO } void GnomePlugin::windowShowEvent(QMainWindow *, QShowEvent *) { if (!d.isActive) return; if (d.theme) { d.window->createWinId(); themeChanged(*d.theme); } } void GnomePlugin::themeChanged(const ThemeInfo& theme) { if (!d.isActive) return; d.theme = &theme; QByteArray gtkThemeVariant = theme.gtkThemeVariant().toUtf8(); if (d.isRunningX11) { X11Helper::setWindowProperty(d.window->winId(), "_GTK_THEME_VARIANT", gtkThemeVariant); } } void GnomePlugin::setupTrayIcon(QSystemTrayIcon* tray) { if (!d.isActive) return; if (qgetenv("XDG_CURRENT_DESKTOP") != "KDE" && qgetenv("KDE_FULL_SESSION").isEmpty()) tray->setVisible(false); } void GnomePlugin::setupMuteAction(QAction* action) { if (!d.isActive) return; d.mute = action; } <commit_msg>GnomePlugin now sets correct style based on theme variant<commit_after>/* Copyright (C) 2008-2016 The Communi Project You may use this file under the terms of BSD license as follows: 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 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 HOLDERS 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 "gnomeplugin.h" #include "gnomemenu.h" #include "x11helper.h" #include "themeinfo.h" #include <QSystemTrayIcon> #include <QMainWindow> #include <QAction> #include <QDebug> #include <QApplication> #include <QStyleFactory> GnomePlugin::GnomePlugin(QObject* parent) : QObject(parent) { d.mute = 0; d.window = 0; d.theme = 0; d.isActive = (qgetenv("XDG_CURRENT_DESKTOP") == "GNOME"); d.isRunningX11 = (static_cast<QGuiApplication*>(QCoreApplication::instance())->platformName() == "xcb"); } void GnomePlugin::windowCreated(QMainWindow* window) { if (!d.isActive) return; d.window = window; #ifdef COMMUNI_HAVE_GIO GnomeMenu *section1 = new GnomeMenu(window); section1->addSimpleItem("showConnect", "Connect...", window, "doConnect"); section1->addSimpleItem("showSettings", "Settings", window, "showSettings"); section1->addSimpleItem("showHelp", "Help", window, "showHelp"); GnomeMenu *section2 = new GnomeMenu(window); section2->addToggleItem("toggleMute", "Mute", d.mute->isChecked(), d.mute, "toggle"); GnomeMenu *section3 = new GnomeMenu(window); section3->addSimpleItem("quit", "Quit", window, "close"); GnomeMenu *builder = new GnomeMenu(window); builder->addSection(section1); builder->addSection(section2); builder->addSection(section3); builder->setMenuToWindow(window->winId(), "/org/communi/gnomeintegration"); #endif // COMMUNI_HAVE_GIO } void GnomePlugin::windowShowEvent(QMainWindow *, QShowEvent *) { if (!d.isActive) return; if (d.theme) { d.window->createWinId(); themeChanged(*d.theme); } } void GnomePlugin::themeChanged(const ThemeInfo& theme) { if (!d.isActive) return; d.theme = &theme; QByteArray gtkThemeVariant = theme.gtkThemeVariant().toUtf8(); if (d.isRunningX11) { X11Helper::setWindowProperty(d.window->winId(), "_GTK_THEME_VARIANT", gtkThemeVariant); } QStyle *style; if (theme.gtkThemeVariant() == "dark") { style = QStyleFactory::create("adwaita-dark"); } else { style = QStyleFactory::create("adwaita"); } if (style) { QApplication *app = static_cast<QApplication*>(QCoreApplication::instance()); app->setStyle(style); } else { qWarning() << Q_FUNC_INFO << "The Adwaita Qt theme is not present on your system, please install it."; } } void GnomePlugin::setupTrayIcon(QSystemTrayIcon* tray) { if (!d.isActive) return; if (qgetenv("XDG_CURRENT_DESKTOP") != "KDE" && qgetenv("KDE_FULL_SESSION").isEmpty()) tray->setVisible(false); } void GnomePlugin::setupMuteAction(QAction* action) { if (!d.isActive) return; d.mute = action; } <|endoftext|>
<commit_before>/* */ #include "opcn2-library.h" #define CS A2 OPCN2 alpha(CS); void setup(){ Serial.begin(9600); Serial.print("Testing OPC-N2 v"); Serial.println(alpha.firmware_version); delay(1000); alpha.on(); } void loop(){ delay(3000); histogram_data = alpha.histogram(); Serial.println(""); Serial.print("Sampling Period:\t"); Serial.println(values.period); Serial.print("PM1: "); Serial.println(values.pm1); Serial.print("PM2.5: "); Serial.println(values.pm25); Serial.print("PM10: "); Serial.println(values.pm10); } <commit_msg>attempt at bug fix 1<commit_after>/* */ #include "opcn2-library/opcn2-library.h" #define CS A2 OPCN2 alpha(CS); void setup(){ Serial.begin(9600); Serial.print("Testing OPC-N2 v0.0.1"); Serial.println(alpha.firmware_version); delay(1000); alpha.on(); } void loop(){ delay(3000); values = alpha.histogram(); Serial.println(""); Serial.print("Sampling Period:\t"); Serial.println(values.period); Serial.print("PM1: "); Serial.println(values.pm1); Serial.print("PM2.5: "); Serial.println(values.pm25); Serial.print("PM10: "); Serial.println(values.pm10); } <|endoftext|>
<commit_before><commit_msg>BSPFilter now correctly sets a margin based on partition width.<commit_after><|endoftext|>
<commit_before>#include "ast.hpp" #include "syntax.hpp" namespace slip { namespace ast { struct repr_visitor { template<class T> sexpr operator()(const literal<T>& self) const { return self.value; } sexpr operator()(const literal<string>& self) const { return make_ref<string>(self.value); } sexpr operator()(const variable& self) const { return self.name; } sexpr operator()(const ref<lambda>& self) const { return kw::lambda >>= map(self->args, [](symbol s) -> sexpr { return s; }) >>= repr(self->body) >>= sexpr::list(); } sexpr operator()(const ref<application>& self) const { return repr(self->func) >>= map(self->args, [](const expr& e) { return repr(e); }); } template<class T> sexpr operator()(const T& self) const { throw error("unimplemented"); } }; sexpr repr(const expr& self) { return self.map<sexpr>( repr_visitor() ); } std::ostream& operator<<(std::ostream& out, const expr& self) { return out << repr(self); } static expr check_expr(const sexpr& e); using special_type = expr (const sexpr::list& e); static special_type check_lambda, check_application, check_definition, check_condition; static expr check_binding(const sexpr::list&); static const std::map< symbol, special_type* > special = { {kw::lambda, check_lambda}, {kw::def, check_definition}, {kw::cond, check_condition}, {kw::var, check_binding}, }; static expr check_lambda(const sexpr::list& args) { struct fail { }; try { if(size(args) != 2 || !args->head.is<sexpr::list>() ) throw fail(); const list<symbol> vars = map(args->head.get<sexpr::list>(), [&](const sexpr& e) { if(!e.is<symbol>()) throw fail(); return e.get<symbol>(); }); return make_ref<lambda>(vars, check_expr(args->tail->head)); } catch( fail& ) { throw syntax_error("(lambda (`symbol`...) `expr`)"); } } static expr check_application(const sexpr::list& self) { if(!self) { throw syntax_error("empty list in application"); } return make_ref<application>( check_expr(self->head), map(self->tail, [](const sexpr& e) { return check_expr(e); })); } static expr check_definition(const sexpr::list& items) { struct fail { }; try { if( size(items) != 2 ) throw fail(); if( !items->head.is<symbol>() ) throw fail(); return make_ref<definition>(items->head.get<symbol>(), check_expr(items->tail->head)); } catch( fail& ) { throw syntax_error("(def `symbol` `expr`)"); } } static expr check_condition(const sexpr::list& items) { struct fail {}; try{ return make_ref<condition>(map(items, [](const sexpr& e) { if(!e.is<sexpr::list>()) throw fail(); const sexpr::list& lst = e.get<sexpr::list>(); if(size(lst) != 2) throw fail(); return condition::branch(check_expr(lst->head), check_expr(lst->tail->head)); })); } catch( fail ) { throw syntax_error("(cond (`expr` `expr`)...)"); } } struct expr_visitor { template<class T> expr operator()(const T& self) const { return literal<T>{self}; } expr operator()(const symbol& self) const { return variable{self}; } expr operator()(const ref<string>& self) const { return literal<string>{*self}; } expr operator()(const sexpr::list& self) const { if(self && self->head.is<symbol>() ) { auto it = special.find(self->head.get<symbol>()); if(it != special.end()) { return it->second(self->tail); } } return check_application(self); } }; static expr check_expr(const sexpr& e) { return e.map<expr>(expr_visitor()); } static expr check_binding(const sexpr::list& items) { struct fail { }; try { if( size(items) != 2 ) throw fail(); if( !items->head.is<symbol>() ) throw fail(); return make_ref<binding>(items->head.get<symbol>(), check_expr(items->tail->head)); } catch( fail& ) { throw syntax_error("(var `symbol` `expr`)"); } } struct toplevel_visitor : expr_visitor { template<class T> toplevel operator()(const T& self) const { return expr_visitor::operator()(self); } }; toplevel check_toplevel(const sexpr& e) { return e.map<toplevel>(toplevel_visitor()); } std::ostream& operator<<(std::ostream& out, const toplevel& self) { return out << self.get<expr>(); } sexpr repr(const toplevel& self) { return repr(self.get<expr>()); } } } <commit_msg>repr-ing stuff<commit_after>#include "ast.hpp" #include "syntax.hpp" namespace slip { namespace ast { struct repr_visitor { template<class T> sexpr operator()(const literal<T>& self) const { return self.value; } sexpr operator()(const literal<string>& self) const { return make_ref<string>(self.value); } sexpr operator()(const variable& self) const { return self.name; } sexpr operator()(const ref<lambda>& self) const { return kw::lambda >>= map(self->args, [](symbol s) -> sexpr { return s; }) >>= repr(self->body) >>= sexpr::list(); } sexpr operator()(const ref<definition>& self) const { return kw::def >>= self->name >>= repr(self->value) >>= sexpr::list(); } sexpr operator()(const ref<binding>& self) const { return kw::var >>= self->name >>= repr(self->value) >>= sexpr::list(); } sexpr operator()(const ref<sequence>& self) const { return kw::seq >>= map(self->items, [](const expr& e) { return repr(e); }); } sexpr operator()(const ref<condition>& self) const { return kw::cond >>= map(self->branches, [](const condition::branch& b) -> sexpr { return repr(b.test) >>= repr(b.value) >>= sexpr::list(); }); } sexpr operator()(const ref<application>& self) const { return repr(self->func) >>= map(self->args, [](const expr& e) { return repr(e); }); } template<class T> sexpr operator()(const T& self) const { throw error("unimplemented"); } }; sexpr repr(const expr& self) { return self.map<sexpr>( repr_visitor() ); } std::ostream& operator<<(std::ostream& out, const expr& self) { return out << repr(self); } static expr check_expr(const sexpr& e); using special_type = expr (const sexpr::list& e); static special_type check_lambda, check_application, check_definition, check_condition; static expr check_binding(const sexpr::list&); static const std::map< symbol, special_type* > special = { {kw::lambda, check_lambda}, {kw::def, check_definition}, {kw::cond, check_condition}, {kw::var, check_binding}, }; static expr check_lambda(const sexpr::list& args) { struct fail { }; try { if(size(args) != 2 || !args->head.is<sexpr::list>() ) throw fail(); const list<symbol> vars = map(args->head.get<sexpr::list>(), [&](const sexpr& e) { if(!e.is<symbol>()) throw fail(); return e.get<symbol>(); }); return make_ref<lambda>(vars, check_expr(args->tail->head)); } catch( fail& ) { throw syntax_error("(lambda (`symbol`...) `expr`)"); } } static expr check_application(const sexpr::list& self) { if(!self) { throw syntax_error("empty list in application"); } return make_ref<application>( check_expr(self->head), map(self->tail, [](const sexpr& e) { return check_expr(e); })); } static expr check_definition(const sexpr::list& items) { struct fail { }; try { if( size(items) != 2 ) throw fail(); if( !items->head.is<symbol>() ) throw fail(); return make_ref<definition>(items->head.get<symbol>(), check_expr(items->tail->head)); } catch( fail& ) { throw syntax_error("(def `symbol` `expr`)"); } } static expr check_condition(const sexpr::list& items) { struct fail {}; try{ return make_ref<condition>(map(items, [](const sexpr& e) { if(!e.is<sexpr::list>()) throw fail(); const sexpr::list& lst = e.get<sexpr::list>(); if(size(lst) != 2) throw fail(); return condition::branch(check_expr(lst->head), check_expr(lst->tail->head)); })); } catch( fail ) { throw syntax_error("(cond (`expr` `expr`)...)"); } } struct expr_visitor { template<class T> expr operator()(const T& self) const { return literal<T>{self}; } expr operator()(const symbol& self) const { return variable{self}; } expr operator()(const ref<string>& self) const { return literal<string>{*self}; } expr operator()(const sexpr::list& self) const { if(self && self->head.is<symbol>() ) { auto it = special.find(self->head.get<symbol>()); if(it != special.end()) { return it->second(self->tail); } } return check_application(self); } }; static expr check_expr(const sexpr& e) { return e.map<expr>(expr_visitor()); } static expr check_binding(const sexpr::list& items) { struct fail { }; try { if( size(items) != 2 ) throw fail(); if( !items->head.is<symbol>() ) throw fail(); return make_ref<binding>(items->head.get<symbol>(), check_expr(items->tail->head)); } catch( fail& ) { throw syntax_error("(var `symbol` `expr`)"); } } struct toplevel_visitor : expr_visitor { template<class T> toplevel operator()(const T& self) const { return expr_visitor::operator()(self); } }; toplevel check_toplevel(const sexpr& e) { return e.map<toplevel>(toplevel_visitor()); } std::ostream& operator<<(std::ostream& out, const toplevel& self) { return out << self.get<expr>(); } sexpr repr(const toplevel& self) { return repr(self.get<expr>()); } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdarg.h> #include <string.h> #include "disasm.h" #include "dis_tables.h" /* ******************** */ // INSTRUCTION PREFIXES // /* ******************** */ static const unsigned char instruction_has_modrm[512] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ /* ------------------------------- */ /* 00 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 10 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 20 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 30 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 40 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 50 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 60 */ 0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0, /* 70 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 80 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 90 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* A0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* B0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* C0 */ 1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0, /* D0 */ 1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1, /* E0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* F0 */ 0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1, /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ /* ------------------------------- */ 1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,1, /* 0F 00 */ 1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0, /* 0F 10 */ 1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1, /* 0F 20 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0F 30 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 40 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 50 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 60 */ 1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1, /* 0F 70 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0F 80 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 90 */ 0,0,0,1,1,1,0,0,0,0,0,1,1,1,1,1, /* 0F A0 */ 1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1, /* 0F B0 */ 1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0, /* 0F C0 */ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F D0 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F E0 */ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 /* 0F F0 */ /* ------------------------------- */ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ }; /* * Group 1: * * F0h - LOCK * F2h - REPNE/REPZ (used only with string instructions) * F3h - REP or REPE/REPZ (used only with string instructions) * * Group 2 : * * - segment override prefixes * 2Eh - CS segment override * 36h - SS segment override * 3Eh - DS segment override * 26h - ES segment override * 64h - FS segment override * 65h - GS segment override * * - branch hints * 2Eh - branch not taken (branch hint for Jcc instructions only) * 3Eh - branch taken (branch hint for Jcc instructions only) * * Group 3: * * 66h - operand size override prefix * 67h - address size override prefix */ unsigned disassembler::disasm(bx_bool is_32, bx_address base, bx_address ip, Bit8u *instr, char *disbuf) { i32bit_opsize = is_32; i32bit_addrsize = is_32; db_eip = ip; db_base = base; // cs linear base (base for PM & cs<<4 for RM & VM) Bit8u *instruction_begin = instruction = instr; displacement.displ32 = 0; resolve_modrm = NULL; seg_override = NULL; n_prefixes = 0; disbufptr = disbuf; // start sprintf()'ing into beginning of buffer #define SSE_PREFIX_NONE 0 #define SSE_PREFIX_66 1 #define SSE_PREFIX_F2 2 #define SSE_PREFIX_F3 4 /* only one SSE prefix could be used */ static int sse_prefix_index[8] = { 0, 1, 2, -1, 3, -1, -1, -1 }; unsigned sse_prefix = SSE_PREFIX_NONE; int b1; const BxDisasmOpcodeInfo_t *entry; for(;;) { b1 = fetch_byte(); entry = &BxDisasmOpcodes[b1]; if (entry->Attr == _PREFIX) { switch(b1) { case 0xf3: sse_prefix |= SSE_PREFIX_F3; break; case 0xf2: sse_prefix |= SSE_PREFIX_F2; break; case 0x2e: case 0x36: case 0x3e: case 0x26: case 0x64: case 0x65: seg_override = entry->Opcode; break; case 0x66: i32bit_opsize = !i32bit_opsize; sse_prefix |= SSE_PREFIX_66; break; case 0x67: i32bit_addrsize = !i32bit_addrsize; break; case 0xf0: // lock break; default: printf("Internal disassembler error !\n"); return 0; } n_prefixes++; } else break; } if (b1 == 0x0f) { b1 = 0x100 | fetch_byte(); entry = &BxDisasmOpcodes[b1]; } if (instruction_has_modrm[b1]) decode_modrm(); int attr = entry->Attr; while(attr) { switch(attr) { case _GROUPN: entry = &(entry->AnotherArray[nnn]); break; case _GRPSSE: { if(sse_prefix) n_prefixes--; /* For SSE opcodes, look into another 4 entries table with the opcode prefixes (NONE, 0x66, 0xF2, 0xF3) */ int op = sse_prefix_index[sse_prefix]; if (op < 0) return 0; entry = &(entry->AnotherArray[op]); } break; case _SPLIT11B: entry = &(entry->AnotherArray[mod==3]); break; case _GRPFP: if(mod != 3) { entry = &(entry->AnotherArray[nnn]); } else { int index = (b1-0xD8)*64 + (0x3f & modrm); entry = &(BxDisasmOpcodeInfoFP[index]); } break; case _GRP3DNOW: entry = &(BxDisasm3DNowGroup[peek_byte()]); break; default: printf("Internal disassembler error !\n"); return 0; } /* get additional attributes from group table */ attr = entry->Attr; } // print prefixes for(unsigned i=0;i<n_prefixes;i++) { if (*(instr+i) == 0xF3 || *(instr+i) == 0xF2 || *(instr+i) == 0xF0) dis_sprintf("%s ", BxDisasmOpcodes[*(instr+i)].Opcode); if (entry->Op3Attr == BRANCH_HINT) { if (*(instr+i) == 0x2E) dis_sprintf("not taken "); if (*(instr+i) == 0x3E) dis_sprintf("taken "); } } // print instruction disassembly if (intel_mode) print_disassembly_intel(entry); else print_disassembly_att (entry); return(instruction - instruction_begin); } void disassembler::dis_sprintf(char *fmt, ...) { va_list ap; va_start(ap, fmt); vsprintf(disbufptr, fmt, ap); va_end(ap); disbufptr += strlen(disbufptr); } void disassembler::dis_putc(char symbol) { *disbufptr++ = symbol; *disbufptr = 0; } <commit_msg>Fixed handling of duplicate 0x66 and 0x67 prefixes in disasm (h.johanson)<commit_after>#include <stdio.h> #include <stdarg.h> #include <string.h> #include "disasm.h" #include "dis_tables.h" /* ******************** */ // INSTRUCTION PREFIXES // /* ******************** */ static const unsigned char instruction_has_modrm[512] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ /* ------------------------------- */ /* 00 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 10 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 20 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 30 */ 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0, /* 40 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 50 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 60 */ 0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0, /* 70 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 80 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 90 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* A0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* B0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* C0 */ 1,1,0,0,1,1,1,1,0,0,0,0,0,0,0,0, /* D0 */ 1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1, /* E0 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* F0 */ 0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1, /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ /* ------------------------------- */ 1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,1, /* 0F 00 */ 1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0, /* 0F 10 */ 1,1,1,1,1,0,1,0,1,1,1,1,1,1,1,1, /* 0F 20 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0F 30 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 40 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 50 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 60 */ 1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1, /* 0F 70 */ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0F 80 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F 90 */ 0,0,0,1,1,1,0,0,0,0,0,1,1,1,1,1, /* 0F A0 */ 1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1, /* 0F B0 */ 1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0, /* 0F C0 */ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F D0 */ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, /* 0F E0 */ 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0 /* 0F F0 */ /* ------------------------------- */ /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ }; /* * Group 1: * * F0h - LOCK * F2h - REPNE/REPZ (used only with string instructions) * F3h - REP or REPE/REPZ (used only with string instructions) * * Group 2 : * * - segment override prefixes * 2Eh - CS segment override * 36h - SS segment override * 3Eh - DS segment override * 26h - ES segment override * 64h - FS segment override * 65h - GS segment override * * - branch hints * 2Eh - branch not taken (branch hint for Jcc instructions only) * 3Eh - branch taken (branch hint for Jcc instructions only) * * Group 3: * * 66h - operand size override prefix * 67h - address size override prefix */ unsigned disassembler::disasm(bx_bool is_32, bx_address base, bx_address ip, Bit8u *instr, char *disbuf) { i32bit_opsize = is_32; i32bit_addrsize = is_32; db_eip = ip; db_base = base; // cs linear base (base for PM & cs<<4 for RM & VM) Bit8u *instruction_begin = instruction = instr; displacement.displ32 = 0; resolve_modrm = NULL; seg_override = NULL; n_prefixes = 0; disbufptr = disbuf; // start sprintf()'ing into beginning of buffer #define SSE_PREFIX_NONE 0 #define SSE_PREFIX_66 1 #define SSE_PREFIX_F2 2 #define SSE_PREFIX_F3 4 /* only one SSE prefix could be used */ static int sse_prefix_index[8] = { 0, 1, 2, -1, 3, -1, -1, -1 }; unsigned sse_prefix = SSE_PREFIX_NONE; int b1; const BxDisasmOpcodeInfo_t *entry; for(;;) { b1 = fetch_byte(); entry = &BxDisasmOpcodes[b1]; if (entry->Attr == _PREFIX) { switch(b1) { case 0xf3: sse_prefix |= SSE_PREFIX_F3; break; case 0xf2: sse_prefix |= SSE_PREFIX_F2; break; case 0x2e: case 0x36: case 0x3e: case 0x26: case 0x64: case 0x65: seg_override = entry->Opcode; break; case 0x66: i32bit_opsize = !is_32; sse_prefix |= SSE_PREFIX_66; break; case 0x67: i32bit_addrsize = !is_32; break; case 0xf0: // lock break; default: printf("Internal disassembler error !\n"); return 0; } n_prefixes++; } else break; } if (b1 == 0x0f) { b1 = 0x100 | fetch_byte(); entry = &BxDisasmOpcodes[b1]; } if (instruction_has_modrm[b1]) decode_modrm(); int attr = entry->Attr; while(attr) { switch(attr) { case _GROUPN: entry = &(entry->AnotherArray[nnn]); break; case _GRPSSE: { if(sse_prefix) n_prefixes--; /* For SSE opcodes, look into another 4 entries table with the opcode prefixes (NONE, 0x66, 0xF2, 0xF3) */ int op = sse_prefix_index[sse_prefix]; if (op < 0) return 0; entry = &(entry->AnotherArray[op]); } break; case _SPLIT11B: entry = &(entry->AnotherArray[mod==3]); break; case _GRPFP: if(mod != 3) { entry = &(entry->AnotherArray[nnn]); } else { int index = (b1-0xD8)*64 + (0x3f & modrm); entry = &(BxDisasmOpcodeInfoFP[index]); } break; case _GRP3DNOW: entry = &(BxDisasm3DNowGroup[peek_byte()]); break; default: printf("Internal disassembler error !\n"); return 0; } /* get additional attributes from group table */ attr = entry->Attr; } // print prefixes for(unsigned i=0;i<n_prefixes;i++) { if (*(instr+i) == 0xF3 || *(instr+i) == 0xF2 || *(instr+i) == 0xF0) dis_sprintf("%s ", BxDisasmOpcodes[*(instr+i)].Opcode); if (entry->Op3Attr == BRANCH_HINT) { if (*(instr+i) == 0x2E) dis_sprintf("not taken "); if (*(instr+i) == 0x3E) dis_sprintf("taken "); } } // print instruction disassembly if (intel_mode) print_disassembly_intel(entry); else print_disassembly_att (entry); return(instruction - instruction_begin); } void disassembler::dis_sprintf(char *fmt, ...) { va_list ap; va_start(ap, fmt); vsprintf(disbufptr, fmt, ap); va_end(ap); disbufptr += strlen(disbufptr); } void disassembler::dis_putc(char symbol) { *disbufptr++ = symbol; *disbufptr = 0; } <|endoftext|>
<commit_before>#define STB_IMAGE_IMPLEMENTATION #include "stb/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" #include <array> #include <cmath> #include <cstdint> #include <fstream> #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> typedef std::vector<std::pair<float, float>> NoiseVector; typedef std::vector<std::array<float, 3>> PixelVector; typedef std::array<float, 4> ParticleArray; typedef std::vector<ParticleArray> ParticleVector; class PRNG { private: uint64_t mSeed; public: PRNG(uint64_t seed = 12118) : mSeed(seed == 0 ? 1 : seed){}; // seed CANNOT be 0!! float Extents(float extents) { mSeed ^= mSeed >> 12; mSeed ^= mSeed << 25; mSeed ^= mSeed >> 27; return -extents + float(mSeed * UINT64_C(2685821657736338717) * 5.4210105e-20) * (2 * extents); }; }; int main(int argc, char *argv[]) { if (argc != 4) { std::cout << "# Usage: " << argv[0] << " commands.txt noise.png output.png" << std::endl; return 0; } int width, height, channels; unsigned char *noiseTexture = stbi_load(argv[2], &width, &height, &channels, 4); printf("# Loaded: %s [%ix%ix%i]\n", argv[2], width, height, channels); NoiseVector noiseVector; for (int n = 0; n < (width * height); n++) { noiseVector.emplace_back((float)(noiseTexture[n * channels] - 127) / 127.0f, (float)(noiseTexture[n * channels + 1] - 127) / 127.0f); } stbi_image_free(noiseTexture); auto noiseSample = [noiseVector, width, height](float x, float y) { if ((int)x < 0 || (int)x >= width || (int)y < 0 || (int)y >= height) { return std::pair<float, float>{0.0f, 0.0f}; } size_t index = (int)x + (int)y * width; return noiseVector[index]; }; PixelVector hdr; hdr.resize(width * height); const std::string commentString("#"); const std::string particleString("PARTICLE"); const std::string colourString("COLOUR"); const std::string simulateString("SIMULATE"); const std::string tonemapString("TONEMAP"); float red, green, blue; ParticleVector particles; std::ifstream commands(argv[1]); if (!commands.is_open()) { std::cout << "# Failed to open: " << argv[1] << std::endl; return -1; } else { std::cout << "# Commands: " << argv[1] << std::endl; } bool readComms = true; while (readComms) { std::string line; std::getline(commands, line); std::stringstream ss(line); std::string token; ss >> token; if (token.compare(commentString) == 0) { std::cout << line << std::endl; continue; } else if (token.compare(particleString) == 0) { float x, y, vx, vy; ss >> x >> y >> vx >> vy; particles.emplace_back(ParticleArray{x, y, vx, vy}); } else if (token.compare(colourString) == 0) { ss >> red >> green >> blue; } else if (token.compare(simulateString) == 0) { int iterations, stepSampleRate; float damping, noisy, fuzz; ss >> iterations >> stepSampleRate >> damping >> noisy >> fuzz; std::cout << "# Simulating" << std::endl; PRNG prng = PRNG(); for (ParticleArray &p : particles) { for (int i = 0; i < iterations; i++) { float x = p[0]; float y = p[1]; auto noise = noiseSample(x, y); float vx = p[2] * damping + (noise.first * 4.0 * noisy) + prng.Extents(0.1) * fuzz; float vy = p[3] * damping + (noise.second * 4.0 * noisy) + prng.Extents(0.1) * fuzz; float step = 1.0f / stepSampleRate; for (int j = 0; j < stepSampleRate; j++) { x += vx * step; y += vy * step; if ((int)x < 0 || (int)x >= width || (int)y < 0 || (int)y >= height) { break; } size_t index = (int)x + (int)y * width; hdr[index][0] += red; hdr[index][1] += green; hdr[index][2] += blue; } p[0] = x; p[1] = y; p[2] = vx; p[3] = vy; } } particles.clear(); } else if (token.compare(tonemapString) == 0) { float exposure; ss >> exposure; std::cout << "# Tonemapping" << std::endl; auto tonemap = [exposure](float n) { return (unsigned char)((1.0f - std::pow(2.0f, -n * 0.005f * exposure)) * 255); }; std::unique_ptr<unsigned char[]> output(new unsigned char[width * height * channels]); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { size_t index = (x + y * width); output[index * channels] = tonemap(hdr[index][0]); output[index * channels + 1] = tonemap(hdr[index][1]); output[index * channels + 2] = tonemap(hdr[index][2]); output[index * channels + 3] = 255; } } stbi_write_png(argv[3], width, height, channels, output.get(), width * channels); std::cout << "# Saved: " << argv[3] << std::endl; readComms = false; } } commands.close(); return 0; } <commit_msg>In line noise query.<commit_after>#define STB_IMAGE_IMPLEMENTATION #include "stb/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" #include <array> #include <cmath> #include <cstdint> #include <fstream> #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> typedef std::vector<std::pair<float, float>> NoiseVector; typedef std::vector<std::array<float, 3>> PixelVector; typedef std::array<float, 4> ParticleArray; typedef std::vector<ParticleArray> ParticleVector; class PRNG { private: uint64_t mSeed; public: PRNG(uint64_t seed = 12118) : mSeed(seed == 0 ? 1 : seed){}; // seed CANNOT be 0!! float Extents(float extents) { mSeed ^= mSeed >> 12; mSeed ^= mSeed << 25; mSeed ^= mSeed >> 27; return -extents + float(mSeed * UINT64_C(2685821657736338717) * 5.4210105e-20) * (2 * extents); }; }; int main(int argc, char *argv[]) { if (argc != 4) { std::cout << "# Usage: " << argv[0] << " commands.txt noise.png output.png" << std::endl; return 0; } int width, height, channels; unsigned char *noiseTexture = stbi_load(argv[2], &width, &height, &channels, 4); printf("# Loaded: %s [%ix%ix%i]\n", argv[2], width, height, channels); NoiseVector noiseVector(width * height); for (int n = 0; n < (width * height); n++) { noiseVector[n] = {(float)(noiseTexture[n * channels] - 127) / 127.0f, (float)(noiseTexture[n * channels + 1] - 127) / 127.0f}; } stbi_image_free(noiseTexture); PixelVector hdr(width * height); const std::string commentString("#"); const std::string particleString("PARTICLE"); const std::string colourString("COLOUR"); const std::string simulateString("SIMULATE"); const std::string tonemapString("TONEMAP"); float red, green, blue; ParticleVector particles; std::ifstream commands(argv[1]); if (!commands.is_open()) { std::cout << "# Failed to open: " << argv[1] << std::endl; return -1; } else { std::cout << "# Commands: " << argv[1] << std::endl; } bool readComms = true; while (readComms) { std::string line; std::getline(commands, line); std::stringstream ss(line); std::string token; ss >> token; if (token.compare(commentString) == 0) { std::cout << line << std::endl; continue; } else if (token.compare(particleString) == 0) { float x, y, vx, vy; ss >> x >> y >> vx >> vy; particles.emplace_back(ParticleArray{x, y, vx, vy}); } else if (token.compare(colourString) == 0) { ss >> red >> green >> blue; } else if (token.compare(simulateString) == 0) { int iterations, stepSampleRate; float damping, noisy, fuzz; ss >> iterations >> stepSampleRate >> damping >> noisy >> fuzz; std::cout << "# Simulating" << std::endl; PRNG prng = PRNG(); for (const ParticleArray &p : particles) { float x = p[0]; float y = p[1]; float vx = p[2]; float vy = p[3]; size_t index = (int)x + (int)y * width; bool alive = true; for (int i = 0; alive && i < iterations; i++) { vx = vx * damping + (noiseVector[index].first * 4.0 * noisy) + prng.Extents(0.1) * fuzz; vy = vy * damping + (noiseVector[index].second * 4.0 * noisy) + prng.Extents(0.1) * fuzz; float step = 1.0f / stepSampleRate; for (int j = 0; j < stepSampleRate; j++) { x += vx * step; y += vy * step; if ((int)x < 0 || (int)x >= width || (int)y < 0 || (int)y >= height) { alive = false; break; } index = (int)x + (int)y * width; hdr[index][0] += red; hdr[index][1] += green; hdr[index][2] += blue; } } } particles.clear(); } else if (token.compare(tonemapString) == 0) { float exposure; ss >> exposure; std::cout << "# Tonemapping" << std::endl; auto tonemap = [exposure](float n) { return (unsigned char)((1.0f - std::pow(2.0f, -n * 0.005f * exposure)) * 255); }; std::unique_ptr<unsigned char[]> output(new unsigned char[width * height * channels]); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { size_t index = (x + y * width); output[index * channels] = tonemap(hdr[index][0]); output[index * channels + 1] = tonemap(hdr[index][1]); output[index * channels + 2] = tonemap(hdr[index][2]); output[index * channels + 3] = 255; } } stbi_write_png(argv[3], width, height, channels, output.get(), width * channels); std::cout << "# Saved: " << argv[3] << std::endl; readComms = false; } } commands.close(); return 0; } <|endoftext|>
<commit_before>#include <map> #include <phosphor-logging/elog-errors.hpp> #include "xyz/openbmc_project/Common/error.hpp" #include "read_fru_data.hpp" #include "fruread.hpp" #include "host-ipmid/ipmid-api.h" #include "utils.hpp" extern const FruMap frus; namespace ipmi { namespace fru { using namespace phosphor::logging; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; std::unique_ptr<sdbusplus::bus::match_t> matchPtr(nullptr); static constexpr auto INV_INTF = "xyz.openbmc_project.Inventory.Manager"; static constexpr auto OBJ_PATH = "/xyz/openbmc_project/inventory"; static constexpr auto PROP_INTF = "org.freedesktop.DBus.Properties"; namespace cache { //User initiate read FRU info area command followed by //FRU read command. Also data is read in small chunks of //the specified offset and count. //Caching the data which will be invalidated when ever there //is a change in FRU properties. FRUAreaMap fruMap; } /** * @brief Read the property value from Inventory * * @param[in] bus dbus * @param[in] intf Interface * @param[in] propertyName Name of the property * @param[in] path Object path * @return property value */ std::string readProperty(const std::string& intf, const std::string& propertyName, const std::string& path) { sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; auto service = ipmi::getService(bus, INV_INTF, OBJ_PATH); std::string objPath = OBJ_PATH + path; auto method = bus.new_method_call(service.c_str(), objPath.c_str(), PROP_INTF, "Get"); method.append(intf, propertyName); auto reply = bus.call(method); if (reply.is_method_error()) { //If property is not found simply return empty value log<level::INFO>("Property value not set", entry("Property=%s", propertyName), entry("Path=%s", objPath)); return {}; } sdbusplus::message::variant<std::string> property; reply.read(property); std::string value = sdbusplus::message::variant_ns::get<std::string>(property); return value; } void processFruPropChange(sdbusplus::message::message& msg) { if(cache::fruMap.empty()) { return; } std::string path = msg.get_path(); //trim the object base path, if found at the beginning if (path.compare(0, strlen(OBJ_PATH), OBJ_PATH) == 0) { path.erase(0, strlen(OBJ_PATH)); } for (auto& fru : frus) { bool found = false; auto& fruId = fru.first; auto& instanceList = fru.second; for (auto& instance : instanceList) { if(instance.first == path) { found = true; break; } } if (found) { cache::fruMap.erase(fruId); break; } } } //register for fru property change int registerCallbackHandler() { if(matchPtr == nullptr) { using namespace sdbusplus::bus::match::rules; sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; matchPtr = std::make_unique<sdbusplus::bus::match_t>( bus, path_namespace(OBJ_PATH) + type::signal() + member("PropertiesChanged") + interface(PROP_INTF), std::bind(processFruPropChange, std::placeholders::_1)); } return 0; } /** * @brief Read FRU property values from Inventory * * @param[in] fruNum FRU id * @return populate FRU Inventory data */ FruInventoryData readDataFromInventory(const FRUId& fruNum) { auto iter = frus.find(fruNum); if (iter == frus.end()) { log<level::ERR>("Unsupported FRU ID ",entry("FRUID=%d", fruNum)); elog<InternalFailure>(); } FruInventoryData data; auto& instanceList = iter->second; for (auto& instance : instanceList) { for (auto& interfaceList : instance.second) { for (auto& properties : interfaceList.second) { decltype(auto) pdata = properties.second; auto value = readProperty( interfaceList.first, properties.first, instance.first); data[pdata.section].emplace(properties.first, value); } } } return data; } const FruAreaData& getFruAreaData(const FRUId& fruNum) { auto iter = cache::fruMap.find(fruNum); if (iter != cache::fruMap.end()) { return iter->second; } auto invData = readDataFromInventory(fruNum); //Build area info based on inventory data FruAreaData newdata = buildFruAreaData(std::move(invData)); cache::fruMap.emplace(fruNum, std::move(newdata)); return cache::fruMap.at(fruNum); } } //fru } //ipmi <commit_msg>Refactor reading and parsing of inventory data<commit_after>#include <map> #include <phosphor-logging/elog-errors.hpp> #include "xyz/openbmc_project/Common/error.hpp" #include "read_fru_data.hpp" #include "fruread.hpp" #include "host-ipmid/ipmid-api.h" #include "utils.hpp" #include "types.hpp" extern const FruMap frus; namespace ipmi { namespace fru { using namespace phosphor::logging; using InternalFailure = sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; std::unique_ptr<sdbusplus::bus::match_t> matchPtr(nullptr); static constexpr auto INV_INTF = "xyz.openbmc_project.Inventory.Manager"; static constexpr auto OBJ_PATH = "/xyz/openbmc_project/inventory"; static constexpr auto PROP_INTF = "org.freedesktop.DBus.Properties"; namespace cache { //User initiate read FRU info area command followed by //FRU read command. Also data is read in small chunks of //the specified offset and count. //Caching the data which will be invalidated when ever there //is a change in FRU properties. FRUAreaMap fruMap; } /** * @brief Read all the property value's for the specified interface * from Inventory. * * @param[in] intf Interface * @param[in] path Object path * @return map of properties */ ipmi::PropertyMap readAllProperties(const std::string& intf, const std::string& path) { ipmi::PropertyMap properties; sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; auto service = ipmi::getService(bus, INV_INTF, OBJ_PATH); std::string objPath = OBJ_PATH + path; auto method = bus.new_method_call(service.c_str(), objPath.c_str(), PROP_INTF, "GetAll"); method.append(intf); auto reply = bus.call(method); if (reply.is_method_error()) { //If property is not found simply return empty value log<level::ERR>("Error in reading property values from inventory", entry("Interface=%s", intf), entry("Path=%s", objPath)); return properties; } reply.read(properties); return properties; } void processFruPropChange(sdbusplus::message::message& msg) { if(cache::fruMap.empty()) { return; } std::string path = msg.get_path(); //trim the object base path, if found at the beginning if (path.compare(0, strlen(OBJ_PATH), OBJ_PATH) == 0) { path.erase(0, strlen(OBJ_PATH)); } for (auto& fru : frus) { bool found = false; auto& fruId = fru.first; auto& instanceList = fru.second; for (auto& instance : instanceList) { if(instance.first == path) { found = true; break; } } if (found) { cache::fruMap.erase(fruId); break; } } } //register for fru property change int registerCallbackHandler() { if(matchPtr == nullptr) { using namespace sdbusplus::bus::match::rules; sdbusplus::bus::bus bus{ipmid_get_sd_bus_connection()}; matchPtr = std::make_unique<sdbusplus::bus::match_t>( bus, path_namespace(OBJ_PATH) + type::signal() + member("PropertiesChanged") + interface(PROP_INTF), std::bind(processFruPropChange, std::placeholders::_1)); } return 0; } /** * @brief Read FRU property values from Inventory * * @param[in] fruNum FRU id * @return populate FRU Inventory data */ FruInventoryData readDataFromInventory(const FRUId& fruNum) { auto iter = frus.find(fruNum); if (iter == frus.end()) { log<level::ERR>("Unsupported FRU ID ",entry("FRUID=%d", fruNum)); elog<InternalFailure>(); } FruInventoryData data; auto& instanceList = iter->second; for (auto& instance : instanceList) { for (auto& intf : instance.second) { ipmi::PropertyMap allProp = readAllProperties( intf.first, instance.first); for (auto& properties : intf.second) { auto iter = allProp.find(properties.first); if (iter != allProp.end()) { data[properties.second.section].emplace(properties.first, std::move(allProp[properties.first].get<std::string>())); } } } } return data; } const FruAreaData& getFruAreaData(const FRUId& fruNum) { auto iter = cache::fruMap.find(fruNum); if (iter != cache::fruMap.end()) { return iter->second; } auto invData = readDataFromInventory(fruNum); //Build area info based on inventory data FruAreaData newdata = buildFruAreaData(std::move(invData)); cache::fruMap.emplace(fruNum, std::move(newdata)); return cache::fruMap.at(fruNum); } } //fru } //ipmi <|endoftext|>
<commit_before>/** * @file mainpage.hpp * @brief File containing only documentation (for the Doxygen mainpage) * @author Freek Stulp */ /** Namespace used for all classes in the project. */ namespace DmpBBO { } /** \mainpage \section sec_cui_bono What the doxygen documentation is for This is the doxygen documentation of the C++ of the dmpbbo library. Its main aim is to document the C++ API, describe the implemenation, and provide rationale management (see \ref page_design) for developers: \li If you want to get started quickly with the C++ implementation only, the <a href="https://github.com/stulp/dmpbbo/blob/master/demos_cpp">demos</a> would be the right place. \li If you are more interested in the theory behind dynamical movement primitives and their optimization, the <a href="https://github.com/stulp/dmpbbo/blob/master/tutorial">tutorials</a> is the place to go for you. \li If you would like to train function approximators and DMPs, please do so in the Python code, and export the result to json with jsonpickle. This C++ library can read those json files and execute the resulting DMPs. See also the page on <a href="https://github.com/stulp/dmpbbo/blob/master/tutorial/python_cpp.md">Python and C++</a>. \section sec_overview_modules Overview of the modules/libraries This library contains several modules for executing dynamical movement primitives (DMPs). Each module has its own dedicated page. \li \ref eigenutils (in eigenutils/) This header-only module provides utilities for the Eigen matrix library (file IO, (de)serialization with JSON, and checking whether code is real-time). \li \ref page_dyn_sys (in dynamicalsystems/) This module provides implementations of several basic dynamical systems. DMPs are combinations of such systems. \li \ref page_func_approx (in functionapproximators/) This module provides implementations of several function approximators. DMPs use function approximators to learn and reproduce arbitrary smooth movements. \li \ref page_dmp (in dmp/) This module provides an implementation of several types of DMPs. */ /** \page page_design Design Rationale This page explains the overal design rationale for DmpBbo \section sec_remarks General Remarks \li Code legibility is more important to me than absolute execution speed (except for those parts of the code likely to be called in a time-critical context) or using all of the design patterns known to man (that is why I do not use PIMPL; it is not so legible for the uninitiated user. \li I learned to use Eigen whilst coding this project (learning-by-doing). So especially the parts I coded first might have some convoluted solutions (I didn't learn about Eigen::Ref til later...). Any suggestions for making the code more legible or efficient are welcome. \li For the organization of the code (directory structure), I went with this suggestion: http://stackoverflow.com/questions/13521618/c-project-organisation-with-gtest-cmake-and-doxygen/13522826#13522826 \li In function signatures, inputs come first (if they are references, they are const) and then outputs (if they are not const, they are inputs for sure). Exception: if input arguments have default values, they can come after outputs. Virtual functions should not have default function arguments (this is confusing in the derived classes). \section sec_naming Coding style Formatting according to the Google style (https://google.github.io/styleguide/cppguide.html) is done automatically with `clang-format' The only difference to the Google formatting style is that the opening bracket after a function header is on a newline, as this improves legibility for me. See the `.clang-format` settings file in the root of the repo. I mainly follow the following naming style: https://google.github.io/styleguide/cppguide.html#Naming Notes: \li Members end with a _, i.e. <code>this_is_a_member_</code>. (Exception: members in a POD (plain old data) class, which are public, and can be accessed directly) \li I also use this convention: https://google.github.io/styleguide/cppguide.html#Access_Control \li Abbreviation is the root of all evil! Long variable names are meaningful, and thus beautiful. Exceptions to the style guide above: \li functions start with low caps (as in Java, to distinguish them from classes) \li filenames for classes follow the classname (i.e. CamelCased) The PEP Python naming conventions have been followed as much as possible, except for functions, which are camelCased, for consistency with the C++ code. */ /** \page page_todo Todo \todo Documentation: Write a related pages with a table on which functionality is implemented in Python/Cpp \todo Documentation: document Python classes/functions \todo Documentation: Update documentation for parallel (No need for parallel in python, because only decay has been implemented for now) \todo Plotting: setColor on ellipses? \todo delay_cost in C++ not the same as in Python. Take the mean (as in Python) rather than the sum. \todo Check documentation of dmp_bbo_robot \todo demoOptimizationTaskWrapper.py: should there be a Task there also? \todo clean up demoImitationAndOptimization \todo clean up demoOptimizationDmpParallel: remove deprecated, only covar updates matter, make a flag \todo FunctionApproximator::saveGridData in Python also \todo further compare scripts \todo testTrainingCompareCppPython.py => move part of it into demos/python/functionapproximators \todo Table showing which functionality is available in Python/C++ \todo Consistent interfaces and helps for demos (e.g. with argparse) \todo Please note that this doxygen documentation only documents the C++ API of the libraries (in src/), not the demos. For explanations of the demos, please see the md files in the dmpbbo/demos_cpp/ directory. => Are there md files everywhere? \todo What exactly goes in tutorial and what in implementation? \todo Include design rationale for txt files (in design_rationale.md) in dmp_bbo_bbo.md \todo Make Python scripts robust against missing data, e.g. cost_vars \todo Check if true: "An example is given in TaskViapoint, which implements a Task in which the first N columns in cost_vars should represent a N-D trajectory. This convention is respected by TaskSolverDmp, which is able to generate such trajectories." */ /** \defgroup Demos Demos */ /** \page page_demos Demos * * DmpBbo comes with several demos. * * The C++ demos are located in the dmpbbo/demos_cpp/ directory. Please see the README.md files located there. * * Many of the compiled executables are accompanied by a Python wrapper, which calls the executable, and reads the files it writes, and then plots them (yes, I know about Python bindings; this approach allows better debugging of the format of the output files, which should always remain compatible between the C++ and Python versions of DmpBbo). For completeness, the pure Python demos are located in dmpbbo/demos_python. * Please note that this doxygen documentation only documents the C++ API of the libraries (in src/), not the demos. For explanations of the demos, please see the md files in the dmpbbo/demos_cpp/ directory. */ /** \page page_bibliography Bibliography To ensure that all relevant entries are generated for the bibliography, here is a list. \cite buchli11learning \cite ijspeert02movement \cite ijspeert13dynamical \cite kalakrishnan11learning \cite kulvicius12joining \cite matsubara11learning \cite silva12learning \cite stulp12adaptive \cite stulp12path \cite stulp12policy_hal \cite stulp13learning \cite stulp13robot \cite stulp14simultaneous \cite stulp15many */ <commit_msg>Formatting<commit_after>/** * @file mainpage.hpp * @brief File containing only documentation (for the Doxygen mainpage) * @author Freek Stulp */ /** Namespace used for all classes in the project. */ namespace DmpBBO { } /** \mainpage \section sec_cui_bono What the doxygen documentation is for This is the doxygen documentation of the C++ of the dmpbbo library. Its main aim is to document the C++ API, describe the implemenation, and provide rationale management (see \ref page_design) for developers: \li If you want to get started quickly with the C++ implementation only, the <a href="https://github.com/stulp/dmpbbo/blob/master/demos_cpp">demos</a> would be the right place. \li If you are more interested in the theory behind dynamical movement primitives and their optimization, the <a href="https://github.com/stulp/dmpbbo/blob/master/tutorial">tutorials</a> is the place to go for you. \li If you would like to train function approximators and DMPs, please do so in the Python code, and export the result to json with jsonpickle. This C++ library can read those json files and execute the resulting DMPs. See also the page on <a href="https://github.com/stulp/dmpbbo/blob/master/tutorial/python_cpp.md">Python and C++</a>. \section sec_overview_modules Overview of the modules/libraries This library contains several modules for executing dynamical movement primitives (DMPs). Each module has its own dedicated page. \li \ref eigenutils (in eigenutils/) This header-only module provides utilities for the Eigen matrix library (file IO, (de)serialization with JSON, and checking whether code is real-time). \li \ref page_dyn_sys (in dynamicalsystems/) This module provides implementations of several basic dynamical systems. DMPs are combinations of such systems. \li \ref page_func_approx (in functionapproximators/) This module provides implementations of several function approximators. DMPs use function approximators to learn and reproduce arbitrary smooth movements. \li \ref page_dmp (in dmp/) This module provides an implementation of several types of DMPs. */ /** \page page_design Design Rationale This page explains the overal design rationale for DmpBbo \section sec_remarks General Remarks \li Code legibility is more important to me than absolute execution speed (except for those parts of the code likely to be called in a time-critical context) or using all of the design patterns known to man (that is why I do not use PIMPL; it is not so legible for the uninitiated user. \li I learned to use Eigen whilst coding this project (learning-by-doing). So especially the parts I coded first might have some convoluted solutions (I didn't learn about Eigen::Ref til later...). Any suggestions for making the code more legible or efficient are welcome. \li For the organization of the code (directory structure), I went with this suggestion: http://stackoverflow.com/questions/13521618/c-project-organisation-with-gtest-cmake-and-doxygen/13522826#13522826 \li In function signatures, inputs come first (if they are references, they are const) and then outputs (if they are not const, they are inputs for sure). Exception: if input arguments have default values, they can come after outputs. Virtual functions should not have default function arguments (this is confusing in the derived classes). \section sec_naming Coding style Formatting according to the Google style (https://google.github.io/styleguide/cppguide.html) is done automatically with `clang-format' The only difference to the Google formatting style is that the opening bracket after a function header is on a newline, as this improves legibility for me. See the `.clang-format` settings file in the root of the repo. I mainly follow the following naming style: https://google.github.io/styleguide/cppguide.html#Naming Notes: \li Members end with a _, i.e. <code>this_is_a_member_</code>. (Exception: members in a POD (plain old data) class, which are public, and can be accessed directly) \li I also use this convention: https://google.github.io/styleguide/cppguide.html#Access_Control \li Abbreviation is the root of all evil! Long variable names are meaningful, and thus beautiful. Exceptions to the style guide above: \li functions start with low caps (as in Java, to distinguish them from classes) \li filenames for classes follow the classname (i.e. CamelCased) The PEP Python naming conventions have been followed as much as possible, except for functions, which are camelCased, for consistency with the C++ code. */ /** \page page_todo Todo \todo Documentation: Write a related pages with a table on which functionality is implemented in Python/Cpp \todo Documentation: document Python classes/functions \todo Documentation: Update documentation for parallel (No need for parallel in python, because only decay has been implemented for now) \todo Plotting: setColor on ellipses? \todo delay_cost in C++ not the same as in Python. Take the mean (as in Python) rather than the sum. \todo Check documentation of dmp_bbo_robot \todo demoOptimizationTaskWrapper.py: should there be a Task there also? \todo clean up demoImitationAndOptimization \todo clean up demoOptimizationDmpParallel: remove deprecated, only covar updates matter, make a flag \todo FunctionApproximator::saveGridData in Python also \todo further compare scripts \todo testTrainingCompareCppPython.py => move part of it into demos/python/functionapproximators \todo Table showing which functionality is available in Python/C++ \todo Consistent interfaces and helps for demos (e.g. with argparse) \todo Please note that this doxygen documentation only documents the C++ API of the libraries (in src/), not the demos. For explanations of the demos, please see the md files in the dmpbbo/demos_cpp/ directory. => Are there md files everywhere? \todo What exactly goes in tutorial and what in implementation? \todo Include design rationale for txt files (in design_rationale.md) in dmp_bbo_bbo.md \todo Make Python scripts robust against missing data, e.g. cost_vars \todo Check if true: "An example is given in TaskViapoint, which implements a Task in which the first N columns in cost_vars should represent a N-D trajectory. This convention is respected by TaskSolverDmp, which is able to generate such trajectories." */ /** \defgroup Demos Demos */ /** \page page_demos Demos * * DmpBbo comes with several demos. * * The C++ demos are located in the dmpbbo/demos_cpp/ directory. Please see the README.md files located there. * * Many of the compiled executables are accompanied by a Python wrapper, which calls the executable, and reads the files it writes, and then plots them (yes, I know about Python bindings; this approach allows better debugging of the format of the output files, which should always remain compatible between the C++ and Python versions of DmpBbo). For completeness, the pure Python demos are located in dmpbbo/demos_python. * Please note that this doxygen documentation only documents the C++ API of the libraries (in src/), not the demos. For explanations of the demos, please see the md files in the dmpbbo/demos_cpp/ directory. */ /** \page page_bibliography Bibliography To ensure that all relevant entries are generated for the bibliography, here is a list. \cite buchli11learning \cite ijspeert02movement \cite ijspeert13dynamical \cite kalakrishnan11learning \cite kulvicius12joining \cite matsubara11learning \cite silva12learning \cite stulp12adaptive \cite stulp12path \cite stulp12policy_hal \cite stulp13learning \cite stulp13robot \cite stulp14simultaneous \cite stulp15many */ <|endoftext|>
<commit_before>/* * * Copyright 2015-2016, Google 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 Google 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 "test/cpp/qps/qps_worker.h" #include <cassert> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> #include <grpc++/client_context.h> #include <grpc++/security/server_credentials.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/cpu.h> #include <grpc/support/histogram.h> #include <grpc/support/host_port.h> #include <grpc/support/log.h> #include "src/proto/grpc/testing/services.pb.h" #include "test/core/util/grpc_profiler.h" #include "test/cpp/qps/client.h" #include "test/cpp/qps/server.h" #include "test/cpp/util/create_test_channel.h" namespace grpc { namespace testing { static std::unique_ptr<Client> CreateClient(const ClientConfig& config) { gpr_log(GPR_INFO, "Starting client of type %s %s %d", ClientType_Name(config.client_type()).c_str(), RpcType_Name(config.rpc_type()).c_str(), config.payload_config().has_bytebuf_params()); switch (config.client_type()) { case ClientType::SYNC_CLIENT: return (config.rpc_type() == RpcType::UNARY) ? CreateSynchronousUnaryClient(config) : CreateSynchronousStreamingClient(config); case ClientType::ASYNC_CLIENT: return (config.rpc_type() == RpcType::UNARY) ? CreateAsyncUnaryClient(config) : (config.payload_config().has_bytebuf_params() ? CreateGenericAsyncStreamingClient(config) : CreateAsyncStreamingClient(config)); default: abort(); } abort(); } static std::unique_ptr<Server> CreateServer(const ServerConfig& config) { gpr_log(GPR_INFO, "Starting server of type %s", ServerType_Name(config.server_type()).c_str()); switch (config.server_type()) { case ServerType::SYNC_SERVER: return CreateSynchronousServer(config); case ServerType::ASYNC_SERVER: return CreateAsyncServer(config); case ServerType::ASYNC_GENERIC_SERVER: return CreateAsyncGenericServer(config); default: abort(); } abort(); } class ScopedProfile GRPC_FINAL { public: ScopedProfile(const char *filename, bool enable) : enable_(enable) { if (enable_) grpc_profiler_start(filename); } ~ScopedProfile() { if (enable_) grpc_profiler_stop(); } private: const bool enable_; }; class WorkerServiceImpl GRPC_FINAL : public WorkerService::Service { public: WorkerServiceImpl(int server_port, QpsWorker* worker) : acquired_(false), server_port_(server_port), worker_(worker) {} Status RunClient(ServerContext* ctx, ServerReaderWriter<ClientStatus, ClientArgs>* stream) GRPC_OVERRIDE { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, ""); } ScopedProfile profile("qps_client.prof", false); Status ret = RunClientBody(ctx, stream); return ret; } Status RunServer(ServerContext* ctx, ServerReaderWriter<ServerStatus, ServerArgs>* stream) GRPC_OVERRIDE { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, ""); } ScopedProfile profile("qps_server.prof", false); Status ret = RunServerBody(ctx, stream); return ret; } Status CoreCount(ServerContext* ctx, const CoreRequest*, CoreResponse* resp) GRPC_OVERRIDE { resp->set_cores(gpr_cpu_num_cores()); return Status::OK; } Status QuitWorker(ServerContext* ctx, const Void*, Void*) GRPC_OVERRIDE { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, ""); } worker_->MarkDone(); return Status::OK; } private: // Protect against multiple clients using this worker at once. class InstanceGuard { public: InstanceGuard(WorkerServiceImpl* impl) : impl_(impl), acquired_(impl->TryAcquireInstance()) {} ~InstanceGuard() { if (acquired_) { impl_->ReleaseInstance(); } } bool Acquired() const { return acquired_; } private: WorkerServiceImpl* const impl_; const bool acquired_; }; bool TryAcquireInstance() { std::lock_guard<std::mutex> g(mu_); if (acquired_) return false; acquired_ = true; return true; } void ReleaseInstance() { std::lock_guard<std::mutex> g(mu_); GPR_ASSERT(acquired_); acquired_ = false; } Status RunClientBody(ServerContext* ctx, ServerReaderWriter<ClientStatus, ClientArgs>* stream) { ClientArgs args; if (!stream->Read(&args)) { return Status(StatusCode::INVALID_ARGUMENT, ""); } if (!args.has_setup()) { return Status(StatusCode::INVALID_ARGUMENT, ""); } gpr_log(GPR_INFO, "RunClientBody: about to create client"); auto client = CreateClient(args.setup()); if (!client) { return Status(StatusCode::INVALID_ARGUMENT, ""); } gpr_log(GPR_INFO, "RunClientBody: client created"); ClientStatus status; if (!stream->Write(status)) { return Status(StatusCode::UNKNOWN, ""); } gpr_log(GPR_INFO, "RunClientBody: creation status reported"); while (stream->Read(&args)) { gpr_log(GPR_INFO, "RunClientBody: Message read"); if (!args.has_mark()) { gpr_log(GPR_INFO, "RunClientBody: Message is not a mark!"); return Status(StatusCode::INVALID_ARGUMENT, ""); } *status.mutable_stats() = client->Mark(args.mark().reset()); stream->Write(status); gpr_log(GPR_INFO, "RunClientBody: Mark response given"); } gpr_log(GPR_INFO, "RunClientBody: Returning"); return Status::OK; } Status RunServerBody(ServerContext* ctx, ServerReaderWriter<ServerStatus, ServerArgs>* stream) { ServerArgs args; if (!stream->Read(&args)) { return Status(StatusCode::INVALID_ARGUMENT, ""); } if (!args.has_setup()) { return Status(StatusCode::INVALID_ARGUMENT, ""); } if (server_port_ != 0) { args.mutable_setup()->set_port(server_port_); } gpr_log(GPR_INFO, "RunServerBody: about to create server"); auto server = CreateServer(args.setup()); if (!server) { return Status(StatusCode::INVALID_ARGUMENT, ""); } gpr_log(GPR_INFO, "RunServerBody: server created"); ServerStatus status; status.set_port(server->port()); status.set_cores(server->cores()); if (!stream->Write(status)) { return Status(StatusCode::UNKNOWN, ""); } gpr_log(GPR_INFO, "RunServerBody: creation status reported"); while (stream->Read(&args)) { gpr_log(GPR_INFO, "RunServerBody: Message read"); if (!args.has_mark()) { gpr_log(GPR_INFO, "RunServerBody: Message not a mark!"); return Status(StatusCode::INVALID_ARGUMENT, ""); } *status.mutable_stats() = server->Mark(args.mark().reset()); stream->Write(status); gpr_log(GPR_INFO, "RunServerBody: Mark response given"); } gpr_log(GPR_INFO, "RunServerBody: Returning"); return Status::OK; } std::mutex mu_; bool acquired_; int server_port_; QpsWorker* worker_; }; QpsWorker::QpsWorker(int driver_port, int server_port) { impl_.reset(new WorkerServiceImpl(server_port, this)); gpr_atm_rel_store(&done_, static_cast<gpr_atm>(0)); char* server_address = NULL; gpr_join_host_port(&server_address, "::", driver_port); ServerBuilder builder; builder.AddListeningPort(server_address, InsecureServerCredentials()); builder.RegisterService(impl_.get()); gpr_free(server_address); server_ = builder.BuildAndStart(); } QpsWorker::~QpsWorker() {} bool QpsWorker::Done() const { return (gpr_atm_acq_load(&done_) != static_cast<gpr_atm>(0)); } void QpsWorker::MarkDone() { gpr_atm_rel_store(&done_, static_cast<gpr_atm>(1)); } } // namespace testing } // namespace grpc <commit_msg>Fix formatting<commit_after>/* * * Copyright 2015-2016, Google 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 Google 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 "test/cpp/qps/qps_worker.h" #include <cassert> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> #include <grpc++/client_context.h> #include <grpc++/security/server_credentials.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/cpu.h> #include <grpc/support/histogram.h> #include <grpc/support/host_port.h> #include <grpc/support/log.h> #include "src/proto/grpc/testing/services.pb.h" #include "test/core/util/grpc_profiler.h" #include "test/cpp/qps/client.h" #include "test/cpp/qps/server.h" #include "test/cpp/util/create_test_channel.h" namespace grpc { namespace testing { static std::unique_ptr<Client> CreateClient(const ClientConfig& config) { gpr_log(GPR_INFO, "Starting client of type %s %s %d", ClientType_Name(config.client_type()).c_str(), RpcType_Name(config.rpc_type()).c_str(), config.payload_config().has_bytebuf_params()); switch (config.client_type()) { case ClientType::SYNC_CLIENT: return (config.rpc_type() == RpcType::UNARY) ? CreateSynchronousUnaryClient(config) : CreateSynchronousStreamingClient(config); case ClientType::ASYNC_CLIENT: return (config.rpc_type() == RpcType::UNARY) ? CreateAsyncUnaryClient(config) : (config.payload_config().has_bytebuf_params() ? CreateGenericAsyncStreamingClient(config) : CreateAsyncStreamingClient(config)); default: abort(); } abort(); } static std::unique_ptr<Server> CreateServer(const ServerConfig& config) { gpr_log(GPR_INFO, "Starting server of type %s", ServerType_Name(config.server_type()).c_str()); switch (config.server_type()) { case ServerType::SYNC_SERVER: return CreateSynchronousServer(config); case ServerType::ASYNC_SERVER: return CreateAsyncServer(config); case ServerType::ASYNC_GENERIC_SERVER: return CreateAsyncGenericServer(config); default: abort(); } abort(); } class ScopedProfile GRPC_FINAL { public: ScopedProfile(const char* filename, bool enable) : enable_(enable) { if (enable_) grpc_profiler_start(filename); } ~ScopedProfile() { if (enable_) grpc_profiler_stop(); } private: const bool enable_; }; class WorkerServiceImpl GRPC_FINAL : public WorkerService::Service { public: WorkerServiceImpl(int server_port, QpsWorker* worker) : acquired_(false), server_port_(server_port), worker_(worker) {} Status RunClient(ServerContext* ctx, ServerReaderWriter<ClientStatus, ClientArgs>* stream) GRPC_OVERRIDE { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, ""); } ScopedProfile profile("qps_client.prof", false); Status ret = RunClientBody(ctx, stream); return ret; } Status RunServer(ServerContext* ctx, ServerReaderWriter<ServerStatus, ServerArgs>* stream) GRPC_OVERRIDE { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, ""); } ScopedProfile profile("qps_server.prof", false); Status ret = RunServerBody(ctx, stream); return ret; } Status CoreCount(ServerContext* ctx, const CoreRequest*, CoreResponse* resp) GRPC_OVERRIDE { resp->set_cores(gpr_cpu_num_cores()); return Status::OK; } Status QuitWorker(ServerContext* ctx, const Void*, Void*) GRPC_OVERRIDE { InstanceGuard g(this); if (!g.Acquired()) { return Status(StatusCode::RESOURCE_EXHAUSTED, ""); } worker_->MarkDone(); return Status::OK; } private: // Protect against multiple clients using this worker at once. class InstanceGuard { public: InstanceGuard(WorkerServiceImpl* impl) : impl_(impl), acquired_(impl->TryAcquireInstance()) {} ~InstanceGuard() { if (acquired_) { impl_->ReleaseInstance(); } } bool Acquired() const { return acquired_; } private: WorkerServiceImpl* const impl_; const bool acquired_; }; bool TryAcquireInstance() { std::lock_guard<std::mutex> g(mu_); if (acquired_) return false; acquired_ = true; return true; } void ReleaseInstance() { std::lock_guard<std::mutex> g(mu_); GPR_ASSERT(acquired_); acquired_ = false; } Status RunClientBody(ServerContext* ctx, ServerReaderWriter<ClientStatus, ClientArgs>* stream) { ClientArgs args; if (!stream->Read(&args)) { return Status(StatusCode::INVALID_ARGUMENT, ""); } if (!args.has_setup()) { return Status(StatusCode::INVALID_ARGUMENT, ""); } gpr_log(GPR_INFO, "RunClientBody: about to create client"); auto client = CreateClient(args.setup()); if (!client) { return Status(StatusCode::INVALID_ARGUMENT, ""); } gpr_log(GPR_INFO, "RunClientBody: client created"); ClientStatus status; if (!stream->Write(status)) { return Status(StatusCode::UNKNOWN, ""); } gpr_log(GPR_INFO, "RunClientBody: creation status reported"); while (stream->Read(&args)) { gpr_log(GPR_INFO, "RunClientBody: Message read"); if (!args.has_mark()) { gpr_log(GPR_INFO, "RunClientBody: Message is not a mark!"); return Status(StatusCode::INVALID_ARGUMENT, ""); } *status.mutable_stats() = client->Mark(args.mark().reset()); stream->Write(status); gpr_log(GPR_INFO, "RunClientBody: Mark response given"); } gpr_log(GPR_INFO, "RunClientBody: Returning"); return Status::OK; } Status RunServerBody(ServerContext* ctx, ServerReaderWriter<ServerStatus, ServerArgs>* stream) { ServerArgs args; if (!stream->Read(&args)) { return Status(StatusCode::INVALID_ARGUMENT, ""); } if (!args.has_setup()) { return Status(StatusCode::INVALID_ARGUMENT, ""); } if (server_port_ != 0) { args.mutable_setup()->set_port(server_port_); } gpr_log(GPR_INFO, "RunServerBody: about to create server"); auto server = CreateServer(args.setup()); if (!server) { return Status(StatusCode::INVALID_ARGUMENT, ""); } gpr_log(GPR_INFO, "RunServerBody: server created"); ServerStatus status; status.set_port(server->port()); status.set_cores(server->cores()); if (!stream->Write(status)) { return Status(StatusCode::UNKNOWN, ""); } gpr_log(GPR_INFO, "RunServerBody: creation status reported"); while (stream->Read(&args)) { gpr_log(GPR_INFO, "RunServerBody: Message read"); if (!args.has_mark()) { gpr_log(GPR_INFO, "RunServerBody: Message not a mark!"); return Status(StatusCode::INVALID_ARGUMENT, ""); } *status.mutable_stats() = server->Mark(args.mark().reset()); stream->Write(status); gpr_log(GPR_INFO, "RunServerBody: Mark response given"); } gpr_log(GPR_INFO, "RunServerBody: Returning"); return Status::OK; } std::mutex mu_; bool acquired_; int server_port_; QpsWorker* worker_; }; QpsWorker::QpsWorker(int driver_port, int server_port) { impl_.reset(new WorkerServiceImpl(server_port, this)); gpr_atm_rel_store(&done_, static_cast<gpr_atm>(0)); char* server_address = NULL; gpr_join_host_port(&server_address, "::", driver_port); ServerBuilder builder; builder.AddListeningPort(server_address, InsecureServerCredentials()); builder.RegisterService(impl_.get()); gpr_free(server_address); server_ = builder.BuildAndStart(); } QpsWorker::~QpsWorker() {} bool QpsWorker::Done() const { return (gpr_atm_acq_load(&done_) != static_cast<gpr_atm>(0)); } void QpsWorker::MarkDone() { gpr_atm_rel_store(&done_, static_cast<gpr_atm>(1)); } } // namespace testing } // namespace grpc <|endoftext|>
<commit_before>#include "base.h" /////////////////////////////////////////////////////////////////////////////// // Google Test #include "gtest/gtest.h" TEST(TStr, Constructors) { TStr Default; TStr CStr("abc"); TStr OneChar('a'); TStr CopyCStr(CStr); TStr Move(TStr("abc")); TStr ChA(TChA("abc")); TStr SStr(TSStr("abc")); EXPECT_EQ(Default, ""); EXPECT_EQ(CStr, "abc"); EXPECT_EQ(OneChar, "a"); EXPECT_EQ(CopyCStr, "abc"); EXPECT_EQ(Move, "abc"); EXPECT_EQ(ChA, "abc"); EXPECT_EQ(SStr, "abc"); } TEST(TStr, OperatorPlusEquals) { TStr Str = "abc"; TStr Empty; // empyt+= full Empty += Str; EXPECT_EQ(Empty, "abc"); // self+= self Str += Str; EXPECT_EQ(Str, "abcabc"); Str += TStr(); EXPECT_EQ(Str, "abcabc"); // empyt+= full Empty = TStr(); Empty += "abc"; EXPECT_EQ(Empty, "abc"); // full+= empty Str = "abc"; Str += ""; EXPECT_EQ(Str, "abc"); Str = "abc"; Str += nullptr; EXPECT_EQ(Str, "abc"); } TEST(TStr, OperatorComparison) { TStr Str = "abc"; TStr Str2 = "Abc"; TStr Str3 = "abc"; TStr Str4 = "abc "; TStr Empty; // == operator EXPECT_TRUE(Str == Str3); EXPECT_TRUE(Empty == Empty); EXPECT_FALSE(Str == Str2); EXPECT_FALSE(Str == Str4); EXPECT_FALSE(Str == Empty); EXPECT_TRUE(Str == "abc"); EXPECT_TRUE(Empty == ""); EXPECT_FALSE(Str == "Abc"); EXPECT_FALSE(Str == "abc "); EXPECT_FALSE(Str == ""); EXPECT_FALSE(Empty == nullptr); // != operator EXPECT_FALSE(Str != Str3); EXPECT_FALSE(Empty != Empty); EXPECT_TRUE(Str != Str2); EXPECT_TRUE(Str != Str4); EXPECT_TRUE(Str != Empty); EXPECT_FALSE(Str != "abc"); EXPECT_FALSE(Empty != ""); EXPECT_TRUE(Str != "Abc"); EXPECT_TRUE(Str != "abc "); EXPECT_TRUE(Str != ""); EXPECT_TRUE(Empty != nullptr); } TEST(TStr, OperatorIndex) { TStr Str = "abc"; int Len = Str.Len(); TStr Empty; EXPECT_EQ(Str[0], 'a'); EXPECT_EQ(Str[1], 'b'); EXPECT_EQ(Str[2], 'c'); // changing character Str[2] = 'e'; EXPECT_EQ(Str[2], 'e'); EXPECT_EQ(Str.Len(), 3); } TEST(TStr, OperatorPlus) { TStr Str = "abc"; TStr Empty; EXPECT_EQ(Empty + Str, "abc"); EXPECT_EQ(Str + Empty, "abc"); EXPECT_EQ(Empty + "abc", "abc"); EXPECT_EQ(Str + "", "abc"); EXPECT_EQ(Str + nullptr, "abc"); } ///// Counts occurrences of a character between [BChN, end] //int CountCh(const char& Ch, const int& BChN = 0) const; ///// Returns the position of the first occurrence of a character between [BChN, end] //int SearchCh(const char& Ch, const int& BChN = 0) const; ///// Returns the position of the last occurrence of a character between [BChN, end] //int SearchChBack(const char& Ch, int BChN = -1) const; ///// Returns the position of the first occurrence of a (sub)string between [BChN, end] //int SearchStr(const TStr& Str, const int& BChN = 0) const; ///// Returns true if character occurs in string //bool IsChIn(const char& Ch) const { return SearchCh(Ch) != -1; } ///// Returns true if (sub)string occurs in string //bool IsStrIn(const TStr& Str) const { return SearchStr(Str) != -1; } ///// Returns true if this string starts with the prefix c-string //bool StartsWith(const char *Str) const; ///// Returns true if this string starts with the prefix string //bool StartsWith(const TStr& Str) const { return StartsWith(Str.CStr()); } ///// Returns true if this string ends with the sufix c-string //bool EndsWith(const char *Str) const; ///// Returns true if this string ends with the sufix string //bool EndsWith(const TStr& Str) const { return EndsWith(Str.CStr()); }<commit_msg>unit tests<commit_after>#include "base.h" /////////////////////////////////////////////////////////////////////////////// // Google Test #include "gtest/gtest.h" TEST(TStr, Constructors) { TStr Default; TStr CStr("abc"); TStr OneChar('a'); TStr CopyCStr(CStr); TStr Move(TStr("abc")); TStr ChA(TChA("abc")); TStr SStr(TSStr("abc")); EXPECT_EQ(Default, ""); EXPECT_EQ(CStr, "abc"); EXPECT_EQ(OneChar, "a"); EXPECT_EQ(CopyCStr, "abc"); EXPECT_EQ(Move, "abc"); EXPECT_EQ(ChA, "abc"); EXPECT_EQ(SStr, "abc"); } TEST(TStr, OperatorPlusEquals) { TStr Str = "abc"; TStr Empty; // empyt+= full Empty += Str; EXPECT_EQ(Empty, "abc"); // self+= self Str += Str; EXPECT_EQ(Str, "abcabc"); Str += TStr(); EXPECT_EQ(Str, "abcabc"); // empyt+= full Empty = TStr(); Empty += "abc"; EXPECT_EQ(Empty, "abc"); // full+= empty Str = "abc"; Str += ""; EXPECT_EQ(Str, "abc"); Str = "abc"; Str += nullptr; EXPECT_EQ(Str, "abc"); } TEST(TStr, OperatorComparison) { TStr Str = "abc"; TStr Str2 = "Abc"; TStr Str3 = "abc"; TStr Str4 = "abc "; TStr Empty; // == operator EXPECT_TRUE(Str == Str3); EXPECT_TRUE(Empty == Empty); EXPECT_FALSE(Str == Str2); EXPECT_FALSE(Str == Str4); EXPECT_FALSE(Str == Empty); EXPECT_TRUE(Str == "abc"); EXPECT_TRUE(Empty == ""); EXPECT_FALSE(Str == "Abc"); EXPECT_FALSE(Str == "abc "); EXPECT_FALSE(Str == ""); EXPECT_FALSE(Empty == nullptr); // != operator EXPECT_FALSE(Str != Str3); EXPECT_FALSE(Empty != Empty); EXPECT_TRUE(Str != Str2); EXPECT_TRUE(Str != Str4); EXPECT_TRUE(Str != Empty); EXPECT_FALSE(Str != "abc"); EXPECT_FALSE(Empty != ""); EXPECT_TRUE(Str != "Abc"); EXPECT_TRUE(Str != "abc "); EXPECT_TRUE(Str != ""); EXPECT_TRUE(Empty != nullptr); } TEST(TStr, OperatorIndex) { TStr Str = "abc"; int Len = Str.Len(); TStr Empty; EXPECT_EQ(Str[0], 'a'); EXPECT_EQ(Str[1], 'b'); EXPECT_EQ(Str[2], 'c'); // changing character Str[2] = 'e'; EXPECT_EQ(Str[2], 'e'); EXPECT_EQ(Str.Len(), 3); } TEST(TStr, Search) { TStr Str = "abcdaaba"; int Len = Str.Len(); EXPECT_EQ(Str.CountCh('a'), 4); EXPECT_EQ(Str.CountCh('b'), 2); EXPECT_EQ(Str.CountCh('e'), 0); EXPECT_TRUE(Str.IsChIn('a')); EXPECT_TRUE(Str.IsChIn('b')); EXPECT_FALSE(Str.IsChIn('e')); EXPECT_TRUE(Str.IsStrIn(Str)); EXPECT_TRUE(Str.IsStrIn("")); EXPECT_TRUE(Str.IsStrIn("bcd")); EXPECT_TRUE(Str.IsStrIn("ab")); EXPECT_FALSE(Str.IsStrIn("eba")); EXPECT_EQ(Str.CountCh('a', 1), 3); EXPECT_EQ(Str.CountCh('a', 10), 0); EXPECT_EQ(Str.CountCh('b', 2), 1); EXPECT_EQ(Str.CountCh('e', 1), 0); EXPECT_EQ(Str.SearchCh('a'), 0); EXPECT_EQ(Str.SearchCh('b'), 1); EXPECT_EQ(Str.SearchCh('e'), -1); EXPECT_EQ(Str.SearchCh('a', 1), 4); EXPECT_EQ(Str.SearchCh('b', 2), 6); EXPECT_EQ(Str.SearchCh('e', 1), -1); EXPECT_EQ(Str.SearchChBack('a'), Len - 1); EXPECT_EQ(Str.SearchChBack('b'), Len - 2); EXPECT_EQ(Str.SearchChBack('e'), -1); EXPECT_EQ(Str.SearchChBack('a', Len - 2), Len - 3); EXPECT_EQ(Str.SearchChBack('b', Len - 3), 1);; EXPECT_EQ(Str.SearchChBack('e', 3), -1); EXPECT_EQ(Str.SearchStr("a"), 0); EXPECT_EQ(Str.SearchStr("b"), 1); EXPECT_EQ(Str.SearchStr("e"), -1); EXPECT_EQ(Str.SearchStr(""), 0); // TODO: check if this is OK EXPECT_EQ(Str.SearchStr("a", 1), 4); EXPECT_EQ(Str.SearchStr("b", 2), 6); EXPECT_EQ(Str.SearchStr("e", 1), -1); } TEST(TStr, StartsWith) { TStr Str = "abcdef"; EXPECT_TRUE(Str.StartsWith("abc")); EXPECT_TRUE(Str.StartsWith(TStr("abc"))); EXPECT_FALSE(Str.StartsWith("bbc")); EXPECT_FALSE(Str.StartsWith(TStr("bbc"))); // Empty string is a prefix of every string EXPECT_TRUE(Str.StartsWith("")); // starts with empty strin EXPECT_TRUE(Str.StartsWith(TStr())); EXPECT_FALSE(Str.StartsWith("abcdefg")); EXPECT_FALSE(Str.StartsWith("AB")); EXPECT_FALSE(Str.StartsWith("abcdef ")); } TEST(TStr, EndsWith) { TStr Str = "abcdef"; EXPECT_TRUE(Str.EndsWith("def")); EXPECT_TRUE(Str.EndsWith(TStr("def"))); EXPECT_FALSE(Str.EndsWith("ddf")); EXPECT_FALSE(Str.EndsWith(TStr("ddf"))); // Empty string is a suffix of every string EXPECT_TRUE(Str.EndsWith("")); // ends with empty string EXPECT_TRUE(Str.EndsWith(TStr())); // ends with empty string EXPECT_FALSE(Str.EndsWith("aabcdef")); EXPECT_FALSE(Str.EndsWith("EF")); EXPECT_FALSE(Str.EndsWith(" abcdef")); } TEST(TStr, OperatorPlus) { TStr Str = "abc"; TStr Empty; EXPECT_EQ(Empty + Str, "abc"); EXPECT_EQ(Str + Empty, "abc"); EXPECT_EQ(Empty + "abc", "abc"); EXPECT_EQ(Str + "", "abc"); EXPECT_EQ(Str + nullptr, "abc"); } <|endoftext|>
<commit_before>/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 copyright holders 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. * * Authors: Ali Saidi */ #include "mem/tport.hh" void SimpleTimingPort::recvFunctional(PacketPtr pkt) { std::list<PacketPtr>::iterator i = transmitList.begin(); std::list<PacketPtr>::iterator end = transmitList.end(); bool cont = true; while (i != end) { PacketPtr target = *i; // If the target contains data, and it overlaps the // probed request, need to update data if (target->intersect(pkt)) fixPacket(pkt, target); } //Then just do an atomic access and throw away the returned latency if (pkt->result != Packet::Success) recvAtomic(pkt); } bool SimpleTimingPort::recvTiming(PacketPtr pkt) { // If the device is only a slave, it should only be sending // responses, which should never get nacked. There used to be // code to hanldle nacks here, but I'm pretty sure it didn't work // correctly with the drain code, so that would need to be fixed // if we ever added it back. assert(pkt->result != Packet::Nacked); Tick latency = recvAtomic(pkt); // turn packet around to go back to requester if response expected if (pkt->needsResponse()) { pkt->makeTimingResponse(); sendTimingLater(pkt, latency); } else { if (pkt->cmd != Packet::UpgradeReq) { delete pkt->req; delete pkt; } } return true; } void SimpleTimingPort::recvRetry() { assert(outTiming > 0); assert(!transmitList.empty()); if (sendTiming(transmitList.front())) { transmitList.pop_front(); outTiming--; DPRINTF(Bus, "No Longer waiting on retry\n"); if (!transmitList.empty()) sendTimingLater(transmitList.front(), 1); } if (transmitList.empty() && drainEvent) { drainEvent->process(); drainEvent = NULL; } } void SimpleTimingPort::SendEvent::process() { assert(port->outTiming > 0); if (!port->transmitList.empty() && port->transmitList.front() != packet) { //We are not the head of the list port->transmitList.push_back(packet); } else if (port->sendTiming(packet)) { // send successful if (port->transmitList.size()) { port->transmitList.pop_front(); port->outTiming--; if (!port->transmitList.empty()) port->sendTimingLater(port->transmitList.front(), 1); } if (port->transmitList.empty() && port->drainEvent) { port->drainEvent->process(); port->drainEvent = NULL; } } else { // send unsuccessful (due to flow control). Will get retry // callback later; save for then if not already DPRINTF(Bus, "Waiting on retry\n"); if (!(port->transmitList.front() == packet)) port->transmitList.push_back(packet); } } unsigned int SimpleTimingPort::drain(Event *de) { if (outTiming == 0 && transmitList.size() == 0) return 0; drainEvent = de; return 1; } <commit_msg>Get rid of a variable put back by merge.<commit_after>/* * Copyright (c) 2006 The Regents of The University of Michigan * 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 copyright holders 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. * * Authors: Ali Saidi */ #include "mem/tport.hh" void SimpleTimingPort::recvFunctional(PacketPtr pkt) { std::list<PacketPtr>::iterator i = transmitList.begin(); std::list<PacketPtr>::iterator end = transmitList.end(); while (i != end) { PacketPtr target = *i; // If the target contains data, and it overlaps the // probed request, need to update data if (target->intersect(pkt)) fixPacket(pkt, target); } //Then just do an atomic access and throw away the returned latency if (pkt->result != Packet::Success) recvAtomic(pkt); } bool SimpleTimingPort::recvTiming(PacketPtr pkt) { // If the device is only a slave, it should only be sending // responses, which should never get nacked. There used to be // code to hanldle nacks here, but I'm pretty sure it didn't work // correctly with the drain code, so that would need to be fixed // if we ever added it back. assert(pkt->result != Packet::Nacked); Tick latency = recvAtomic(pkt); // turn packet around to go back to requester if response expected if (pkt->needsResponse()) { pkt->makeTimingResponse(); sendTimingLater(pkt, latency); } else { if (pkt->cmd != Packet::UpgradeReq) { delete pkt->req; delete pkt; } } return true; } void SimpleTimingPort::recvRetry() { assert(outTiming > 0); assert(!transmitList.empty()); if (sendTiming(transmitList.front())) { transmitList.pop_front(); outTiming--; DPRINTF(Bus, "No Longer waiting on retry\n"); if (!transmitList.empty()) sendTimingLater(transmitList.front(), 1); } if (transmitList.empty() && drainEvent) { drainEvent->process(); drainEvent = NULL; } } void SimpleTimingPort::SendEvent::process() { assert(port->outTiming > 0); if (!port->transmitList.empty() && port->transmitList.front() != packet) { //We are not the head of the list port->transmitList.push_back(packet); } else if (port->sendTiming(packet)) { // send successful if (port->transmitList.size()) { port->transmitList.pop_front(); port->outTiming--; if (!port->transmitList.empty()) port->sendTimingLater(port->transmitList.front(), 1); } if (port->transmitList.empty() && port->drainEvent) { port->drainEvent->process(); port->drainEvent = NULL; } } else { // send unsuccessful (due to flow control). Will get retry // callback later; save for then if not already DPRINTF(Bus, "Waiting on retry\n"); if (!(port->transmitList.front() == packet)) port->transmitList.push_back(packet); } } unsigned int SimpleTimingPort::drain(Event *de) { if (outTiming == 0 && transmitList.size() == 0) return 0; drainEvent = de; return 1; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: evntpost.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 12:14:02 $ * * 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_vcl.hxx" #include "evntpost.hxx" #include "svapp.hxx" namespace vcl { EventPoster::EventPoster( const Link& rLink ) : m_aLink(rLink) { m_nId = 0; } EventPoster::~EventPoster() { if ( m_nId ) GetpApp()->RemoveUserEvent( m_nId ); } void EventPoster::Post( UserEvent* pEvent ) { m_nId = GetpApp()->PostUserEvent( ( LINK( this, EventPoster, DoEvent_Impl ) ), pEvent ); } IMPL_LINK_INLINE_START( EventPoster, DoEvent_Impl, UserEvent*, pEvent ) { m_nId = 0; m_aLink.Call( pEvent ); return 0; } IMPL_LINK_INLINE_END( EventPoster, DoEvent_Impl, UserEvent*, pEvent ) } <commit_msg>INTEGRATION: CWS vgbugs07 (1.6.240); FILE MERGED 2007/06/04 13:29:45 vg 1.6.240.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: evntpost.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-06-27 20:26:30 $ * * 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_vcl.hxx" #include <vcl/evntpost.hxx> #include <vcl/svapp.hxx> namespace vcl { EventPoster::EventPoster( const Link& rLink ) : m_aLink(rLink) { m_nId = 0; } EventPoster::~EventPoster() { if ( m_nId ) GetpApp()->RemoveUserEvent( m_nId ); } void EventPoster::Post( UserEvent* pEvent ) { m_nId = GetpApp()->PostUserEvent( ( LINK( this, EventPoster, DoEvent_Impl ) ), pEvent ); } IMPL_LINK_INLINE_START( EventPoster, DoEvent_Impl, UserEvent*, pEvent ) { m_nId = 0; m_aLink.Call( pEvent ); return 0; } IMPL_LINK_INLINE_END( EventPoster, DoEvent_Impl, UserEvent*, pEvent ) } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: atkbridge.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2006-05-05 10:53:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <plugins/gtk/atkbridge.hxx> #include <plugins/gtk/gtkframe.hxx> #include "atkfactory.hxx" #include "atkutil.hxx" #include "atkwindow.hxx" #include <stdio.h> #if ! ( defined AIX || defined HPUX ) // these have no dl* functions #include <dlfcn.h> #endif void InitAtkBridge(void) { unsigned int major, minor, micro; /* check gail minimum version requirements */ if( sscanf( atk_get_toolkit_version(), "%u.%u.%u", &major, &minor, &micro) < 3 ) { g_warning( "unable to parse gail version number" ); return; } if( ( (major << 16) | (minor << 8) | micro ) < ( (1 << 16) | 8 << 8 | 6 ) ) { g_warning( "libgail >= 1.8.6 required for accessibility support" ); return; } /* get at-spi version by checking the libspi.so version number */ #if ! ( defined AIX || defined HPUX ) // these have no dl* functions /* libspi should be mapped by loading libatk-bridge.so already */ void * sym = dlsym( RTLD_DEFAULT, "spi_accessible_new" ); g_return_if_fail( sym != NULL ); Dl_info dl_info; int ret = dladdr( sym, &dl_info ); g_return_if_fail( ret != 0 ); char path[PATH_MAX]; if( NULL == realpath(dl_info.dli_fname, path) ) { perror( "unable to resolve libspi.so.0" ); return; } const char * cp = strrchr(path, '/'); if( cp != NULL ) ++cp; else cp = dl_info.dli_fname; if( sscanf( cp, "libspi.so.%u.%u.%u", &major, &minor, &micro) < 3 ) { g_warning( "unable to parse at-spi version number: %s", cp ); return; } if( ( (major << 16) | (minor << 8) | micro ) < ( 10 << 8 | 6 ) ) { g_warning( "at-spi >= 1.7 required for accessibility support" ); return; } #endif // ! ( defined AIX || defined HPUX ) /* Initialize the AtkUtilityWrapper class */ g_type_class_unref( g_type_class_ref( OOO_TYPE_ATK_UTIL ) ); /* Initialize the GailWindow wrapper class */ g_type_class_unref( g_type_class_ref( OOO_TYPE_WINDOW_WRAPPER ) ); /* Register AtkObject wrapper factory */ AtkRegistry * registry = atk_get_default_registry(); if( registry) atk_registry_set_factory_type( registry, OOO_TYPE_FIXED, OOO_TYPE_WRAPPER_FACTORY ); } <commit_msg>INTEGRATION: CWS atkbridge2 (1.2.4); FILE MERGED 2006/05/08 13:45:14 obr 1.2.4.1: #135353# fixed crashes when closing sub-toolbars and application exit<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: atkbridge.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2006-05-11 13:31:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <plugins/gtk/atkbridge.hxx> #include <plugins/gtk/gtkframe.hxx> #include "atkfactory.hxx" #include "atkutil.hxx" #include "atkwindow.hxx" #include <stdio.h> #if ! ( defined AIX || defined HPUX ) // these have no dl* functions #include <dlfcn.h> #endif bool InitAtkBridge(void) { unsigned int major, minor, micro; /* check gail minimum version requirements */ if( sscanf( atk_get_toolkit_version(), "%u.%u.%u", &major, &minor, &micro) < 3 ) { g_warning( "unable to parse gail version number" ); return false; } if( ( (major << 16) | (minor << 8) | micro ) < ( (1 << 16) | 8 << 8 | 6 ) ) { g_warning( "libgail >= 1.8.6 required for accessibility support" ); return false; } /* get at-spi version by checking the libspi.so version number */ #if ! ( defined AIX || defined HPUX ) // these have no dl* functions /* libspi should be mapped by loading libatk-bridge.so already */ void * sym = dlsym( RTLD_DEFAULT, "spi_accessible_new" ); g_return_val_if_fail( sym != NULL, false ); Dl_info dl_info; int ret = dladdr( sym, &dl_info ); g_return_val_if_fail( ret != 0, false ); char path[PATH_MAX]; if( NULL == realpath(dl_info.dli_fname, path) ) { perror( "unable to resolve libspi.so.0" ); return false; } const char * cp = strrchr(path, '/'); if( cp != NULL ) ++cp; else cp = dl_info.dli_fname; if( sscanf( cp, "libspi.so.%u.%u.%u", &major, &minor, &micro) < 3 ) { g_warning( "unable to parse at-spi version number: %s", cp ); return false; } if( ( (major << 16) | (minor << 8) | micro ) < ( 10 << 8 | 6 ) ) { g_warning( "at-spi >= 1.7 required for accessibility support" ); return false; } #endif // ! ( defined AIX || defined HPUX ) /* Initialize the AtkUtilityWrapper class */ g_type_class_unref( g_type_class_ref( OOO_TYPE_ATK_UTIL ) ); /* Initialize the GailWindow wrapper class */ g_type_class_unref( g_type_class_ref( OOO_TYPE_WINDOW_WRAPPER ) ); /* Register AtkObject wrapper factory */ AtkRegistry * registry = atk_get_default_registry(); if( registry ) atk_registry_set_factory_type( registry, OOO_TYPE_FIXED, OOO_TYPE_WRAPPER_FACTORY ); return true; } void DeInitAtkBridge() { restore_gail_window_vtable(); /* shutdown atk-bridge Gtk+ module here, otherwise it is done in an atexit handler * where the VCL Gtk+ plugin might already be unloaded */ #if ! ( defined AIX || defined HPUX ) // these have no dl* functions void (* shutdown) ( void ) = (void (*) (void)) dlsym( RTLD_DEFAULT, "gnome_accessibility_module_shutdown"); if( shutdown ) shutdown(); #endif // ! ( defined AIX || defined HPUX ) } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2016-2020 urShadow * * 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 "SDK/amx/amx.h" #include "SDK/plugincommon.h" #include "RakNet/BitStream.h" #include "RakNet/StringCompressor.h" #include "RakNet/PluginInterface.h" #include "urmem/urmem.hpp" #include "crtp_singleton/crtp_singleton.hpp" #include "cpptoml/include/cpptoml.h" #include <unordered_set> #include <list> #include <array> #include <string> #include <regex> #include <queue> #include "Pawn.RakNet.inc" extern void *pAMXFunctions; using logprintf_t = void(*)(const char *format, ...); #include "Logger.h" #include "Settings.h" #include "Addresses.h" #include "Functions.h" #include "Scripts.h" #include "Hooks.h" #include "Natives.h" namespace Plugin { bool Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; Logger::instance()->Init(reinterpret_cast<logprintf_t>(ppData[PLUGIN_DATA_LOGPRINTF]), "[" + std::string(Settings::kPluginName) + "] "); Logger::instance()->Write( "\n\n" \ " | %s %s | 2016 - %s" \ "\n" \ " |--------------------------------" \ "\n" \ " | Author and maintainer: urShadow" \ "\n\n\n" \ " | Compiled: %s at %s" \ "\n" \ " |--------------------------------------------------------------" \ "\n" \ " | Forum thread: %s" \ "\n" \ " |--------------------------------------------------------------" \ "\n" \ " | Repository: %s" \ "\n", Settings::kPluginName, Settings::kPluginVersion, &__DATE__[7], __DATE__, __TIME__, Settings::kPluginThreadUrl, Settings::kPluginRepositoryUrl ); try { Settings::Read(); Hooks::Init(*ppData); StringCompressor::AddReference(); return true; } catch (const std::exception &e) { Logger::instance()->Write("%s: %s", __FUNCTION__, e.what()); } return false; } void Unload() { try { StringCompressor::RemoveReference(); Settings::Save(); Logger::instance()->Write("plugin unloaded"); } catch (const std::exception &e) { Logger::instance()->Write("%s: %s", __FUNCTION__, e.what()); } } void AmxLoad(AMX *amx) { cell include_version{}; if (Functions::GetAmxPublicVar(amx, Settings::kPublicVarNameVersion, include_version)) { if (include_version != PAWNRAKNET_INCLUDE_VERSION) { Logger::instance()->Write("%s: mismatch between the plugin (%d) and include (%d) versions", __FUNCTION__, PAWNRAKNET_INCLUDE_VERSION, include_version); return; } Natives::Register(amx); } } }; PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { return Plugin::Load(ppData); } PLUGIN_EXPORT void PLUGIN_CALL Unload() { Plugin::Unload(); } PLUGIN_EXPORT void PLUGIN_CALL AmxLoad(AMX *amx) { Plugin::AmxLoad(amx); } <commit_msg>Add wiki url<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2016-2020 urShadow * * 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 "SDK/amx/amx.h" #include "SDK/plugincommon.h" #include "RakNet/BitStream.h" #include "RakNet/StringCompressor.h" #include "RakNet/PluginInterface.h" #include "urmem/urmem.hpp" #include "crtp_singleton/crtp_singleton.hpp" #include "cpptoml/include/cpptoml.h" #include <unordered_set> #include <list> #include <array> #include <string> #include <regex> #include <queue> #include "Pawn.RakNet.inc" extern void *pAMXFunctions; using logprintf_t = void(*)(const char *format, ...); #include "Logger.h" #include "Settings.h" #include "Addresses.h" #include "Functions.h" #include "Scripts.h" #include "Hooks.h" #include "Natives.h" namespace Plugin { bool Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; Logger::instance()->Init(reinterpret_cast<logprintf_t>(ppData[PLUGIN_DATA_LOGPRINTF]), "[" + std::string(Settings::kPluginName) + "] "); Logger::instance()->Write( "\n\n" \ " | %s %s | 2016 - %s" \ "\n" \ " |--------------------------------" \ "\n" \ " | Author and maintainer: urShadow" \ "\n\n\n" \ " | Compiled: %s at %s" \ "\n" \ " |--------------------------------------------------------------" \ "\n" \ " | Forum thread: %s" \ "\n" \ " |--------------------------------------------------------------" \ "\n" \ " | Repository: %s" \ "\n" \ " |--------------------------------------------------------------" \ "\n" \ " | Wiki: %s/wiki" \ "\n", Settings::kPluginName, Settings::kPluginVersion, &__DATE__[7], __DATE__, __TIME__, Settings::kPluginThreadUrl, Settings::kPluginRepositoryUrl, Settings::kPluginRepositoryUrl ); try { Settings::Read(); Hooks::Init(*ppData); StringCompressor::AddReference(); return true; } catch (const std::exception &e) { Logger::instance()->Write("%s: %s", __FUNCTION__, e.what()); } return false; } void Unload() { try { StringCompressor::RemoveReference(); Settings::Save(); Logger::instance()->Write("plugin unloaded"); } catch (const std::exception &e) { Logger::instance()->Write("%s: %s", __FUNCTION__, e.what()); } } void AmxLoad(AMX *amx) { cell include_version{}; if (Functions::GetAmxPublicVar(amx, Settings::kPublicVarNameVersion, include_version)) { if (include_version != PAWNRAKNET_INCLUDE_VERSION) { Logger::instance()->Write("%s: mismatch between the plugin (%d) and include (%d) versions", __FUNCTION__, PAWNRAKNET_INCLUDE_VERSION, include_version); return; } Natives::Register(amx); } } }; PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { return Plugin::Load(ppData); } PLUGIN_EXPORT void PLUGIN_CALL Unload() { Plugin::Unload(); } PLUGIN_EXPORT void PLUGIN_CALL AmxLoad(AMX *amx) { Plugin::AmxLoad(amx); } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file param.cpp \author Урусов Андрей ([email protected]) \date 09.01.2011 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES #include <boost/bind.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/rdoparser.h" #include "simulator/compiler/parser/param.h" #include "simulator/compiler/parser/rdortp.h" #include "simulator/runtime/rdo_resource.h" #include "simulator/runtime/calc/resource/calc_resource.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE const std::string RDOParam::CONTEXT_PARAM_PARAM_ID = "param_id"; RDOParam::RDOParam(CREF(tstring) name, CREF(LPTypeInfo) pType, CREF(LPRDOValue) pDefault) : RDOParserSrcInfo(name ) , m_pType (pType ) , m_pDefault (pDefault) { checkDefault(); } RDOParam::RDOParam(CREF(RDOParserSrcInfo) srcInfo, CREF(LPTypeInfo) pType, CREF(LPRDOValue) pDefault) : RDOParserSrcInfo(srcInfo ) , m_pType (pType ) , m_pDefault (pDefault) { checkDefault(); } RDOParam::~RDOParam() {} void RDOParam::checkDefault() { if (m_pDefault && m_pDefault->defined()) { m_pType->type()->type_cast(m_pDefault->typeInfo()->type(), m_pDefault->src_info(), this->src_info(), m_pDefault->src_info()); m_pDefault = m_pType->type()->value_cast(m_pDefault, this->src_info(), m_pDefault->src_info()); } } namespace { LPExpression contextGetParam(const rdo::runtime::LPRDOCalc& resource, ruint paramID, const LPTypeInfo& paramType, const RDOParserSrcInfo& srcInfo) { return rdo::Factory<Expression>::create( paramType, rdo::Factory<rdo::runtime::RDOCalcGetResourceParam>::create(resource, paramID), srcInfo ); } template <rdo::runtime::SetOperationType::Type setOperationType> LPExpression contextSetParam(const rdo::runtime::LPRDOCalc& getResource, const ruint paramID, const rdo::runtime::LPRDOCalc& rightValue, const RDOParserSrcInfo& srcInfo) { return rdo::Factory<Expression>::create( rdo::Factory<TypeInfo>::delegate<RDOType__void>(srcInfo), rdo::Factory<rdo::runtime::RDOSetResourceParam<setOperationType> >::create(getResource, paramID, rightValue), srcInfo ); } } Context::FindResult RDOParam::onFindContext(const std::string& method, const Context::Params& params, const RDOParserSrcInfo& srcInfo) const { if (method == Context::METHOD_GET) { LPExpression resource = params.get<LPExpression>(RDORSSResource::CONTEXT_PARAM_RESOURCE_EXPRESSION); const ruint paramID = params.get<ruint>(RDOParam::CONTEXT_PARAM_PARAM_ID); return FindResult(CreateExpression(boost::bind(&contextGetParam, resource->calc(), paramID, getTypeInfo(), srcInfo))); } if (method == Context::METHOD_SET) { const rdo::runtime::LPRDOCalc rightValue = params.exists(Expression::CONTEXT_PARAM_SET_EXPRESSION) ? params.get<LPExpression>(Expression::CONTEXT_PARAM_SET_EXPRESSION)->calc() : params.get<LPRDOFUNArithm>(RDOFUNArithm::CONTEXT_PARAM_SET_ARITHM)->createCalc(getTypeInfo()); const ruint paramID = params.get<ruint>(RDOParam::CONTEXT_PARAM_PARAM_ID); const rdo::runtime::LPRDOCalc getResource = params.get<rdo::runtime::LPRDOCalc>("getResource()"); using namespace rdo::runtime; switch (params.get<SetOperationType::Type>(Expression::CONTEXT_PARAM_SET_OPERATION_TYPE)) { case SetOperationType::NOCHANGE : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::NOCHANGE>, getResource, paramID, rightValue, srcInfo))); case SetOperationType::SET : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::SET>, getResource, paramID, rightValue, srcInfo))); case SetOperationType::ADDITION : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::ADDITION>, getResource, paramID, rightValue, srcInfo))); case SetOperationType::SUBTRACTION: return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::SUBTRACTION>, getResource, paramID, rightValue, srcInfo))); case SetOperationType::MULTIPLY : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::MULTIPLY>, getResource, paramID, rightValue, srcInfo))); case SetOperationType::DIVIDE : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::DIVIDE>, getResource, paramID, rightValue, srcInfo))); case SetOperationType::INCREMENT : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::INCREMENT>, getResource, paramID, rightValue, srcInfo))); case SetOperationType::DECRIMENT : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::DECRIMENT>, getResource, paramID, rightValue, srcInfo))); default: return FindResult(); } } return FindResult(); } CLOSE_RDO_PARSER_NAMESPACE <commit_msg> - исправил ошибки при обработке метода Context::SET в контексте параметра<commit_after>/*! \copyright (c) RDO-Team, 2011 \file param.cpp \author Урусов Андрей ([email protected]) \date 09.01.2011 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH #include "simulator/compiler/parser/pch.h" // ----------------------------------------------------------------------- INCLUDES #include <boost/bind.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/compiler/parser/rdoparser.h" #include "simulator/compiler/parser/param.h" #include "simulator/compiler/parser/rdortp.h" #include "simulator/compiler/parser/type/range.h" #include "simulator/runtime/rdo_resource.h" #include "simulator/runtime/calc/resource/calc_resource.h" // -------------------------------------------------------------------------------- OPEN_RDO_PARSER_NAMESPACE const std::string RDOParam::CONTEXT_PARAM_PARAM_ID = "param_id"; RDOParam::RDOParam(CREF(tstring) name, CREF(LPTypeInfo) pType, CREF(LPRDOValue) pDefault) : RDOParserSrcInfo(name ) , m_pType (pType ) , m_pDefault (pDefault) { checkDefault(); } RDOParam::RDOParam(CREF(RDOParserSrcInfo) srcInfo, CREF(LPTypeInfo) pType, CREF(LPRDOValue) pDefault) : RDOParserSrcInfo(srcInfo ) , m_pType (pType ) , m_pDefault (pDefault) { checkDefault(); } RDOParam::~RDOParam() {} void RDOParam::checkDefault() { if (m_pDefault && m_pDefault->defined()) { m_pType->type()->type_cast(m_pDefault->typeInfo()->type(), m_pDefault->src_info(), this->src_info(), m_pDefault->src_info()); m_pDefault = m_pType->type()->value_cast(m_pDefault, this->src_info(), m_pDefault->src_info()); } } namespace { LPExpression contextGetParam(const rdo::runtime::LPRDOCalc& resource, ruint paramID, const LPTypeInfo& paramType, const RDOParserSrcInfo& srcInfo) { return rdo::Factory<Expression>::create( paramType, rdo::Factory<rdo::runtime::RDOCalcGetResourceParam>::create(resource, paramID), srcInfo ); } template <rdo::runtime::SetOperationType::Type setOperationType> LPExpression contextSetParam(const rdo::runtime::LPRDOCalc& getResource, const RDOParam* param, const ruint paramID, const rdo::runtime::LPRDOCalc& rightValue, const RDOParserSrcInfo& srcInfo) { rdo::runtime::LPRDOCalc setParamCalc = rdo::Factory<rdo::runtime::RDOSetResourceParam<setOperationType> >::create(getResource, paramID, rightValue); LPRDOTypeIntRange pTypeIntRange = param->getTypeInfo()->type().object_dynamic_cast<RDOTypeIntRange>(); if (pTypeIntRange) { setParamCalc = rdo::Factory<rdo::runtime::RDOCalcCheckRange>::create(pTypeIntRange->range()->getMin()->value(), pTypeIntRange->range()->getMax()->value(), setParamCalc); } LPRDOTypeRealRange pTypeRealRange = param->getTypeInfo()->type().object_dynamic_cast<RDOTypeRealRange>(); if (pTypeRealRange) { setParamCalc = rdo::Factory<rdo::runtime::RDOCalcCheckRange>::create(pTypeRealRange->range()->getMin()->value(), pTypeRealRange->range()->getMax()->value(), setParamCalc); } return rdo::Factory<Expression>::create( param->getTypeInfo(), setParamCalc, srcInfo ); } } Context::FindResult RDOParam::onFindContext(const std::string& method, const Context::Params& params, const RDOParserSrcInfo& srcInfo) const { if (method == Context::METHOD_GET) { LPExpression resource = params.get<LPExpression>(RDORSSResource::CONTEXT_PARAM_RESOURCE_EXPRESSION); const ruint paramID = params.get<ruint>(RDOParam::CONTEXT_PARAM_PARAM_ID); return FindResult(CreateExpression(boost::bind(&contextGetParam, resource->calc(), paramID, getTypeInfo(), srcInfo))); } if (method == Context::METHOD_SET) { const rdo::runtime::LPRDOCalc rightValue = params.exists(Expression::CONTEXT_PARAM_SET_EXPRESSION) ? params.get<LPExpression>(Expression::CONTEXT_PARAM_SET_EXPRESSION)->calc() : params.get<LPRDOFUNArithm>(RDOFUNArithm::CONTEXT_PARAM_SET_ARITHM)->createCalc(getTypeInfo()); const ruint paramID = params.get<ruint>(RDOParam::CONTEXT_PARAM_PARAM_ID); const rdo::runtime::LPRDOCalc getResource = params.get<rdo::runtime::LPRDOCalc>("getResource()"); using namespace rdo::runtime; switch (params.get<SetOperationType::Type>(Expression::CONTEXT_PARAM_SET_OPERATION_TYPE)) { case SetOperationType::NOCHANGE : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::NOCHANGE>, getResource, this, paramID, rightValue, srcInfo))); case SetOperationType::SET : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::SET>, getResource, this, paramID, rightValue, srcInfo))); case SetOperationType::ADDITION : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::ADDITION>, getResource, this, paramID, rightValue, srcInfo))); case SetOperationType::SUBTRACTION: return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::SUBTRACTION>, getResource, this, paramID, rightValue, srcInfo))); case SetOperationType::MULTIPLY : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::MULTIPLY>, getResource, this, paramID, rightValue, srcInfo))); case SetOperationType::DIVIDE : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::DIVIDE>, getResource, this, paramID, rightValue, srcInfo))); case SetOperationType::INCREMENT : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::INCREMENT>, getResource, this, paramID, rightValue, srcInfo))); case SetOperationType::DECRIMENT : return FindResult(CreateExpression(boost::bind(&contextSetParam<SetOperationType::DECRIMENT>, getResource, this, paramID, rightValue, srcInfo))); default: return FindResult(); } } return FindResult(); } CLOSE_RDO_PARSER_NAMESPACE <|endoftext|>
<commit_before>#include "Compiler.h" #include <fstream> #include <cstring> using namespace std; using namespace compiler; void print_help(char *program_name) { cout << "Usage: " << program_name << " [options] <inputs>" << endl; cout << "Options:" << endl; cout << " --help -h Show available options" << endl << endl; cout << " --output -o Output binary" << endl; cout << " --header-output -ho Output header" << endl << endl; #ifdef CCPP cout << " --cpp C++ backend" << endl; #endif #ifdef CGNUASM cout << " --gnuasm GNU Assembly backend" << endl; #endif #ifdef CHASKELL cout << " --haskell Haskell backend" << endl; #endif #ifdef CLLVM cout << " --llvm LLVM backend" << endl; #endif cout << " --pprinter Pretty printer backend" << endl; } int main(int argc, char *argv[]) { Backend backend = Backend::PPRINTER; vector<string> input; string output("a.out"); string header_output("a.h"); if (argc == 1) { print_help(argv[0]); return 0; } for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { print_help(argv[0]); return 0; } #ifdef CCPP else if (strcmp(argv[i],"--cpp") == 0) backend = Backend::CPP; #endif #ifdef CGNUASM else if (strcmp(argv[i],"--gnuasm") == 0) backend = Backend::GNUASM; #endif #ifdef CHASKELL else if (strcmp(argv[i],"--haskell") == 0) backend = Backend::GNUASM; #endif #ifdef CLLVM else if (strcmp(argv[i],"--llvm") == 0) backend = Backend::LLVM; #endif else if (strcmp(argv[i],"--pprinter") == 0) backend = Backend::PPRINTER; else if (strcmp(argv[i],"--output") == 0 || strcmp(argv[i],"-o") == 0) if (i < argc - 1) output = argv[++i]; else { cerr << "No output file specified" << endl; return 2; } else if (strcmp(argv[i],"--header-output") == 0 || strcmp(argv[i],"-ho") == 0) if (i < argc - 1) header_output = argv[++i]; else { cerr << "No output header specified" << endl; return 3; } else input.push_back(argv[i]); } if (input.size() == 0) { cerr << "No input files" << endl; return 1; } ifstream in(input[0]); ofstream out(output); ofstream hout(header_output); compiler::Compiler compiler(&in, &out, &hout); compiler.set_backend(backend); compiler.compile(); return 0; } <commit_msg>main: cleanup<commit_after>#include "Compiler.h" #include <fstream> #include <cstring> using namespace std; using namespace compiler; void print_help(char *program_name) { cout << "Usage: " << program_name << " [options] <inputs>" << endl; cout << "Options:" << endl; cout << " --help -h Show available options" << endl << endl; cout << " --output -o <file> Set binary output file" << endl; cout << " --header-output -ho <file> Set header output file" << endl << endl; #ifdef CCPP cout << " --cpp C++ backend" << endl; #endif #ifdef CGNUASM cout << " --gnuasm GNU Assembly backend" << endl; #endif #ifdef CHASKELL cout << " --haskell Haskell backend" << endl; #endif #ifdef CLLVM cout << " --llvm LLVM backend" << endl; #endif cout << " --pprinter Pretty printer backend" << endl; } int main(int argc, char *argv[]) { Backend backend = Backend::PPRINTER; vector<string> input; string output("a.out"); string header_output("a.h"); if (argc == 1) { print_help(argv[0]); return 0; } for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) { print_help(argv[0]); return 0; } #ifdef CCPP else if (strcmp(argv[i],"--cpp") == 0) backend = Backend::CPP; #endif #ifdef CGNUASM else if (strcmp(argv[i],"--gnuasm") == 0) backend = Backend::GNUASM; #endif #ifdef CHASKELL else if (strcmp(argv[i],"--haskell") == 0) backend = Backend::GNUASM; #endif #ifdef CLLVM else if (strcmp(argv[i],"--llvm") == 0) backend = Backend::LLVM; #endif else if (strcmp(argv[i],"--pprinter") == 0) backend = Backend::PPRINTER; else if (strcmp(argv[i],"--output") == 0 || strcmp(argv[i],"-o") == 0) if (i < argc - 1) output = argv[++i]; else { cerr << "No output file specified" << endl; return 2; } else if (strcmp(argv[i],"--header-output") == 0 || strcmp(argv[i],"-ho") == 0) if (i < argc - 1) header_output = argv[++i]; else { cerr << "No output header specified" << endl; return 3; } else input.push_back(argv[i]); } if (input.size() == 0) { cerr << "No input files" << endl; return 1; } ifstream in(input[0]); ofstream out(output); ofstream hout(header_output); compiler::Compiler compiler(&in, &out, &hout); compiler.set_backend(backend); compiler.compile(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Jakob Sinclair 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 "kemi.hpp" Kemi::Kemi() { ; } Kemi::~Kemi() { ; } /*Loads a file and reads in all the information to create a periodic table*/ void Kemi::init(std::string file) { std::ifstream File; File.open(file); try { if (!File.is_open()) { Error FileError; throw FileError.set_error("Could not load file " + file + '!'); } else { std::string BufferLine = ""; int i = 0; while (std::getline(File, BufferLine)) { m_PeriodicTable.emplace_back(Element()); int c = 0; while (BufferLine[c] != ' ') { m_PeriodicTable[i].Name += BufferLine[c]; c++; } c++; while (BufferLine[c] != ' ') { m_PeriodicTable[i].AtomicNumber *= 10; m_PeriodicTable[i].AtomicNumber += BufferLine[c] - '0'; c++; } c++; int p = -1; bool point = false; while (BufferLine[c] != ' ') { if (BufferLine[c] == '.') { point = true; } else if (point == true) { m_PeriodicTable[i].AtomicMass += (float)((BufferLine[c] - '0') * pow(10, p)); p--; } else { m_PeriodicTable[i].AtomicMass *= 10; m_PeriodicTable[i].AtomicMass += (float)(BufferLine[c] - '0'); } c++; } if (BufferLine[BufferLine.size() - 1] == 'N') { m_PeriodicTable[i].Property = type::NonMetal; } else if (BufferLine[BufferLine.size() - 1] == 'M') { m_PeriodicTable[i].Property = type::Metal; } else { m_PeriodicTable[i].Property = type::TransitionMetal; } i++; } } } catch (std::exception &e) { std::cout << e.what() << std::endl; } } /*Handles user input and events and corresponds with the correct functions*/ void Kemi::run() { for(int i = 0; i < m_PeriodicTable.size(); i++) { std::cout << "Name: " << m_PeriodicTable[i].Name << std::endl; std::cout << "Mass: " << m_PeriodicTable[i].AtomicMass << std::endl; std::cout << "Number: " << m_PeriodicTable[i].AtomicNumber << std::endl; std::cout << "Property: "; if (m_PeriodicTable[i].Property == 0) { std::cout << "Metal" << std::endl; } else if (m_PeriodicTable[i].Property == 1) { std::cout << "Nonmetal" << std::endl; } else { std::cout << "Transitionmetal" << std::endl; } } } <commit_msg>Updated the main loop.<commit_after>/* Copyright (c) 2016 Jakob Sinclair 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 "kemi.hpp" Kemi::Kemi() { ; } Kemi::~Kemi() { ; } /*Loads a file and reads in all the information to create a periodic table*/ void Kemi::init(std::string file) { std::ifstream File; File.open(file); try { if (!File.is_open()) { Error FileError; throw FileError.set_error("Could not load file " + file + '!'); } else { std::string BufferLine = ""; int i = 0; while (std::getline(File, BufferLine)) { m_PeriodicTable.emplace_back(Element()); int c = 0; while (BufferLine[c] != ' ') { m_PeriodicTable[i].Name += BufferLine[c]; c++; } c++; while (BufferLine[c] != ' ') { m_PeriodicTable[i].AtomicNumber *= 10; m_PeriodicTable[i].AtomicNumber += BufferLine[c] - '0'; c++; } c++; int p = -1; bool point = false; while (BufferLine[c] != ' ') { if (BufferLine[c] == '.') { point = true; } else if (point == true) { m_PeriodicTable[i].AtomicMass += (float)((BufferLine[c] - '0') * pow(10, p)); p--; } else { m_PeriodicTable[i].AtomicMass *= 10; m_PeriodicTable[i].AtomicMass += (float)(BufferLine[c] - '0'); } c++; } if (BufferLine[BufferLine.size() - 1] == 'N') { m_PeriodicTable[i].Property = type::NonMetal; } else if (BufferLine[BufferLine.size() - 1] == 'M') { m_PeriodicTable[i].Property = type::Metal; } else { m_PeriodicTable[i].Property = type::TransitionMetal; } i++; } } } catch (std::exception &e) { std::cout << e.what() << std::endl; } } /*Handles user input and events and corresponds with the correct functions*/ void Kemi::run() { for(int i = 0; i < m_PeriodicTable.size(); i++) { std::cout << "Name: " << m_PeriodicTable[i].Name << std::endl; std::cout << "Mass: " << m_PeriodicTable[i].AtomicMass << std::endl; std::cout << "Number: " << m_PeriodicTable[i].AtomicNumber << std::endl; std::cout << "Property: "; if (m_PeriodicTable[i].Property == 0) { std::cout << "Metal" << std::endl; } else if (m_PeriodicTable[i].Property == 1) { std::cout << "Nonmetal" << std::endl; } else { std::cout << "Transitionmetal" << std::endl; } } bool quit = false; while (!quit) { std::string answer; std::cin >> answer; if (answer == 'q') { quit = true; } } } <|endoftext|>
<commit_before>/* * * Copyright 2019 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 <grpc/support/port_platform.h> #include "src/core/lib/iomgr/work_serializer.h" namespace grpc_core { DebugOnlyTraceFlag grpc_work_serializer_trace(false, "work_serializer"); struct CallbackWrapper { CallbackWrapper(std::function<void()> cb, const grpc_core::DebugLocation& loc) : callback(std::move(cb)), location(loc) {} MultiProducerSingleConsumerQueue::Node mpscq_node; const std::function<void()> callback; const DebugLocation location; }; class WorkSerializer::WorkSerializerImpl : public Orphanable { public: void Run(std::function<void()> callback, const grpc_core::DebugLocation& location); void Orphan() override; private: void DrainQueue(); // An initial size of 1 keeps track of whether the work serializer has been // orphaned. Atomic<size_t> size_{1}; MultiProducerSingleConsumerQueue queue_; }; void WorkSerializer::WorkSerializerImpl::Run( std::function<void()> callback, const grpc_core::DebugLocation& location) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, "WorkSerializer::Run() %p Scheduling callback [%s:%d]", this, location.file(), location.line()); } const size_t prev_size = size_.FetchAdd(1); // The work serializer should not have been orphaned. GPR_DEBUG_ASSERT(prev_size > 0); if (prev_size == 1) { // There is no other closure executing right now on this work serializer. // Execute this closure immediately. if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Executing immediately"); } callback(); // Loan this thread to the work serializer thread and drain the queue. DrainQueue(); } else { CallbackWrapper* cb_wrapper = new CallbackWrapper(std::move(callback), location); // There already are closures executing on this work serializer. Simply add // this closure to the queue. if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Scheduling on queue : item %p", cb_wrapper); } queue_.Push(&cb_wrapper->mpscq_node); } } void WorkSerializer::WorkSerializerImpl::Orphan() { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, "WorkSerializer::Orphan() %p", this); } size_t prev_size = size_.FetchSub(1); if (prev_size == 1) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Destroying"); } delete this; } } // The thread that calls this loans itself to the work serializer so as to // execute all the scheduled callback. This is called from within // WorkSerializer::Run() after executing a callback immediately, and hence size_ // is at least 1. void WorkSerializer::WorkSerializerImpl::DrainQueue() { while (true) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, "WorkSerializer::DrainQueue() %p", this); } size_t prev_size = size_.FetchSub(1); GPR_DEBUG_ASSERT(prev_size >= 1); // It is possible that while draining the queue, one of the callbacks ended // up orphaning the work serializer. In that case, delete the object. if (prev_size == 1) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Queue Drained. Destroying"); } delete this; return; } if (prev_size == 2) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Queue Drained"); } return; } // There is at least one callback on the queue. Pop the callback from the // queue and execute it. CallbackWrapper* cb_wrapper = nullptr; bool empty_unused; while ((cb_wrapper = reinterpret_cast<CallbackWrapper*>( queue_.PopAndCheckEnd(&empty_unused))) == nullptr) { // This can happen either due to a race condition within the mpscq // implementation or because of a race with Run() if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Queue returned nullptr, trying again"); } } if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Running item %p : callback scheduled at [%s:%d]", cb_wrapper, cb_wrapper->location.file(), cb_wrapper->location.line()); } cb_wrapper->callback(); delete cb_wrapper; } } // WorkSerializer WorkSerializer::WorkSerializer() : impl_(MakeOrphanable<WorkSerializerImpl>()) {} WorkSerializer::~WorkSerializer() {} void WorkSerializer::Run(std::function<void()> callback, const grpc_core::DebugLocation& location) { impl_->Run(callback, location); } } // namespace grpc_core <commit_msg>Clang-tidy<commit_after>/* * * Copyright 2019 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 <grpc/support/port_platform.h> #include "src/core/lib/iomgr/work_serializer.h" namespace grpc_core { DebugOnlyTraceFlag grpc_work_serializer_trace(false, "work_serializer"); struct CallbackWrapper { CallbackWrapper(std::function<void()> cb, const grpc_core::DebugLocation& loc) : callback(std::move(cb)), location(loc) {} MultiProducerSingleConsumerQueue::Node mpscq_node; const std::function<void()> callback; const DebugLocation location; }; class WorkSerializer::WorkSerializerImpl : public Orphanable { public: void Run(std::function<void()> callback, const grpc_core::DebugLocation& location); void Orphan() override; private: void DrainQueue(); // An initial size of 1 keeps track of whether the work serializer has been // orphaned. Atomic<size_t> size_{1}; MultiProducerSingleConsumerQueue queue_; }; void WorkSerializer::WorkSerializerImpl::Run( std::function<void()> callback, const grpc_core::DebugLocation& location) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, "WorkSerializer::Run() %p Scheduling callback [%s:%d]", this, location.file(), location.line()); } const size_t prev_size = size_.FetchAdd(1); // The work serializer should not have been orphaned. GPR_DEBUG_ASSERT(prev_size > 0); if (prev_size == 1) { // There is no other closure executing right now on this work serializer. // Execute this closure immediately. if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Executing immediately"); } callback(); // Loan this thread to the work serializer thread and drain the queue. DrainQueue(); } else { CallbackWrapper* cb_wrapper = new CallbackWrapper(std::move(callback), location); // There already are closures executing on this work serializer. Simply add // this closure to the queue. if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Scheduling on queue : item %p", cb_wrapper); } queue_.Push(&cb_wrapper->mpscq_node); } } void WorkSerializer::WorkSerializerImpl::Orphan() { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, "WorkSerializer::Orphan() %p", this); } size_t prev_size = size_.FetchSub(1); if (prev_size == 1) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Destroying"); } delete this; } } // The thread that calls this loans itself to the work serializer so as to // execute all the scheduled callback. This is called from within // WorkSerializer::Run() after executing a callback immediately, and hence size_ // is at least 1. void WorkSerializer::WorkSerializerImpl::DrainQueue() { while (true) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, "WorkSerializer::DrainQueue() %p", this); } size_t prev_size = size_.FetchSub(1); GPR_DEBUG_ASSERT(prev_size >= 1); // It is possible that while draining the queue, one of the callbacks ended // up orphaning the work serializer. In that case, delete the object. if (prev_size == 1) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Queue Drained. Destroying"); } delete this; return; } if (prev_size == 2) { if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Queue Drained"); } return; } // There is at least one callback on the queue. Pop the callback from the // queue and execute it. CallbackWrapper* cb_wrapper = nullptr; bool empty_unused; while ((cb_wrapper = reinterpret_cast<CallbackWrapper*>( queue_.PopAndCheckEnd(&empty_unused))) == nullptr) { // This can happen either due to a race condition within the mpscq // implementation or because of a race with Run() if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Queue returned nullptr, trying again"); } } if (GRPC_TRACE_FLAG_ENABLED(grpc_work_serializer_trace)) { gpr_log(GPR_INFO, " Running item %p : callback scheduled at [%s:%d]", cb_wrapper, cb_wrapper->location.file(), cb_wrapper->location.line()); } cb_wrapper->callback(); delete cb_wrapper; } } // WorkSerializer WorkSerializer::WorkSerializer() : impl_(MakeOrphanable<WorkSerializerImpl>()) {} WorkSerializer::~WorkSerializer() {} void WorkSerializer::Run(std::function<void()> callback, const grpc_core::DebugLocation& location) { impl_->Run(std::move(callback), location); } } // namespace grpc_core <|endoftext|>
<commit_before>/************************************ * file enc : ASCII * author : [email protected] ************************************/ #ifndef CPPJIEBA_TRIE_H #define CPPJIEBA_TRIE_H #include <iostream> #include <fstream> #include <map> #include <cstring> #include <stdint.h> #include <cmath> #include <limits> #include "Limonp/str_functs.hpp" #include "Limonp/logger.hpp" #include "TransCode.hpp" namespace CppJieba { using namespace Limonp; const double MIN_DOUBLE = -3.14e+100; const double MAX_DOUBLE = 3.14e+100; typedef unordered_map<uint16_t, struct TrieNode*> TrieNodeMap; struct TrieNode { TrieNodeMap hmap; bool isLeaf; uint nodeInfoVecPos; TrieNode() { isLeaf = false; nodeInfoVecPos = 0; } }; struct TrieNodeInfo { Unicode word; size_t freq; string tag; double logFreq; //logFreq = log(freq/sum(freq)); TrieNodeInfo():freq(0),logFreq(0.0) { } TrieNodeInfo(const TrieNodeInfo& nodeInfo):word(nodeInfo.word), freq(nodeInfo.freq), tag(nodeInfo.tag), logFreq(nodeInfo.logFreq) { } TrieNodeInfo(const Unicode& _word):word(_word),freq(0),logFreq(MIN_DOUBLE) { } string toString()const { string tmp; TransCode::encode(word, tmp); return string_format("{word:%s,freq:%d, logFreq:%lf}", tmp.c_str(), freq, logFreq); } }; typedef unordered_map<uint, const TrieNodeInfo*> DagType; class Trie { private: TrieNode* _root; vector<TrieNodeInfo> _nodeInfoVec; bool _initFlag; int64_t _freqSum; double _minLogFreq; public: Trie() { _root = NULL; _freqSum = 0; _minLogFreq = MAX_DOUBLE; _initFlag = false; } ~Trie() { dispose(); } bool init() { if(_getInitFlag()) { LogError("already initted!"); return false; } try { _root = new TrieNode; } catch(const bad_alloc& e) { return false; } if(NULL == _root) { return false; } _setInitFlag(true); return true; } bool dispose() { if(!_getInitFlag()) { return false; } bool ret = _deleteNode(_root); if(!ret) { LogFatal("_deleteNode failed!"); return false; } _root = NULL; _nodeInfoVec.clear(); _setInitFlag(false); return ret; } bool loadDict(const char * const filePath) { if(!_getInitFlag()) { LogError("not initted."); return false; } if(!checkFileExist(filePath)) { LogError("cann't find fiel[%s].",filePath); return false; } bool res = false; res = _trieInsert(filePath); if(!res) { LogError("_trieInsert failed."); return false; } res = _countWeight(); if(!res) { LogError("_countWeight failed."); return false; } return true; } private: void _setInitFlag(bool on){_initFlag = on;}; bool _getInitFlag()const{return _initFlag;}; public: const TrieNodeInfo* find(const string& str)const { Unicode uintVec; if(!TransCode::decode(str, uintVec)) { return NULL; } return find(uintVec); } const TrieNodeInfo* find(const Unicode& uintVec)const { if(uintVec.empty()) { return NULL; } return find(uintVec.begin(), uintVec.end()); } const TrieNodeInfo* find(Unicode::const_iterator begin, Unicode::const_iterator end)const { if(!_getInitFlag()) { LogFatal("trie not initted!"); return NULL; } if(begin >= end) { return NULL; } TrieNode* p = _root; for(Unicode::const_iterator it = begin; it != end; it++) { uint16_t chUni = *it; if(p->hmap.find(chUni) == p-> hmap.end()) { return NULL; } else { p = p->hmap[chUni]; } } if(p->isLeaf) { uint pos = p->nodeInfoVecPos; if(pos < _nodeInfoVec.size()) { return &(_nodeInfoVec[pos]); } else { LogFatal("node's nodeInfoVecPos is out of _nodeInfoVec's range"); return NULL; } } return NULL; } bool find(const Unicode& unico, vector<pair<uint, const TrieNodeInfo*> >& res)const { if(!_getInitFlag()) { LogFatal("trie not initted!"); return false; } TrieNode* p = _root; for(uint i = 0; i < unico.size(); i++) { if(p->hmap.find(unico[i]) == p-> hmap.end()) { break; } p = p->hmap[unico[i]]; if(p->isLeaf) { uint pos = p->nodeInfoVecPos; if(pos < _nodeInfoVec.size()) { res.push_back(make_pair(i, &_nodeInfoVec[pos])); } else { LogFatal("node's nodeInfoVecPos is out of _nodeInfoVec's range"); return false; } } } return !res.empty(); } const TrieNodeInfo* findPrefix(const string& str)const { if(!_getInitFlag()) { LogFatal("trie not initted!"); return NULL; } Unicode uintVec; if(!TransCode::decode(str, uintVec)) { LogError("TransCode::decode failed."); return NULL; } //find TrieNode* p = _root; uint pos = 0; uint16_t chUni = 0; const TrieNodeInfo * res = NULL; for(uint i = 0; i < uintVec.size(); i++) { chUni = uintVec[i]; if(p->isLeaf) { pos = p->nodeInfoVecPos; if(pos >= _nodeInfoVec.size()) { LogFatal("node's nodeInfoVecPos is out of _nodeInfoVec's range"); return NULL; } res = &(_nodeInfoVec[pos]); } if(p->hmap.find(chUni) == p->hmap.end()) { break; } else { p = p->hmap[chUni]; } } return res; } public: double getMinLogFreq()const{return _minLogFreq;}; bool insert(const TrieNodeInfo& nodeInfo) { if(!_getInitFlag()) { LogFatal("not initted!"); return false; } const Unicode& uintVec = nodeInfo.word; TrieNode* p = _root; for(uint i = 0; i < uintVec.size(); i++) { uint16_t cu = uintVec[i]; if(NULL == p) { return false; } if(p->hmap.end() == p->hmap.find(cu)) { TrieNode * next = NULL; try { next = new TrieNode; } catch(const bad_alloc& e) { return false; } p->hmap[cu] = next; p = next; } else { p = p->hmap[cu]; } } if(NULL == p) { return false; } if(p->isLeaf) { LogError("this node already inserted"); return false; } p->isLeaf = true; _nodeInfoVec.push_back(nodeInfo); p->nodeInfoVecPos = _nodeInfoVec.size() - 1; return true; } private: bool _trieInsert(const char * const filePath) { ifstream ifile(filePath); string line; vector<string> vecBuf; TrieNodeInfo nodeInfo; while(getline(ifile, line)) { vecBuf.clear(); splitStr(line, vecBuf, " "); if(3 < vecBuf.size()) { LogError("line[%s] illegal.", line.c_str()); return false; } if(!TransCode::decode(vecBuf[0], nodeInfo.word)) { return false; } nodeInfo.freq = atoi(vecBuf[1].c_str()); if(3 == vecBuf.size()) { nodeInfo.tag = vecBuf[2]; } //insert node if(!insert(nodeInfo)) { LogError("insert node failed!"); } } return true; } bool _countWeight() { if(_nodeInfoVec.empty() || 0 != _freqSum) { LogError("_nodeInfoVec is empty or _freqSum has been counted already."); return false; } //freq total freq for(size_t i = 0; i < _nodeInfoVec.size(); i++) { _freqSum += _nodeInfoVec[i].freq; } if(0 == _freqSum) { LogError("_freqSum == 0 ."); return false; } //normalize for(uint i = 0; i < _nodeInfoVec.size(); i++) { TrieNodeInfo& nodeInfo = _nodeInfoVec[i]; if(0 == nodeInfo.freq) { LogFatal("nodeInfo.freq == 0!"); return false; } nodeInfo.logFreq = log(double(nodeInfo.freq)/double(_freqSum)); if(_minLogFreq > nodeInfo.logFreq) { _minLogFreq = nodeInfo.logFreq; } } return true; } bool _deleteNode(TrieNode* node) { for(TrieNodeMap::iterator it = node->hmap.begin(); it != node->hmap.end(); it++) { TrieNode* next = it->second; _deleteNode(next); } delete node; return true; } }; } #endif <commit_msg>replace tab with space in Trie.hpp<commit_after>/************************************ * file enc : ASCII * author : [email protected] ************************************/ #ifndef CPPJIEBA_TRIE_H #define CPPJIEBA_TRIE_H #include <iostream> #include <fstream> #include <map> #include <cstring> #include <stdint.h> #include <cmath> #include <limits> #include "Limonp/str_functs.hpp" #include "Limonp/logger.hpp" #include "TransCode.hpp" namespace CppJieba { using namespace Limonp; const double MIN_DOUBLE = -3.14e+100; const double MAX_DOUBLE = 3.14e+100; typedef unordered_map<uint16_t, struct TrieNode*> TrieNodeMap; struct TrieNode { TrieNodeMap hmap; bool isLeaf; uint nodeInfoVecPos; TrieNode() { isLeaf = false; nodeInfoVecPos = 0; } }; struct TrieNodeInfo { Unicode word; size_t freq; string tag; double logFreq; //logFreq = log(freq/sum(freq)); TrieNodeInfo():freq(0),logFreq(0.0) { } TrieNodeInfo(const TrieNodeInfo& nodeInfo):word(nodeInfo.word), freq(nodeInfo.freq), tag(nodeInfo.tag), logFreq(nodeInfo.logFreq) { } TrieNodeInfo(const Unicode& _word):word(_word),freq(0),logFreq(MIN_DOUBLE) { } string toString()const { string tmp; TransCode::encode(word, tmp); return string_format("{word:%s,freq:%d, logFreq:%lf}", tmp.c_str(), freq, logFreq); } }; typedef unordered_map<uint, const TrieNodeInfo*> DagType; class Trie { private: TrieNode* _root; vector<TrieNodeInfo> _nodeInfoVec; bool _initFlag; int64_t _freqSum; double _minLogFreq; public: Trie() { _root = NULL; _freqSum = 0; _minLogFreq = MAX_DOUBLE; _initFlag = false; } ~Trie() { dispose(); } bool init() { if(_getInitFlag()) { LogError("already initted!"); return false; } try { _root = new TrieNode; } catch(const bad_alloc& e) { return false; } if(NULL == _root) { return false; } _setInitFlag(true); return true; } bool dispose() { if(!_getInitFlag()) { return false; } bool ret = _deleteNode(_root); if(!ret) { LogFatal("_deleteNode failed!"); return false; } _root = NULL; _nodeInfoVec.clear(); _setInitFlag(false); return ret; } bool loadDict(const char * const filePath) { if(!_getInitFlag()) { LogError("not initted."); return false; } if(!checkFileExist(filePath)) { LogError("cann't find fiel[%s].",filePath); return false; } bool res = false; res = _trieInsert(filePath); if(!res) { LogError("_trieInsert failed."); return false; } res = _countWeight(); if(!res) { LogError("_countWeight failed."); return false; } return true; } private: void _setInitFlag(bool on){_initFlag = on;}; bool _getInitFlag()const{return _initFlag;}; public: const TrieNodeInfo* find(const string& str)const { Unicode uintVec; if(!TransCode::decode(str, uintVec)) { return NULL; } return find(uintVec); } const TrieNodeInfo* find(const Unicode& uintVec)const { if(uintVec.empty()) { return NULL; } return find(uintVec.begin(), uintVec.end()); } const TrieNodeInfo* find(Unicode::const_iterator begin, Unicode::const_iterator end)const { if(!_getInitFlag()) { LogFatal("trie not initted!"); return NULL; } if(begin >= end) { return NULL; } TrieNode* p = _root; for(Unicode::const_iterator it = begin; it != end; it++) { uint16_t chUni = *it; if(p->hmap.find(chUni) == p-> hmap.end()) { return NULL; } else { p = p->hmap[chUni]; } } if(p->isLeaf) { uint pos = p->nodeInfoVecPos; if(pos < _nodeInfoVec.size()) { return &(_nodeInfoVec[pos]); } else { LogFatal("node's nodeInfoVecPos is out of _nodeInfoVec's range"); return NULL; } } return NULL; } bool find(const Unicode& unico, vector<pair<uint, const TrieNodeInfo*> >& res)const { if(!_getInitFlag()) { LogFatal("trie not initted!"); return false; } TrieNode* p = _root; for(uint i = 0; i < unico.size(); i++) { if(p->hmap.find(unico[i]) == p-> hmap.end()) { break; } p = p->hmap[unico[i]]; if(p->isLeaf) { uint pos = p->nodeInfoVecPos; if(pos < _nodeInfoVec.size()) { res.push_back(make_pair(i, &_nodeInfoVec[pos])); } else { LogFatal("node's nodeInfoVecPos is out of _nodeInfoVec's range"); return false; } } } return !res.empty(); } const TrieNodeInfo* findPrefix(const string& str)const { if(!_getInitFlag()) { LogFatal("trie not initted!"); return NULL; } Unicode uintVec; if(!TransCode::decode(str, uintVec)) { LogError("TransCode::decode failed."); return NULL; } //find TrieNode* p = _root; uint pos = 0; uint16_t chUni = 0; const TrieNodeInfo * res = NULL; for(uint i = 0; i < uintVec.size(); i++) { chUni = uintVec[i]; if(p->isLeaf) { pos = p->nodeInfoVecPos; if(pos >= _nodeInfoVec.size()) { LogFatal("node's nodeInfoVecPos is out of _nodeInfoVec's range"); return NULL; } res = &(_nodeInfoVec[pos]); } if(p->hmap.find(chUni) == p->hmap.end()) { break; } else { p = p->hmap[chUni]; } } return res; } public: double getMinLogFreq()const{return _minLogFreq;}; bool insert(const TrieNodeInfo& nodeInfo) { if(!_getInitFlag()) { LogFatal("not initted!"); return false; } const Unicode& uintVec = nodeInfo.word; TrieNode* p = _root; for(uint i = 0; i < uintVec.size(); i++) { uint16_t cu = uintVec[i]; if(NULL == p) { return false; } if(p->hmap.end() == p->hmap.find(cu)) { TrieNode * next = NULL; try { next = new TrieNode; } catch(const bad_alloc& e) { return false; } p->hmap[cu] = next; p = next; } else { p = p->hmap[cu]; } } if(NULL == p) { return false; } if(p->isLeaf) { LogError("this node already inserted"); return false; } p->isLeaf = true; _nodeInfoVec.push_back(nodeInfo); p->nodeInfoVecPos = _nodeInfoVec.size() - 1; return true; } private: bool _trieInsert(const char * const filePath) { ifstream ifile(filePath); string line; vector<string> vecBuf; TrieNodeInfo nodeInfo; while(getline(ifile, line)) { vecBuf.clear(); splitStr(line, vecBuf, " "); if(3 < vecBuf.size()) { LogError("line[%s] illegal.", line.c_str()); return false; } if(!TransCode::decode(vecBuf[0], nodeInfo.word)) { return false; } nodeInfo.freq = atoi(vecBuf[1].c_str()); if(3 == vecBuf.size()) { nodeInfo.tag = vecBuf[2]; } //insert node if(!insert(nodeInfo)) { LogError("insert node failed!"); } } return true; } bool _countWeight() { if(_nodeInfoVec.empty() || 0 != _freqSum) { LogError("_nodeInfoVec is empty or _freqSum has been counted already."); return false; } //freq total freq for(size_t i = 0; i < _nodeInfoVec.size(); i++) { _freqSum += _nodeInfoVec[i].freq; } if(0 == _freqSum) { LogError("_freqSum == 0 ."); return false; } //normalize for(uint i = 0; i < _nodeInfoVec.size(); i++) { TrieNodeInfo& nodeInfo = _nodeInfoVec[i]; if(0 == nodeInfo.freq) { LogFatal("nodeInfo.freq == 0!"); return false; } nodeInfo.logFreq = log(double(nodeInfo.freq)/double(_freqSum)); if(_minLogFreq > nodeInfo.logFreq) { _minLogFreq = nodeInfo.logFreq; } } return true; } bool _deleteNode(TrieNode* node) { for(TrieNodeMap::iterator it = node->hmap.begin(); it != node->hmap.end(); it++) { TrieNode* next = it->second; _deleteNode(next); } delete node; return true; } }; } #endif <|endoftext|>
<commit_before>#include "rsa-crypt-lib.hh" #include <gmpxx.h> #include <vector> #include <iostream> #include <tuple> // std::tuple #include <algorithm> // std::min #include <dgcrypto/dgcrypto.hh> // to use 'random' is there more specific header? // I meant #include <random> for std::random_device // #include <random> // sam: don't need this if we use dgrandprime // generates two random primes and checks coprimality RsaKeys::RsaKeys(mp_bitcnt_t k) : bits_{k} { // generate p and q std::tuple<mpz_class, mpz_class> keys = generate_keys(); mpz_class q = std::get<0>(keys); mpz_class p = std::get<1>(keys); // compute n this->n_ = compute_n(p, q); // compute totient this->totient_ = compute_totient(p, q); // compute e this->e_ = compute_e(this->totient_); // compute d this->d_ = calculate_d(totient_, e_); // public key this->encode_ = encode("Hello", e(), n()); //std::cout<<"result of my_pow : "<<my_pow(2,8)<<std::endl; this-> decode_ = decode(encode_result(), d(), n()); // private key // std::cerr<<"Public key is : "<<p<<q<<d_<<std::endl; } //encodes message std::string RsaKeys::encode(std::string message, mpz_class e, mpz_class n) { std::string inter = ""; mpz_class cipher; std::string result = ""; if(message.length() > 20){ int k = 0; int i = 0; while(i < message.length()){ while(i < message.length() && k < 20){ mpz_class temp = (int) message.at(i); inter = temp.get_str(); i++; k++; } mpz_class pTxt = mpz_class(inter); // cipher = my_pow(pTxt, e) % n; mpz_ui_pow_ui(cipher.get_mpz_t(), pTxt, e); result += cipher.get_str() + 'n'; inter = ""; k = 0; } std::cout<<"result is : "<<result<<std::endl; return result; } else{ for( int i = 0; i < message.length(); ++i) { mpz_class temp = (int) message.at(i); inter += temp.get_str(); } mpz_class pTxt = mpz_class(inter); std::cout<<"pTxt"<<pTxt<<std::endl; //cipher = my_pow(pTxt, e) %n; mpz_ui_pow_ui(cipher.get_mpz_t(), pTxt.get_mpz_t(), e.get_mpz_t()); result = cipher.get_str(); return result; } return "Error"; } //pow didn't work so had to generate my own mpz_class RsaKeys::my_pow(mpz_class base, mpz_class exp) { mpz_class result = 1; for(mpz_class i = 0; i < exp; ++i){ result = result*base; } return result; } std::string RsaKeys::decode(std::string cryptText, mpz_class d, mpz_class n){ std::cout<<"D is : "<< d<<std::endl; std::cout<<"N is : "<<n<<std::endl; std::cout<<"message to be decoded : "<<cryptText<<std::endl; std::string base = cryptText; std::string part = ""; std::vector<std::string> partition; mpz_class nCount = 0; for(int i = 0; i < base.length(); ++i){ if(base.at(i) == 'n'){ partition.push_back(part); nCount++; part = ""; } else { part += base.at(i); } } if(nCount == 0) partition.push_back(part); std::string buffer = ""; for(int i = 0; i < partition.size(); ++i){ mpz_class cTxt = mpz_class(partition.at(i)); std::cout<<"cTxt : "<< cTxt<<std::endl; mpz_class pTxt = my_pow(cTxt, d) % n; std::cout<<"pTxt : " <<pTxt<<std::endl; buffer += pTxt.get_str(); } std::string buffer2 = ""; std::string output = ""; for(int i = 0; i < buffer.length(); ++i){ buffer2 = ""; if(buffer.at(i) == '1'){ buffer2 += buffer.at(i); i++; buffer2 += buffer.at(i); i++; buffer2 += buffer.at(i); } else { buffer2 += buffer.at(i); i++; buffer2 += buffer.at(i); } std::cout<<"Buffer 2 value : "<<buffer2<<std::endl; output += (char) stoi(buffer2); } return output; } // helper function to check for primality // generates two random primes and checks coprimality const std::tuple<mpz_class, mpz_class> RsaKeys::generate_keys() const { dgrandprime p(bits_); dgrandprime q(bits_); return std::make_tuple(p.get_mpz_class(), q.get_mpz_class()); } mpz_class RsaKeys::calculate_d(mpz_class totient, mpz_class e) { // we want the second value: y mpz_class d = extended_euclidean(totient, e)[1]; // make sure d is in our bounds mpz_class bounded_d = d % totient; // -- Function: void mpz_mod (mpz_t R, const mpz_t N, const mpz_t D) // C++ mod arithmetic not suitable if d is negative // http://stackoverflow.com/a/12089637 if (bounded_d < 0) { bounded_d = bounded_d + totient; } return bounded_d; } std::vector<mpz_class> RsaKeys::extended_euclidean(mpz_class a, mpz_class b) { std::vector<mpz_class> x_y_gcd(3); mpz_class x, last_x, y, last_y, r, last_r; x = last_y = 0; y = last_x = 1; r = b; last_r = a; while (r != 0) { mpz_class q = last_r / r; // floor division because of int type // mpz_class r = b % a; mpz_class tmp = r; r = last_r - q * tmp; last_r = tmp; tmp = x; x = last_x - q * tmp; last_x = tmp; tmp = y; y = last_y - q * tmp; last_y = tmp; } x_y_gcd = {last_x, last_y, last_r}; return x_y_gcd; } // helper function to get gcd const mpz_class RsaKeys::get_gcd(mpz_class p, mpz_class q) const { mpz_class gcd = 1; for (mpz_class i = 1; ((i <= p) && (i <= q)); ++i) { if ((p % i == 0) && (q % i == 0)) { gcd = i; } } return gcd; } // helper function to check for primality inline bool RsaKeys::is_coprime(mpz_class p, mpz_class q) const { return (get_gcd(p, q) != 1) ? false : true; } const mpz_class RsaKeys::compute_e(mpz_class totient) { // why not use dgrandominteger...this is what it's for dgrandprime e(bits_); if (bits_ > 17) { return 65537; } else { for (int i = 0; i < 9; ++i) { if (is_coprime(e.get_mpz_class(), totient)) { return e.get_mpz_class(); } else { e.reroll(); } } } std::cerr << "no coprime values"; return 0; } <commit_msg>added more comments<commit_after>#include "rsa-crypt-lib.hh" #include <gmpxx.h> #include <vector> #include <iostream> #include <tuple> // std::tuple #include <algorithm> // std::min #include <dgcrypto/dgcrypto.hh> // to use 'random' is there more specific header? // I meant #include <random> for std::random_device // #include <random> // sam: don't need this if we use dgrandprime // generates two random primes and checks coprimality RsaKeys::RsaKeys(mp_bitcnt_t k) : bits_{k} { // generate p and q std::tuple<mpz_class, mpz_class> keys = generate_keys(); mpz_class q = std::get<0>(keys); mpz_class p = std::get<1>(keys); // compute n this->n_ = compute_n(p, q); // compute totient this->totient_ = compute_totient(p, q); // compute e this->e_ = compute_e(this->totient_); // compute d this->d_ = calculate_d(totient_, e_); // public key this->encode_ = encode("Hello", e(), n()); //std::cout<<"result of my_pow : "<<my_pow(2,8)<<std::endl; this-> decode_ = decode(encode_result(), d(), n()); // private key // std::cerr<<"Public key is : "<<p<<q<<d_<<std::endl; } //encodes message std::string RsaKeys::encode(std::string message, mpz_class e, mpz_class n) { std::string inter = ""; mpz_class cipher; std::string result = ""; //if the message is greater than 20 characters if(message.length() > 20){ int k = 0; int i = 0; while(i < message.length()){ //gets 20 chars in message and adds a 'n' to the end after passing through formula while(i < message.length() && k < 20){ //converts to ascii value mpz_class temp = (int) message.at(i); inter = temp.get_str(); i++; k++; } mpz_class pTxt = mpz_class(inter); // cipher = my_pow(pTxt, e) % n; mpz_powm_sec(cipher.get_mpz_t(), pTxt, e, n); result += cipher.get_str() + 'n'; inter = ""; k = 0; } std::cout<<"result is : "<<result<<std::endl; return result; } else{ //if message is less than 20 chars just go ahead and stick in formula for( int i = 0; i < message.length(); ++i) { mpz_class temp = (int) message.at(i); inter += temp.get_str(); } mpz_class pTxt = mpz_class(inter); std::cout<<"pTxt"<<pTxt<<std::endl; //cipher = my_pow(pTxt, e) %n; mpz_powm_sec(cipher.get_mpz_t(), pTxt.get_mpz_t(), e.get_mpz_t(), n); result = cipher.get_str(); return result; } return "Error"; } //pow didn't work so had to generate my own //piece of crap, takes too long. doesn't work mpz_class RsaKeys::my_pow(mpz_class base, mpz_class exp) { mpz_class result = 1; for(mpz_class i = 0; i < exp; ++i){ result = result*base; } return result; } //makes a vector of partitions std::string RsaKeys::decode(std::string cryptText, mpz_class d, mpz_class n){ std::cout<<"D is : "<< d<<std::endl; std::cout<<"N is : "<<n<<std::endl; std::cout<<"message to be decoded : "<<cryptText<<std::endl; std::string base = cryptText; std::string part = ""; std::vector<std::string> partition; mpz_class nCount = 0; //traverses string and puts everything befor n in formula to convert back to ascii for(int i = 0; i < base.length(); ++i){ if(base.at(i) == 'n'){ partition.push_back(part); nCount++; part = ""; } else { part += base.at(i); } } if(nCount == 0) partition.push_back(part); std::string buffer = ""; for(int i = 0; i < partition.size(); ++i){ mpz_class cTxt = mpz_class(partition.at(i)); std::cout<<"cTxt : "<< cTxt<<std::endl; //mpz_class pTxt = my_pow(cTxt, d) % n; mpz_class pTxt; mpz_powm_sec(pTxt, cTxt, d, n); std::cout<<"pTxt : " <<pTxt<<std::endl; buffer += pTxt.get_str(); } std::string buffer2 = ""; std::string output = ""; //because if way ascii table setup, if ascii starts with one //taake the next two digits to convert back to letter //if ascii starts with anything else, take next one for(int i = 0; i < buffer.length(); ++i){ buffer2 = ""; if(buffer.at(i) == '1'){ buffer2 += buffer.at(i); i++; buffer2 += buffer.at(i); i++; buffer2 += buffer.at(i); } else { buffer2 += buffer.at(i); i++; buffer2 += buffer.at(i); } std::cout<<"Buffer 2 value : "<<buffer2<<std::endl; output += (char) stoi(buffer2); } return output; } // helper function to check for primality // generates two random primes and checks coprimality const std::tuple<mpz_class, mpz_class> RsaKeys::generate_keys() const { dgrandprime p(bits_); dgrandprime q(bits_); return std::make_tuple(p.get_mpz_class(), q.get_mpz_class()); } mpz_class RsaKeys::calculate_d(mpz_class totient, mpz_class e) { // we want the second value: y mpz_class d = extended_euclidean(totient, e)[1]; // make sure d is in our bounds mpz_class bounded_d = d % totient; // -- Function: void mpz_mod (mpz_t R, const mpz_t N, const mpz_t D) // C++ mod arithmetic not suitable if d is negative // http://stackoverflow.com/a/12089637 if (bounded_d < 0) { bounded_d = bounded_d + totient; } return bounded_d; } std::vector<mpz_class> RsaKeys::extended_euclidean(mpz_class a, mpz_class b) { std::vector<mpz_class> x_y_gcd(3); mpz_class x, last_x, y, last_y, r, last_r; x = last_y = 0; y = last_x = 1; r = b; last_r = a; while (r != 0) { mpz_class q = last_r / r; // floor division because of int type // mpz_class r = b % a; mpz_class tmp = r; r = last_r - q * tmp; last_r = tmp; tmp = x; x = last_x - q * tmp; last_x = tmp; tmp = y; y = last_y - q * tmp; last_y = tmp; } x_y_gcd = {last_x, last_y, last_r}; return x_y_gcd; } // helper function to get gcd const mpz_class RsaKeys::get_gcd(mpz_class p, mpz_class q) const { mpz_class gcd = 1; for (mpz_class i = 1; ((i <= p) && (i <= q)); ++i) { if ((p % i == 0) && (q % i == 0)) { gcd = i; } } return gcd; } // helper function to check for primality inline bool RsaKeys::is_coprime(mpz_class p, mpz_class q) const { return (get_gcd(p, q) != 1) ? false : true; } const mpz_class RsaKeys::compute_e(mpz_class totient) { // why not use dgrandominteger...this is what it's for dgrandprime e(bits_); if (bits_ > 17) { return 65537; } else { for (int i = 0; i < 9; ++i) { if (is_coprime(e.get_mpz_class(), totient)) { return e.get_mpz_class(); } else { e.reroll(); } } } std::cerr << "no coprime values"; return 0; } <|endoftext|>
<commit_before>#include <QCoreApplication> #include <QFileInfo> #include "TumorOnlyReportWorker.h" #include "QCCollection.h" #include "Exceptions.h" #include "Statistics.h" #include "LoginManager.h" #include "RtfDocument.h" TumorOnlyReportWorker::TumorOnlyReportWorker(const VariantList& variants, const TumorOnlyReportWorkerConfig& config) : config_(config) , variants_(variants) , db_(config.use_test_db) { //set annotation indices i_co_sp_ = variants_.annotationIndexByName("coding_and_splicing"); i_tum_af_ = variants_.annotationIndexByName("tumor_af"); i_cgi_driver_statem_ = variants_.annotationIndexByName("CGI_driver_statement"); i_ncg_oncogene_ = variants_.annotationIndexByName("ncg_oncogene"); i_ncg_tsg_ = variants_.annotationIndexByName("ncg_tsg"); i_germl_class_ = variants_.annotationIndexByName("classification"); i_somatic_class_ = variants_.annotationIndexByName("somatic_classification"); //Set up RTF file specifications doc_.setMargins(1134,1134,1134,1134); doc_.addColor(188,230,138); doc_.addColor(255,0,0); doc_.addColor(255,255,0); doc_.addColor(161,161,161); doc_.addColor(217,217,217); } void TumorOnlyReportWorker::checkAnnotation(const VariantList &variants) { const QStringList anns = {"coding_and_splicing", "tumor_af", "tumor_dp", "gene", "variant_type", "CGI_driver_statement", "ncg_oncogene", "ncg_tsg", "classification", "somatic_classification"}; for(const auto& ann : anns) { if( variants.annotationIndexByName(ann, true, false) < 0) THROW(FileParseException, "Could not find column " + ann + " for tumor only report in variant list."); } } QByteArray TumorOnlyReportWorker::variantDescription(const Variant &var) { QByteArrayList out; //NCG gene classification if(var.annotations()[i_ncg_tsg_].contains("1")) out << "TSG"; if(var.annotations()[i_ncg_oncogene_].contains("1")) out << "Onkogen"; //germline in-house classification if(var.annotations()[i_germl_class_] == "4" || var.annotations()[i_germl_class_] == "5") out << "Keimbahn: Klasse " + var.annotations()[i_germl_class_]; //somatic in-house classification if(!var.annotations()[i_somatic_class_].isEmpty() && var.annotations()[i_somatic_class_] != "n/a") { out << "Somatik: " + trans(var.annotations()[i_somatic_class_]); } //CGI classification if(var.annotations()[i_cgi_driver_statem_].contains("known")) out << "CGI: Treiber (bekannt)"; else if(var.annotations()[i_cgi_driver_statem_].contains("predicted driver")) out << "CGI: Treiber (vorhergesagt)"; return out.join(", \\line\n"); } QByteArray TumorOnlyReportWorker::trans(QByteArray english) { static QHash<QByteArray, QByteArray> en2de; en2de["activating"] = "aktivierend"; en2de["likely_activating"] = "wahrscheinlich aktivierend"; en2de["inactivating"] = "inaktivierend"; en2de["likely_inactivating"] = "wahrscheinlich inaktivierend"; en2de["unclear"] = "unklar"; en2de["test_dependent"] = "testabhängig"; if(!en2de.contains(english)) return english; return en2de[english]; } QByteArray TumorOnlyReportWorker::exonNumber(QByteArray gene, int start, int end) { //get approved gene name int gene_id = db_.geneToApprovedID(gene); if (gene_id==-1) return ""; gene = db_.geneSymbol(gene_id); //select transcripts QList<Transcript> transcripts; try { if(config_.preferred_transcripts.contains(gene)) { for(QByteArray preferred_trans : config_.preferred_transcripts.value(gene)) { transcripts << db_.transcript(db_.transcriptId(preferred_trans)); } } else //fallback to longest coding transcript { transcripts << db_.longestCodingTranscript(gene_id, Transcript::SOURCE::ENSEMBL, false, true); } } catch(Exception) { return ""; } //calculate exon number QByteArrayList out; for(const Transcript& trans : transcripts) { int exon_number = trans.exonNumber(start, end); if(exon_number<=0) continue; out << trans.name() + " (exon " + QByteArray::number(exon_number) + "/" + QByteArray::number(trans.regions().count()) + ")"; } return out.join(",\\line\n"); } QByteArray TumorOnlyReportWorker::cgiCancerTypeFromVariantList(const VariantList &variants) { QStringList comments = variants.comments(); foreach(QString comment,comments) { if(comment.startsWith("##CGI_CANCER_TYPE=")) { QByteArray cancer_type = comment.mid(18).trimmed().toUtf8(); if(!cancer_type.isEmpty()) return cancer_type; else return "n/a"; } } return "n/a"; } void TumorOnlyReportWorker::writeRtf(QByteArray file_path) { //Write SNV table RtfTable snv_table; for(int i=0; i<variants_.count(); ++i) { if(!config_.filter_result.passing(i)) continue; RtfTableRow row; VariantTranscript trans = variants_[i].transcriptAnnotations(i_co_sp_).first(); for(const VariantTranscript& tmp_trans : variants_[i].transcriptAnnotations(i_co_sp_)) { if(config_.preferred_transcripts.value(tmp_trans.gene).contains(tmp_trans.idWithoutVersion())) { trans = tmp_trans; break; } } row.addCell( 1000, trans.gene , RtfParagraph().setItalic(true) ); row.addCell( { trans.hgvs_c + ", " + trans.hgvs_p, RtfText(trans.id).setFontSize(14).RtfCode()}, 2900 ); row.addCell( 1700, trans.type.replace("_variant", "").replace("&", ", ") ); row.addCell( 900, QByteArray::number(variants_[i].annotations()[i_tum_af_].toDouble(),'f',2) ); row.addCell( 3138, variantDescription(variants_[i]) ); snv_table.addRow(row); } //sort SNVs by gene symbol snv_table.sortByCol(0); //SNV table headline snv_table.prependRow(RtfTableRow({"Gen","Veränderung","Typ","Anteil","Beschreibung"},{1000,2900,1700,900,3138},RtfParagraph().setBold(true).setHorizontalAlignment("c")).setHeader()); snv_table.prependRow(RtfTableRow("Punktmutationen (SNVS) und kleine Insertionen/Deletionen (INDELs)",doc_.maxWidth(),RtfParagraph().setBold(true).setHorizontalAlignment("c")).setBackgroundColor(5).setHeader()); snv_table.setUniqueBorder(1,"brdrhair"); doc_.addPart( snv_table.RtfCode() ); doc_.addPart( RtfParagraph("").RtfCode() ); //Create table with additional report data QCCollection qc_mapping = db_.getQCData(db_.processedSampleId(config_.ps)); RtfTable metadata; metadata.addRow( RtfTableRow( { RtfText("Allgemeine Informationen").setBold(true).setFontSize(16).RtfCode(), RtfText("Qualitätsparameter").setBold(true).setFontSize(16).RtfCode() }, {5000,4638}) ); metadata.addRow( RtfTableRow( { "Datum:",QDate::currentDate().toString("dd.MM.yyyy").toUtf8(), "Coverage 100x:", qc_mapping.value("QC:2000030",true).toString().toUtf8() + "\%"}, {2250,2750,2319,2319}) ); metadata.addRow( RtfTableRow( { "Analysepipeline:", variants_.getPipeline().toUtf8(), "Coverage 500x:", qc_mapping.value("QC:2000032",true).toString().toUtf8() + "\%"} , {2250, 2750, 2319, 2319} ) ); metadata.addRow( RtfTableRow( { "Auswertungssoftware:", QCoreApplication::applicationName().toUtf8() + " " + QCoreApplication::applicationVersion().toUtf8(), "Durchschnittliche Tiefe", qc_mapping.value("QC:2000025",true).toString().toUtf8() + "x"}, {2250,2750,2319,2319}) ); metadata.addRow( RtfTableRow( { "CGI-Tumortyp:", cgiCancerTypeFromVariantList(variants_), "", ""} , {2250,2750,2319,2319} ) ); metadata.setUniqueFontSize(16); doc_.addPart(metadata.RtfCode()); doc_.addPart(RtfParagraph("").RtfCode()); //gap statistics if target file exists if(config_.roi.isValid() && QFileInfo::exists(config_.low_coverage_file)) { doc_.addPart(RtfParagraph("Statistik:").setBold(true).setSpaceAfter(45).setSpaceBefore(45).setFontSize(16).RtfCode()); RtfTable table; table.addRow( RtfTableRow( {"Zielregion:", config_.roi.name.toUtf8()} , {1700,7938} ) ); if(!config_.roi.genes.isEmpty()) { table.addRow( RtfTableRow({"Zielregion Gene (" + QByteArray::number(config_.roi.genes.count())+"):", config_.roi.genes.join(", ")} , {1700,7938}) ); } table.addRow( RtfTableRow({"Zielregion Region:",QByteArray::number(config_.roi.regions.count())} , {1700,7938}) ); table.addRow( RtfTableRow({"Zielregion Basen:",QByteArray::number(config_.roi.regions.baseCount())} , {1700,7938}) ); //Low coverage statistics of target region BedFile low_cov; low_cov.load(config_.low_coverage_file); low_cov.intersect(config_.roi.regions); table.addRow( RtfTableRow( {"Lücken Regionen:",QByteArray::number(low_cov.count())}, {1700,7938}) ); table.addRow( RtfTableRow( {"Lücken Basen:",QByteArray::number(low_cov.baseCount()) + " (" + QByteArray::number(100.0 * low_cov.baseCount()/config_.roi.regions.baseCount(), 'f', 2) + "%)"},{1700,7938}) ); table.setUniqueFontSize(16); doc_.addPart( table.RtfCode() ); doc_.addPart(RtfParagraph("").RtfCode()); //Add coverage per gap as annotation to low cov file if(config_.include_coverage_per_gap) { Statistics::avgCoverage(low_cov, config_.bam_file, 1, false, true, 2); } //Find genes with gaps QVector<QByteArray> genes; QVector<QByteArray> exons; //block summary of gaps that overlap an exon, to be printed after gap statistics in table QMultiMap<QString, QString> block_summary; for(int i=0; i<low_cov.count(); ++i) { const BedLine& line = low_cov[i]; QStringList tmp_genes = db_.genesOverlapping(line.chr(), line.start(), line.end()).toStringList(); genes.append( tmp_genes.join(", ").toUtf8() ); if(config_.include_exon_number_per_gap) { QStringList tmp_exons; for(const auto& tmp_gene : tmp_genes) { QByteArray exon = exonNumber(tmp_gene.toUtf8() , line.start(), line.end()); if(exon != "") { tmp_exons << exon; block_summary.insert(tmp_gene, line.toString(true)); } } exons.append( tmp_exons.join(", ").toUtf8() ); } } //Write each gaps RtfTable detailed_gaps; for(int i=0; i< low_cov.count(); ++i) { RtfTableRow row; if(!genes.isEmpty()) { row.addCell(2000, genes[i], RtfParagraph().setItalic(true)); } else { row.addCell(2000,"NA"); } RtfSourceCode pos = low_cov[i].chr().strNormalized(true) + ":" + QByteArray::number(low_cov[i].start()) + "-" + QByteArray::number(low_cov[i].end()); if(!exons.isEmpty() && !exons[i].isEmpty()) pos += RtfText("\\line\n" + exons[i]).setFontSize(14).RtfCode(); row.addCell(3500, pos); if(config_.include_coverage_per_gap) row.addCell(4138, low_cov[i].annotations().last() + "x"); detailed_gaps.addRow(row); } //sort by gene symbol, then by coordinate column detailed_gaps.sortbyCols({0,1}); //add header if(low_cov.count()>0) { detailed_gaps.prependRow(RtfTableRow({"Gen", "Lücke"}, {2000,3500}, RtfParagraph().setBold(true) ).setHeader() ); if(config_.include_coverage_per_gap) detailed_gaps.first().addCell(4138, "Coverage", RtfParagraph().setBold(true) ); } detailed_gaps.setUniqueFontSize(16); doc_.addPart(detailed_gaps.RtfCode()); //add block summary of exon gaps if(!block_summary.isEmpty()) { QList<RtfSourceCode> block_text; for( const auto& gene : block_summary.uniqueKeys() ) { block_text << RtfText(gene.toUtf8()).setItalic(true).setFontSize(16).RtfCode() + ": " + block_summary.values(gene).join(", ").toUtf8(); } doc_.addPart(RtfParagraph("").RtfCode()); doc_.addPart(RtfParagraph(block_text.join("; ")).setFontSize(16).RtfCode()); } } doc_.save(file_path); } <commit_msg>TumorOnlyReportWorker: Modified so that it now also works without CGI annotation.<commit_after>#include <QCoreApplication> #include <QFileInfo> #include "TumorOnlyReportWorker.h" #include "QCCollection.h" #include "Exceptions.h" #include "Statistics.h" #include "LoginManager.h" #include "RtfDocument.h" TumorOnlyReportWorker::TumorOnlyReportWorker(const VariantList& variants, const TumorOnlyReportWorkerConfig& config) : config_(config) , variants_(variants) , db_(config.use_test_db) { //set annotation indices i_co_sp_ = variants_.annotationIndexByName("coding_and_splicing"); i_tum_af_ = variants_.annotationIndexByName("tumor_af"); i_cgi_driver_statem_ = variants_.annotationIndexByName("CGI_driver_statement", true, false); i_ncg_oncogene_ = variants_.annotationIndexByName("ncg_oncogene"); i_ncg_tsg_ = variants_.annotationIndexByName("ncg_tsg"); i_germl_class_ = variants_.annotationIndexByName("classification"); i_somatic_class_ = variants_.annotationIndexByName("somatic_classification"); //Set up RTF file specifications doc_.setMargins(1134,1134,1134,1134); doc_.addColor(188,230,138); doc_.addColor(255,0,0); doc_.addColor(255,255,0); doc_.addColor(161,161,161); doc_.addColor(217,217,217); } void TumorOnlyReportWorker::checkAnnotation(const VariantList &variants) { const QStringList anns = {"coding_and_splicing", "tumor_af", "tumor_dp", "gene", "variant_type", "ncg_oncogene", "ncg_tsg", "classification", "somatic_classification"}; for(const auto& ann : anns) { if( variants.annotationIndexByName(ann, true, false) < 0) THROW(FileParseException, "Could not find column " + ann + " for tumor only report in variant list."); } } QByteArray TumorOnlyReportWorker::variantDescription(const Variant &var) { QByteArrayList out; //NCG gene classification if(var.annotations()[i_ncg_tsg_].contains("1")) out << "TSG"; if(var.annotations()[i_ncg_oncogene_].contains("1")) out << "Onkogen"; //germline in-house classification if(var.annotations()[i_germl_class_] == "4" || var.annotations()[i_germl_class_] == "5") out << "Keimbahn: Klasse " + var.annotations()[i_germl_class_]; //somatic in-house classification if(!var.annotations()[i_somatic_class_].isEmpty() && var.annotations()[i_somatic_class_] != "n/a") { out << "Somatik: " + trans(var.annotations()[i_somatic_class_]); } //CGI classification if(i_cgi_driver_statem_ >= 0) { if(var.annotations()[i_cgi_driver_statem_].contains("known")) out << "CGI: Treiber (bekannt)"; else if(var.annotations()[i_cgi_driver_statem_].contains("predicted driver")) out << "CGI: Treiber (vorhergesagt)"; } return out.join(", \\line\n"); } QByteArray TumorOnlyReportWorker::trans(QByteArray english) { static QHash<QByteArray, QByteArray> en2de; en2de["activating"] = "aktivierend"; en2de["likely_activating"] = "wahrscheinlich aktivierend"; en2de["inactivating"] = "inaktivierend"; en2de["likely_inactivating"] = "wahrscheinlich inaktivierend"; en2de["unclear"] = "unklar"; en2de["test_dependent"] = "testabhängig"; if(!en2de.contains(english)) return english; return en2de[english]; } QByteArray TumorOnlyReportWorker::exonNumber(QByteArray gene, int start, int end) { //get approved gene name int gene_id = db_.geneToApprovedID(gene); if (gene_id==-1) return ""; gene = db_.geneSymbol(gene_id); //select transcripts QList<Transcript> transcripts; try { if(config_.preferred_transcripts.contains(gene)) { for(QByteArray preferred_trans : config_.preferred_transcripts.value(gene)) { transcripts << db_.transcript(db_.transcriptId(preferred_trans)); } } else //fallback to longest coding transcript { transcripts << db_.longestCodingTranscript(gene_id, Transcript::SOURCE::ENSEMBL, false, true); } } catch(Exception) { return ""; } //calculate exon number QByteArrayList out; for(const Transcript& trans : transcripts) { int exon_number = trans.exonNumber(start, end); if(exon_number<=0) continue; out << trans.name() + " (exon " + QByteArray::number(exon_number) + "/" + QByteArray::number(trans.regions().count()) + ")"; } return out.join(",\\line\n"); } QByteArray TumorOnlyReportWorker::cgiCancerTypeFromVariantList(const VariantList &variants) { QStringList comments = variants.comments(); foreach(QString comment,comments) { if(comment.startsWith("##CGI_CANCER_TYPE=")) { QByteArray cancer_type = comment.mid(18).trimmed().toUtf8(); if(!cancer_type.isEmpty()) return cancer_type; else return "n/a"; } } return "n/a"; } void TumorOnlyReportWorker::writeRtf(QByteArray file_path) { //Write SNV table RtfTable snv_table; for(int i=0; i<variants_.count(); ++i) { if(!config_.filter_result.passing(i)) continue; RtfTableRow row; VariantTranscript trans = variants_[i].transcriptAnnotations(i_co_sp_).first(); for(const VariantTranscript& tmp_trans : variants_[i].transcriptAnnotations(i_co_sp_)) { if(config_.preferred_transcripts.value(tmp_trans.gene).contains(tmp_trans.idWithoutVersion())) { trans = tmp_trans; break; } } row.addCell( 1000, trans.gene , RtfParagraph().setItalic(true) ); row.addCell( { trans.hgvs_c + ", " + trans.hgvs_p, RtfText(trans.id).setFontSize(14).RtfCode()}, 2900 ); row.addCell( 1700, trans.type.replace("_variant", "").replace("&", ", ") ); row.addCell( 900, QByteArray::number(variants_[i].annotations()[i_tum_af_].toDouble(),'f',2) ); row.addCell( 3138, variantDescription(variants_[i]) ); snv_table.addRow(row); } //sort SNVs by gene symbol snv_table.sortByCol(0); //SNV table headline snv_table.prependRow(RtfTableRow({"Gen","Veränderung","Typ","Anteil","Beschreibung"},{1000,2900,1700,900,3138},RtfParagraph().setBold(true).setHorizontalAlignment("c")).setHeader()); snv_table.prependRow(RtfTableRow("Punktmutationen (SNVS) und kleine Insertionen/Deletionen (INDELs)",doc_.maxWidth(),RtfParagraph().setBold(true).setHorizontalAlignment("c")).setBackgroundColor(5).setHeader()); snv_table.setUniqueBorder(1,"brdrhair"); doc_.addPart( snv_table.RtfCode() ); doc_.addPart( RtfParagraph("").RtfCode() ); //Create table with additional report data QCCollection qc_mapping = db_.getQCData(db_.processedSampleId(config_.ps)); RtfTable metadata; metadata.addRow( RtfTableRow( { RtfText("Allgemeine Informationen").setBold(true).setFontSize(16).RtfCode(), RtfText("Qualitätsparameter").setBold(true).setFontSize(16).RtfCode() }, {5000,4638}) ); metadata.addRow( RtfTableRow( { "Datum:",QDate::currentDate().toString("dd.MM.yyyy").toUtf8(), "Coverage 100x:", qc_mapping.value("QC:2000030",true).toString().toUtf8() + "\%"}, {2250,2750,2319,2319}) ); metadata.addRow( RtfTableRow( { "Analysepipeline:", variants_.getPipeline().toUtf8(), "Coverage 500x:", qc_mapping.value("QC:2000032",true).toString().toUtf8() + "\%"} , {2250, 2750, 2319, 2319} ) ); metadata.addRow( RtfTableRow( { "Auswertungssoftware:", QCoreApplication::applicationName().toUtf8() + " " + QCoreApplication::applicationVersion().toUtf8(), "Durchschnittliche Tiefe", qc_mapping.value("QC:2000025",true).toString().toUtf8() + "x"}, {2250,2750,2319,2319}) ); metadata.addRow( RtfTableRow( { "CGI-Tumortyp:", cgiCancerTypeFromVariantList(variants_), "", ""} , {2250,2750,2319,2319} ) ); metadata.setUniqueFontSize(16); doc_.addPart(metadata.RtfCode()); doc_.addPart(RtfParagraph("").RtfCode()); //gap statistics if target file exists if(config_.roi.isValid() && QFileInfo::exists(config_.low_coverage_file)) { doc_.addPart(RtfParagraph("Statistik:").setBold(true).setSpaceAfter(45).setSpaceBefore(45).setFontSize(16).RtfCode()); RtfTable table; table.addRow( RtfTableRow( {"Zielregion:", config_.roi.name.toUtf8()} , {1700,7938} ) ); if(!config_.roi.genes.isEmpty()) { table.addRow( RtfTableRow({"Zielregion Gene (" + QByteArray::number(config_.roi.genes.count())+"):", config_.roi.genes.join(", ")} , {1700,7938}) ); } table.addRow( RtfTableRow({"Zielregion Region:",QByteArray::number(config_.roi.regions.count())} , {1700,7938}) ); table.addRow( RtfTableRow({"Zielregion Basen:",QByteArray::number(config_.roi.regions.baseCount())} , {1700,7938}) ); //Low coverage statistics of target region BedFile low_cov; low_cov.load(config_.low_coverage_file); low_cov.intersect(config_.roi.regions); table.addRow( RtfTableRow( {"Lücken Regionen:",QByteArray::number(low_cov.count())}, {1700,7938}) ); table.addRow( RtfTableRow( {"Lücken Basen:",QByteArray::number(low_cov.baseCount()) + " (" + QByteArray::number(100.0 * low_cov.baseCount()/config_.roi.regions.baseCount(), 'f', 2) + "%)"},{1700,7938}) ); table.setUniqueFontSize(16); doc_.addPart( table.RtfCode() ); doc_.addPart(RtfParagraph("").RtfCode()); //Add coverage per gap as annotation to low cov file if(config_.include_coverage_per_gap) { Statistics::avgCoverage(low_cov, config_.bam_file, 1, false, true, 2); } //Find genes with gaps QVector<QByteArray> genes; QVector<QByteArray> exons; //block summary of gaps that overlap an exon, to be printed after gap statistics in table QMultiMap<QString, QString> block_summary; for(int i=0; i<low_cov.count(); ++i) { const BedLine& line = low_cov[i]; QStringList tmp_genes = db_.genesOverlapping(line.chr(), line.start(), line.end()).toStringList(); genes.append( tmp_genes.join(", ").toUtf8() ); if(config_.include_exon_number_per_gap) { QStringList tmp_exons; for(const auto& tmp_gene : tmp_genes) { QByteArray exon = exonNumber(tmp_gene.toUtf8() , line.start(), line.end()); if(exon != "") { tmp_exons << exon; block_summary.insert(tmp_gene, line.toString(true)); } } exons.append( tmp_exons.join(", ").toUtf8() ); } } //Write each gaps RtfTable detailed_gaps; for(int i=0; i< low_cov.count(); ++i) { RtfTableRow row; if(!genes.isEmpty()) { row.addCell(2000, genes[i], RtfParagraph().setItalic(true)); } else { row.addCell(2000,"NA"); } RtfSourceCode pos = low_cov[i].chr().strNormalized(true) + ":" + QByteArray::number(low_cov[i].start()) + "-" + QByteArray::number(low_cov[i].end()); if(!exons.isEmpty() && !exons[i].isEmpty()) pos += RtfText("\\line\n" + exons[i]).setFontSize(14).RtfCode(); row.addCell(3500, pos); if(config_.include_coverage_per_gap) row.addCell(4138, low_cov[i].annotations().last() + "x"); detailed_gaps.addRow(row); } //sort by gene symbol, then by coordinate column detailed_gaps.sortbyCols({0,1}); //add header if(low_cov.count()>0) { detailed_gaps.prependRow(RtfTableRow({"Gen", "Lücke"}, {2000,3500}, RtfParagraph().setBold(true) ).setHeader() ); if(config_.include_coverage_per_gap) detailed_gaps.first().addCell(4138, "Coverage", RtfParagraph().setBold(true) ); } detailed_gaps.setUniqueFontSize(16); doc_.addPart(detailed_gaps.RtfCode()); //add block summary of exon gaps if(!block_summary.isEmpty()) { QList<RtfSourceCode> block_text; for( const auto& gene : block_summary.uniqueKeys() ) { block_text << RtfText(gene.toUtf8()).setItalic(true).setFontSize(16).RtfCode() + ": " + block_summary.values(gene).join(", ").toUtf8(); } doc_.addPart(RtfParagraph("").RtfCode()); doc_.addPart(RtfParagraph(block_text.join("; ")).setFontSize(16).RtfCode()); } } doc_.save(file_path); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include "list.hpp" #include "shared_realm.hpp" #include <stdexcept> using namespace realm; List::List(std::shared_ptr<Realm> r, const ObjectSchema& s, LinkViewRef l) : m_realm(std::move(r)) , m_object_schema(&s) , m_link_view(std::move(l)) { } List::~List() = default; size_t List::size() { verify_attached(); return m_link_view->size(); } Row List::get(size_t row_ndx) { verify_attached(); verify_valid_row(row_ndx); return m_link_view->get(row_ndx); } void List::set(size_t row_ndx, size_t target_row_ndx) { verify_attached(); verify_in_tranaction(); verify_valid_row(row_ndx); m_link_view->set(row_ndx, target_row_ndx); } void List::add(size_t target_row_ndx) { verify_attached(); verify_in_tranaction(); m_link_view->add(target_row_ndx); } void List::insert(size_t row_ndx, size_t target_row_ndx) { verify_attached(); verify_in_tranaction(); verify_valid_row(row_ndx, true); m_link_view->insert(row_ndx, target_row_ndx); } void List::remove(size_t row_ndx) { verify_attached(); verify_in_tranaction(); verify_valid_row(row_ndx); m_link_view->remove(row_ndx); } Query List::get_query() { verify_attached(); return m_link_view->get_target_table().where(m_link_view); } void List::verify_valid_row(size_t row_ndx, bool insertion) { size_t size = m_link_view->size(); if (row_ndx > size || (!insertion && row_ndx == size)) { throw std::out_of_range("Index " + std::to_string(row_ndx) + " is outside of range 0..." + std::to_string(size) + "."); } } void List::verify_attached() { if (!m_link_view->is_attached()) { throw std::runtime_error("Tableview is not attached"); } } void List::verify_in_tranaction() { if (!m_realm->is_in_transaction()) { throw std::runtime_error("Can only mutate a list within a transaction."); } } <commit_msg>Fix incorrect error message<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include "list.hpp" #include "shared_realm.hpp" #include <stdexcept> using namespace realm; List::List(std::shared_ptr<Realm> r, const ObjectSchema& s, LinkViewRef l) : m_realm(std::move(r)) , m_object_schema(&s) , m_link_view(std::move(l)) { } List::~List() = default; size_t List::size() { verify_attached(); return m_link_view->size(); } Row List::get(size_t row_ndx) { verify_attached(); verify_valid_row(row_ndx); return m_link_view->get(row_ndx); } void List::set(size_t row_ndx, size_t target_row_ndx) { verify_attached(); verify_in_tranaction(); verify_valid_row(row_ndx); m_link_view->set(row_ndx, target_row_ndx); } void List::add(size_t target_row_ndx) { verify_attached(); verify_in_tranaction(); m_link_view->add(target_row_ndx); } void List::insert(size_t row_ndx, size_t target_row_ndx) { verify_attached(); verify_in_tranaction(); verify_valid_row(row_ndx, true); m_link_view->insert(row_ndx, target_row_ndx); } void List::remove(size_t row_ndx) { verify_attached(); verify_in_tranaction(); verify_valid_row(row_ndx); m_link_view->remove(row_ndx); } Query List::get_query() { verify_attached(); return m_link_view->get_target_table().where(m_link_view); } void List::verify_valid_row(size_t row_ndx, bool insertion) { size_t size = m_link_view->size(); if (row_ndx > size || (!insertion && row_ndx == size)) { throw std::out_of_range("Index " + std::to_string(row_ndx) + " is outside of range 0..." + std::to_string(size) + "."); } } void List::verify_attached() { if (!m_link_view->is_attached()) { throw std::runtime_error("LinkView is not attached"); } } void List::verify_in_tranaction() { if (!m_realm->is_in_transaction()) { throw std::runtime_error("Can only mutate a list within a transaction."); } } <|endoftext|>
<commit_before>#include "Util.h" #include "Introspection.h" #include "Debug.h" #include "Error.h" #include <sstream> #include <map> namespace Halide { namespace Internal { using std::string; using std::vector; using std::ostringstream; using std::map; string unique_name(char prefix) { // arrays with static storage duration should be initialized to zero automatically static int instances[256]; ostringstream str; str << prefix << instances[(unsigned char)prefix]++; return str.str(); } bool starts_with(const string &str, const string &prefix) { if (str.size() < prefix.size()) return false; for (size_t i = 0; i < prefix.size(); i++) { if (str[i] != prefix[i]) return false; } return true; } bool ends_with(const string &str, const string &suffix) { if (str.size() < suffix.size()) return false; size_t off = str.size() - suffix.size(); for (size_t i = 0; i < suffix.size(); i++) { if (str[off+i] != suffix[i]) return false; } return true; } string replace_all(string &str, const string &find, const string &replace) { size_t pos = 0; while ((pos = str.find(find, pos)) != string::npos) { str.replace(pos, find.length(), replace); pos += replace.length(); } return str; } /** Convert an integer to a string. */ string int_to_string(int x) { // Most calls to this function are during lowering, and correspond // to the dimensions of some buffer. So this gets called with 0, // 1, 2, and 3 a lot, and it's worth optimizing those cases. static const string small_ints[] = {"0", "1", "2", "3", "4", "5", "6", "7"}; if (x < 8) return small_ints[x]; ostringstream ss; ss << x; return ss.str(); } string unique_name(const string &name, bool user) { static map<string, int> known_names; // An empty string really does not make sense, but use 'z' as prefix. if (name.length() == 0) { return unique_name('z'); } // Check the '$' character doesn't appear in the prefix. This lets // us separate the name from the number using '$' as a delimiter, // which guarantees uniqueness of the generated name, without // having to track all names generated so far. if (user) { for (size_t i = 0; i < name.length(); i++) { user_assert(name[i] != '$') << "Name \"" << name << "\" is invalid. " << "Halide names may not contain the character '$'\n"; } } int &count = known_names[name]; count++; if (count == 1) { // The very first unique name is the original function name itself. return name; } else { // Use the programmer-specified name but append a number to make it unique. ostringstream oss; oss << name << '$' << count; return oss.str(); } } string base_name(const string &name, char delim) { size_t off = name.rfind(delim); if (off == string::npos) { return name; } return name.substr(off+1); } string make_entity_name(void *stack_ptr, const string &type, char prefix) { string name = get_variable_name(stack_ptr, type); if (name.empty()) { return unique_name(prefix); } else { // Halide names may not contain '.' for (size_t i = 0; i < name.size(); i++) { if (name[i] == '.') { name[i] = ':'; } } return unique_name(name); } } std::vector<std::string> split_string(const std::string &source, const std::string &delim) { std::vector<std::string> elements; size_t start = 0; size_t found = 0; while ((found = source.find(delim, start)) != std::string::npos) { elements.push_back(source.substr(start, found - start)); start = found + delim.size(); } // If start is exactly source.size(), the last thing in source is a // delimiter, in which case we want to add an empty string to elements. if (start <= source.size()) { elements.push_back(source.substr(start, std::string::npos)); } return elements; } } } <commit_msg>Fix introspection for NamesInterface<commit_after>#include "Util.h" #include "Introspection.h" #include "Debug.h" #include "Error.h" #include <sstream> #include <map> namespace Halide { namespace Internal { using std::string; using std::vector; using std::ostringstream; using std::map; string unique_name(char prefix) { // arrays with static storage duration should be initialized to zero automatically static int instances[256]; ostringstream str; str << prefix << instances[(unsigned char)prefix]++; return str.str(); } bool starts_with(const string &str, const string &prefix) { if (str.size() < prefix.size()) return false; for (size_t i = 0; i < prefix.size(); i++) { if (str[i] != prefix[i]) return false; } return true; } bool ends_with(const string &str, const string &suffix) { if (str.size() < suffix.size()) return false; size_t off = str.size() - suffix.size(); for (size_t i = 0; i < suffix.size(); i++) { if (str[off+i] != suffix[i]) return false; } return true; } string replace_all(string &str, const string &find, const string &replace) { size_t pos = 0; while ((pos = str.find(find, pos)) != string::npos) { str.replace(pos, find.length(), replace); pos += replace.length(); } return str; } /** Convert an integer to a string. */ string int_to_string(int x) { // Most calls to this function are during lowering, and correspond // to the dimensions of some buffer. So this gets called with 0, // 1, 2, and 3 a lot, and it's worth optimizing those cases. static const string small_ints[] = {"0", "1", "2", "3", "4", "5", "6", "7"}; if (x < 8) return small_ints[x]; ostringstream ss; ss << x; return ss.str(); } string unique_name(const string &name, bool user) { static map<string, int> known_names; // An empty string really does not make sense, but use 'z' as prefix. if (name.length() == 0) { return unique_name('z'); } // Check the '$' character doesn't appear in the prefix. This lets // us separate the name from the number using '$' as a delimiter, // which guarantees uniqueness of the generated name, without // having to track all names generated so far. if (user) { for (size_t i = 0; i < name.length(); i++) { user_assert(name[i] != '$') << "Name \"" << name << "\" is invalid. " << "Halide names may not contain the character '$'\n"; } } int &count = known_names[name]; count++; if (count == 1) { // The very first unique name is the original function name itself. return name; } else { // Use the programmer-specified name but append a number to make it unique. ostringstream oss; oss << name << '$' << count; return oss.str(); } } string base_name(const string &name, char delim) { size_t off = name.rfind(delim); if (off == string::npos) { return name; } return name.substr(off+1); } string make_entity_name(void *stack_ptr, const string &type, char prefix) { string name = get_variable_name(stack_ptr, type); if (name.empty() && starts_with(type, "Halide::")) { // Maybe we're in a generator. Try again replacing any // "Halide::" with "Halide::NamesInterface::" string qualified_type = "Halide::NamesInterface::" + type.substr(8, type.size()-8); debug(0) << qualified_type << "\n"; name = get_variable_name(stack_ptr, qualified_type); } if (name.empty()) { return unique_name(prefix); } else { // Halide names may not contain '.' for (size_t i = 0; i < name.size(); i++) { if (name[i] == '.') { name[i] = ':'; } } return unique_name(name); } } std::vector<std::string> split_string(const std::string &source, const std::string &delim) { std::vector<std::string> elements; size_t start = 0; size_t found = 0; while ((found = source.find(delim, start)) != std::string::npos) { elements.push_back(source.substr(start, found - start)); start = found + delim.size(); } // If start is exactly source.size(), the last thing in source is a // delimiter, in which case we want to add an empty string to elements. if (start <= source.size()) { elements.push_back(source.substr(start, std::string::npos)); } return elements; } } } <|endoftext|>
<commit_before>#include <iostream> #include <thread> #include "plugins/lirch_plugin.h" #include "plugins/edict_messages.h" using namespace std; void send_input(plugin_pipe p) { string line; while (getline(cin, line)) { //I can't use the regular constructor since that assumes the //locale is ASCII QString q=QString::fromLocal8Bit(line.c_str()); p.write(raw_edict_message::create(q,"default")); } } void run(plugin_pipe p, string name) { thread t(send_input, p); p.write(registration_message::create(-32000, name, "display")); while (true) { message m=p.blocking_read(); if (m.type=="shutdown") { t.join(); return; } else if (m.type=="registration_status") { //Handle this } else if (m.type=="display") { auto s=dynamic_cast<display_message *>(m.getdata()); if (!s) continue; p.write(m.decrement_priority()); cout << s->channel.toLocal8Bit().constData() << ": <" << s->nick.toLocal8Bit().constData() << "> " << s->contents.toLocal8Bit().constData() << endl; } else { p.write(m.decrement_priority()); } } } <commit_msg>Handle /me messages in the basic UI<commit_after>#include <iostream> #include <thread> #include "plugins/lirch_plugin.h" #include "plugins/edict_messages.h" using namespace std; void send_input(plugin_pipe p) { string line; while (getline(cin, line)) { //I can't use the regular constructor since that assumes the //locale is ASCII QString q=QString::fromLocal8Bit(line.c_str()); p.write(raw_edict_message::create(q,"default")); } } void run(plugin_pipe p, string name) { thread t(send_input, p); p.write(registration_message::create(-32000, name, "display")); p.write(registration_message::create(-32000, name, "me_display")); while (true) { message m=p.blocking_read(); if (m.type=="shutdown") { t.join(); return; } else if (m.type=="registration_status") { //Handle this } else if (m.type=="display") { auto s=dynamic_cast<display_message *>(m.getdata()); if (!s) continue; p.write(m.decrement_priority()); cout << s->channel.toLocal8Bit().constData() << ": <" << s->nick.toLocal8Bit().constData() << "> " << s->contents.toLocal8Bit().constData() << endl; } else if (m.type=="me_display") { auto s=dynamic_cast<me_display_message *>(m.getdata()); if (!s) continue; p.write(m.decrement_priority()); cout << s->channel.toLocal8Bit().constData() << ": " << s->nick.toLocal8Bit().constData() << " " << s->contents.toLocal8Bit().constData() << endl; } else { p.write(m.decrement_priority()); } } } <|endoftext|>
<commit_before>// OpenLieroX // Main entry point // Created 28/6/02 // Jason Boettcher #include "defs.h" #include "LieroX.h" #include "Menu.h" #include "console.h" #ifdef WIN32 #include "crashrpt.h" #pragma comment(lib, "./libs/crashrpt") #endif CClient *cClient = NULL; CServer *cServer = NULL; lierox_t *tLX = NULL; game_t tGameInfo; CInput cTakeScreenshot; CInput cSwitchMode; int nDisableSound = false; keyboard_t *kb; SDL_Surface *Screen; CVec vGravity = CVec(0,4); /////////////////// // Main entry point int main(int argc, char *argv[]) { int startgame = false; float fMaxFPS = 85; // Install the CrashRpt library #ifdef WIN32 Install(NULL,"[email protected]","LXP Crash Report"); #endif // Reset the current working directory (remove the filename first!!!) // Note: Windows give the exe path and name in the first parameter char *slashpos = strrchr(argv[0],'\\'); *slashpos = 0; chdir(argv[0]); // Load options and other settings if(!LoadOptions()) return -1; if (!LoadNetworkStrings()) return -1; // Parse the arguments ParseArguments(argc, argv); // Initialize LX if(!InitializeLieroX()) return -1; kb = GetKeyboard(); Screen = SDL_GetVideoSurface(); // Initialize menu if(!Menu_Initialize(&startgame)) { SystemError("Error: Could not initialize the menu system.\nError when loading graphics files"); ShutdownLieroX(); return -1; } // Log the game start if (tLXOptions->iLogConvos) { FILE *f; f = fopen("Conversations.log","a"); if (f) { char cTime[26]; GetTime(cTime); fputs("<game starttime=\"",f); fputs(cTime,f); fputs("\">\r\n",f); fclose(f); } } // Setup the global keys cTakeScreenshot.Setup(tLXOptions->sGeneralControls[SIN_SCREENSHOTS]); cSwitchMode.Setup(tLXOptions->sGeneralControls[SIN_SWITCHMODE]); while(!tLX->iQuitGame) { startgame = false; // Start the menu Menu_Start(); if(startgame) { // Start the game StartGame(); } else { // Quit ShutdownLieroX(); return 0; } // Pre-game initialization Screen = SDL_GetVideoSurface(); float oldtime = GetMilliSeconds(); float captime = GetMilliSeconds(); ClearEntities(); ProcessEvents(); tLX->iQuitEngine = false; fMaxFPS = 1.0f / (float)tLXOptions->nMaxFPS; // // Main game loop // while(!tLX->iQuitEngine) { tLX->fCurTime = GetMilliSeconds(); // Cap the FPS if(tLX->fCurTime - captime < fMaxFPS) continue; else captime = tLX->fCurTime; ProcessEvents(); // Timing tLX->fDeltaTime = tLX->fCurTime - oldtime; oldtime = tLX->fCurTime; // Main frame GameLoop(); FlipScreen(Screen); } } ShutdownLieroX(); return 0; } /////////////////// // Parse the arguments void ParseArguments(int argc, char *argv[]) { // Parameters passed to liero xtreme overwrite the loaded options char *a; for(int i=1; i<argc; i++) { a = argv[i]; // -nosound // Turns off the sound if( stricmp(a, "-nosound") == 0 ) { nDisableSound = true; tLXOptions->iSoundOn = false; } // -window // Turns fullscreen off if( stricmp(a, "-window") == 0 ) { tLXOptions->iFullscreen = false; } // -fullscreen // Turns fullscreen on if( stricmp(a, "-fullscreen") == 0 ) { tLXOptions->iFullscreen = true; } } } /////////////////// // Initialize the game int InitializeLieroX(void) { // Initialize the aux library if(!InitializeAuxLib("Liero Xtreme","config.cfg",16,0)) return false; // Initialize the network if(!nlInit()) { SystemError("Error: Failed to initialize the network library"); return false; } if(!nlSelectNetwork(NL_IP)) { SystemError("Error: Failed to initialize the network library\nCould not select IP"); return false; } // Allocate the client & server cClient = new CClient; if(cClient == NULL) { SystemError("Error: InitializeLieroX() Out of memory"); return false; } cClient->Clear(); cServer = new CServer; if(cServer == NULL) { SystemError("Error: InitializeLieroX() Out of memory"); return false; } // Initialize the entities if(!InitializeEntities()) { SystemError("Error: InitializeEntities() Out of memory"); return false; } // Initialize the LieroX structure tLX = new lierox_t; if(tLX == NULL) { SystemError("Error: InitializeLieroX() Out of memory"); return false; } tLX->iQuitGame = false; tLX->debug_string[0] = 0; // Load the graphics if(!LoadGraphics()) { SystemError("Error: Error loading graphics"); return false; } // Initialize the console if(!Con_Initialize()) { SystemError("Error: Could not initialize the console"); return false; } // Add some console commands Cmd_AddCommand("kick", Cmd_Kick); Cmd_AddCommand("ban", Cmd_Ban); Cmd_AddCommand("mute", Cmd_Mute); Cmd_AddCommand("unmute", Cmd_Unmute); Cmd_AddCommand("kickid", Cmd_KickId); Cmd_AddCommand("banid", Cmd_BanId); Cmd_AddCommand("muteid", Cmd_MuteId); Cmd_AddCommand("unmuteid", Cmd_UnmuteId); Cmd_AddCommand("crash", Cmd_Crash); Cmd_AddCommand("suicide", Cmd_Suicide); Cmd_AddCommand("unstuck", Cmd_Unstuck); // Load the sounds LoadSounds(); // Load the profiles LoadProfiles(); // Initialize the game info structure tGameInfo.iNumPlayers = 0; tGameInfo.sMapRandom.psObjects = NULL; return true; } /////////////////// // Start the game void StartGame(void) { // Clear the screen DrawRectFill(SDL_GetVideoSurface(), 0,0, 640,480, 0); // Local game if(tGameInfo.iGameType == GME_LOCAL) { // Start the server if(!cServer->StartServer( "local", tLXOptions->iNetworkPort, 8, false )) { // ERROR MessageBox(NULL, "Error: Could not start server", "Liero Xtreme Error", MB_OK); return; } // Setup the client if(!cClient->Initialize()) { // ERROR MessageBox(NULL, "Error: Could not initialize client", "Liero Xtreme Error", MB_OK); return; } // Tell the client to connect to the server cClient->Connect("127.0.0.1"); } } /////////////////// // Game loop void GameLoop(void) { if(tLX->iQuitEngine) return; // Local switch (tGameInfo.iGameType) { //if(tGameInfo.iGameType == GME_LOCAL) { case GME_LOCAL: cClient->Frame(); cServer->Frame(); // If we are connected, just start the game straight away (bypass lobby in local) if(cClient->getStatus() == NET_CONNECTED) { if(cServer->getState() == SVS_LOBBY) cServer->StartGame(); } cClient->Draw(Screen); break; // Hosting //if(tGameInfo.iGameType == GME_HOST) { case GME_HOST: cClient->Frame(); cServer->Frame(); cClient->Draw(Screen); break; // Joined //if(tGameInfo.iGameType == GME_JOIN) { case GME_JOIN: cClient->Frame(); cClient->Draw(Screen); break; } // SWITCH // Switch between window and fullscreen mode if( cSwitchMode.isDown() ) { // Set to fullscreen tLXOptions->iFullscreen = !tLXOptions->iFullscreen; // Set the new video mode SetVideoMode(); // Update both menu and game screens Screen = SDL_GetVideoSurface(); tMenu->bmpScreen = SDL_GetVideoSurface(); } // We put it here, so the mouse never displays SDL_ShowCursor(SDL_DISABLE); } /////////////////// // Quit back to the menu void QuittoMenu(void) { tLX->iQuitEngine = true; Menu_SetSkipStart(false); cClient->Disconnect(); } /////////////////// // Shutdown the game void ShutdownLieroX(void) { if (tLXOptions->iLogConvos) { FILE *f; f = fopen("Conversations.log","a"); if (f) { fputs("</game>\r\n",f); fclose(f); } } Con_Shutdown(); ShutdownGraphics(); Menu_Shutdown(); ShutdownProfiles(); // Free the game info structure if(tGameInfo.sMapRandom.psObjects) delete[] tGameInfo.sMapRandom.psObjects; tGameInfo.sMapRandom.psObjects = NULL; // Free the client & server if(cClient) { cClient->Shutdown(); delete cClient; cClient = NULL; } if(cServer) { cServer->Shutdown(); delete cServer; cServer = NULL; } ShutdownOptions(); ShutdownEntities(); if(tLX) { delete tLX; tLX = NULL; } nlShutdown(); ShutdownAuxLib(); }<commit_msg>some corrections<commit_after>// OpenLieroX // Main entry point // Created 28/6/02 // Jason Boettcher #include "defs.h" #include "LieroX.h" #include "Menu.h" #include "console.h" #ifdef WIN32 #include "crashrpt.h" #pragma comment(lib, "./libs/crashrpt") #endif CClient *cClient = NULL; CServer *cServer = NULL; lierox_t *tLX = NULL; game_t tGameInfo; CInput cTakeScreenshot; CInput cSwitchMode; int nDisableSound = false; keyboard_t *kb; SDL_Surface *Screen; CVec vGravity = CVec(0,4); /////////////////// // Main entry point int main(int argc, char *argv[]) { int startgame = false; float fMaxFPS = 85; // Install the CrashRpt library #ifdef WIN32 Install(NULL,"[email protected]","LXP Crash Report"); #endif // this behavior only make sense for a win-system // under unix, the bin and the data are seperate #ifdef WIN32 // Reset the current working directory (remove the filename first!!!) // Note: Windows give the exe path and name in the first parameter char *slashpos = strrchr(argv[0],'\\'); *slashpos = 0; chdir(argv[0]); #else // TODO: set and handles the following search pathes: // ~/.OpenLieroX , /usr/share/OpenLieroX #endif // Load options and other settings if(!LoadOptions()) return -1; if (!LoadNetworkStrings()) return -1; // Parse the arguments ParseArguments(argc, argv); // Initialize LX if(!InitializeLieroX()) return -1; kb = GetKeyboard(); Screen = SDL_GetVideoSurface(); // Initialize menu if(!Menu_Initialize(&startgame)) { SystemError("Error: Could not initialize the menu system.\nError when loading graphics files"); ShutdownLieroX(); return -1; } // Log the game start if (tLXOptions->iLogConvos) { FILE *f; f = fopen("Conversations.log","a"); if (f) { char cTime[26]; GetTime(cTime); fputs("<game starttime=\"",f); fputs(cTime,f); fputs("\">\r\n",f); fclose(f); } } // Setup the global keys cTakeScreenshot.Setup(tLXOptions->sGeneralControls[SIN_SCREENSHOTS]); cSwitchMode.Setup(tLXOptions->sGeneralControls[SIN_SWITCHMODE]); while(!tLX->iQuitGame) { startgame = false; // Start the menu Menu_Start(); if(startgame) { // Start the game StartGame(); } else { // Quit ShutdownLieroX(); return 0; } // Pre-game initialization Screen = SDL_GetVideoSurface(); float oldtime = GetMilliSeconds(); float captime = GetMilliSeconds(); ClearEntities(); ProcessEvents(); tLX->iQuitEngine = false; fMaxFPS = 1.0f / (float)tLXOptions->nMaxFPS; // // Main game loop // while(!tLX->iQuitEngine) { tLX->fCurTime = GetMilliSeconds(); // Cap the FPS if(tLX->fCurTime - captime < fMaxFPS) continue; else captime = tLX->fCurTime; ProcessEvents(); // Timing tLX->fDeltaTime = tLX->fCurTime - oldtime; oldtime = tLX->fCurTime; // Main frame GameLoop(); FlipScreen(Screen); } } ShutdownLieroX(); return 0; } /////////////////// // Parse the arguments void ParseArguments(int argc, char *argv[]) { // Parameters passed to liero xtreme overwrite the loaded options char *a; for(int i=1; i<argc; i++) { a = argv[i]; // -nosound // Turns off the sound if( stricmp(a, "-nosound") == 0 ) { nDisableSound = true; tLXOptions->iSoundOn = false; } // -window // Turns fullscreen off if( stricmp(a, "-window") == 0 ) { tLXOptions->iFullscreen = false; } // -fullscreen // Turns fullscreen on if( stricmp(a, "-fullscreen") == 0 ) { tLXOptions->iFullscreen = true; } } } /////////////////// // Initialize the game int InitializeLieroX(void) { // Initialize the aux library if(!InitializeAuxLib("Liero Xtreme","config.cfg",16,0)) return false; // Initialize the network if(!nlInit()) { SystemError("Error: Failed to initialize the network library"); return false; } if(!nlSelectNetwork(NL_IP)) { SystemError("Error: Failed to initialize the network library\nCould not select IP"); return false; } // Allocate the client & server cClient = new CClient; if(cClient == NULL) { SystemError("Error: InitializeLieroX() Out of memory"); return false; } cClient->Clear(); cServer = new CServer; if(cServer == NULL) { SystemError("Error: InitializeLieroX() Out of memory"); return false; } // Initialize the entities if(!InitializeEntities()) { SystemError("Error: InitializeEntities() Out of memory"); return false; } // Initialize the LieroX structure tLX = new lierox_t; if(tLX == NULL) { SystemError("Error: InitializeLieroX() Out of memory"); return false; } tLX->iQuitGame = false; tLX->debug_string[0] = 0; // Load the graphics if(!LoadGraphics()) { SystemError("Error: Error loading graphics"); return false; } // Initialize the console if(!Con_Initialize()) { SystemError("Error: Could not initialize the console"); return false; } // Add some console commands Cmd_AddCommand("kick", Cmd_Kick); Cmd_AddCommand("ban", Cmd_Ban); Cmd_AddCommand("mute", Cmd_Mute); Cmd_AddCommand("unmute", Cmd_Unmute); Cmd_AddCommand("kickid", Cmd_KickId); Cmd_AddCommand("banid", Cmd_BanId); Cmd_AddCommand("muteid", Cmd_MuteId); Cmd_AddCommand("unmuteid", Cmd_UnmuteId); Cmd_AddCommand("crash", Cmd_Crash); Cmd_AddCommand("suicide", Cmd_Suicide); Cmd_AddCommand("unstuck", Cmd_Unstuck); // Load the sounds LoadSounds(); // Load the profiles LoadProfiles(); // Initialize the game info structure tGameInfo.iNumPlayers = 0; tGameInfo.sMapRandom.psObjects = NULL; return true; } /////////////////// // Start the game void StartGame(void) { // Clear the screen DrawRectFill(SDL_GetVideoSurface(), 0,0, 640,480, 0); // Local game if(tGameInfo.iGameType == GME_LOCAL) { // TODO: uniform message system // Start the server if(!cServer->StartServer( "local", tLXOptions->iNetworkPort, 8, false )) { // ERROR //MessageBox(NULL, "Error: Could not start server", "Liero Xtreme Error", MB_OK); printf("Error: Could not start server\n"); return; } // Setup the client if(!cClient->Initialize()) { // ERROR //MessageBox(NULL, "Error: Could not initialize client", "Liero Xtreme Error", MB_OK); printf("Error: Could not initialize client\n"); return; } // Tell the client to connect to the server cClient->Connect("127.0.0.1"); } } /////////////////// // Game loop void GameLoop(void) { if(tLX->iQuitEngine) return; // Local switch (tGameInfo.iGameType) { //if(tGameInfo.iGameType == GME_LOCAL) { case GME_LOCAL: cClient->Frame(); cServer->Frame(); // If we are connected, just start the game straight away (bypass lobby in local) if(cClient->getStatus() == NET_CONNECTED) { if(cServer->getState() == SVS_LOBBY) cServer->StartGame(); } cClient->Draw(Screen); break; // Hosting //if(tGameInfo.iGameType == GME_HOST) { case GME_HOST: cClient->Frame(); cServer->Frame(); cClient->Draw(Screen); break; // Joined //if(tGameInfo.iGameType == GME_JOIN) { case GME_JOIN: cClient->Frame(); cClient->Draw(Screen); break; } // SWITCH // Switch between window and fullscreen mode if( cSwitchMode.isDown() ) { // Set to fullscreen tLXOptions->iFullscreen = !tLXOptions->iFullscreen; // Set the new video mode SetVideoMode(); // Update both menu and game screens Screen = SDL_GetVideoSurface(); tMenu->bmpScreen = SDL_GetVideoSurface(); } // We put it here, so the mouse never displays SDL_ShowCursor(SDL_DISABLE); } /////////////////// // Quit back to the menu void QuittoMenu(void) { tLX->iQuitEngine = true; Menu_SetSkipStart(false); cClient->Disconnect(); } /////////////////// // Shutdown the game void ShutdownLieroX(void) { if (tLXOptions->iLogConvos) { FILE *f; f = fopen("Conversations.log","a"); if (f) { fputs("</game>\r\n",f); fclose(f); } } Con_Shutdown(); ShutdownGraphics(); Menu_Shutdown(); ShutdownProfiles(); // Free the game info structure if(tGameInfo.sMapRandom.psObjects) delete[] tGameInfo.sMapRandom.psObjects; tGameInfo.sMapRandom.psObjects = NULL; // Free the client & server if(cClient) { cClient->Shutdown(); delete cClient; cClient = NULL; } if(cServer) { cServer->Shutdown(); delete cServer; cServer = NULL; } ShutdownOptions(); ShutdownEntities(); if(tLX) { delete tLX; tLX = NULL; } nlShutdown(); ShutdownAuxLib(); } <|endoftext|>
<commit_before>#include "common.h" #include "Simulation.h" #include "FullscreenQuad.h" /** \file main.cpp * Main source file. * The source file that contains the main entry point and performs initialization and cleanup. */ /** GLFW window. * The GLFW window. */ GLFWwindow *window = NULL; /** Simulation class. * The global Simulation object. */ Simulation *simulation = NULL; /** GLFW error callback. * Outputs error messages from GLFW. * \param error error id * \param msg error message */ void glfwErrorCallback (int error, const char *msg) { std::cerr << "GLFW error: " << msg << std::endl; } /** OpenGL debug callback. * Outputs a debug message from OpenGL. * \param source source of the debug message * \param type type of the debug message * \param id debug message id * \param severity severity of the debug message * \param length length of the debug message * \param message debug message * \param userParam user pointer * */ void glDebugCallback (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { std::cerr << "OpenGL debug message: " << std::string (message, length) << std::endl; } /** Cursor position. * Stores the last known cursor position. Used to calculate relative cursor movement. */ glm::dvec2 cursor; /** Mouse movement callback. * GLFW callback for mouse movement events. Passes the event to the Simulation class. * \param window GLFW window that produced the event * \param x new x coordinate of the cursor * \param y new y coordinate of the cursor */ void OnMouseMove (GLFWwindow *window, double x, double y) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); simulation->OnMouseMove (x - cursor.x, y - cursor.y); cursor.x = x; cursor.y = y; } /** Mouse button callback. * GLFW callback for mouse button events. Passes the event to the Simulation class. * \param window GLFW window that produced the event * \param button the mouse button that was pressed or released * \param action one of GLFW_PRESS or GLFW_RELEASE * \param mode bit field describing which modifier keys were hold down */ void OnMouseButton (GLFWwindow *window, int button, int action, int mods) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); if (action == GLFW_PRESS) simulation->OnMouseDown (button); else if (action == GLFW_RELEASE) simulation->OnMouseUp (button); } /** Key event callback. * GLFW callback for key events. Passes the event to the Simulation class. * \param window GLFW window that produced the event * \param key the key that was pressed or released * \param scancode system-specific scancode of the key * \param action GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT * \param mods Bit-field describing the modifier keys that were held down when the event ocurred */ void OnKeyEvent (GLFWwindow *window, int key, int scancode, int action, int mods) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); if (action == GLFW_RELEASE) simulation->OnKeyUp (key); else if (action == GLFW_PRESS) simulation->OnKeyDown (key); } /** Window resize callback. * GLFW callback for window resize events. Passes the event to the Simulation class. * \param window GLFW window that was resized * \param width new window width * \param height new window height */ void OnResize (GLFWwindow *window, int width, int height) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); simulation->Resize (width, height); } /** Broken ATI glMemoryBarrier entry point. * This stores the non functional glMemoryBarrier entry point provided by ATI drivers. */ PFNGLMEMORYBARRIERPROC _glMemoryBarrier_BROKEN_ATIHACK = 0; /** Workaround for broken glMemoryBarrier provided by ATI drivers. * This is used as a hack to work around the broken implementation * of glMemoryBarrier provided by ATI drivers. It calls the non functional * entry point provided by the driver preceded by a call of glFlush * which seems to have the correct effect (although this clearly violates * both the specification of glMemoryBarrier and of glFlush). * \param bitfield Specifies the barriers to insert. */ void _glMemoryBarrier_ATIHACK (GLbitfield bitfield) { glFlush (); _glMemoryBarrier_BROKEN_ATIHACK (bitfield); } /** Inialization. * Perform general initialization tasks. */ void initialize (void) { // set GLFW error callback glfwSetErrorCallback (glfwErrorCallback); // specify parameters for the opengl context glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint (GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); // open a window and an OpenGL context window = glfwCreateWindow (1280, 720, "PBF", NULL, NULL); if (window == NULL) throw std::runtime_error ("Cannot open window."); glfwMakeContextCurrent (window); // get OpenGL entry points glcorewInit ((glcorewGetProcAddressCallback) glfwGetProcAddress); std::string vendor (reinterpret_cast<const char*> (glGetString (GL_VENDOR))); if (!vendor.compare ("ATI Technologies Inc.")) { std::cout << "Enable ATI workarounds." << std::endl; _glMemoryBarrier_BROKEN_ATIHACK = glMemoryBarrier; glMemoryBarrier = _glMemoryBarrier_ATIHACK; } glDebugMessageCallback (glDebugCallback, NULL); glEnable (GL_DEBUG_OUTPUT); // create the simulation class simulation = new Simulation (); // setup event callbacks glfwSetWindowUserPointer (window, simulation); glfwGetCursorPos (window, &cursor.x, &cursor.y); glfwSetCursorPosCallback (window, OnMouseMove); glfwSetMouseButtonCallback (window, OnMouseButton); glfwSetKeyCallback (window, OnKeyEvent); glfwSetFramebufferSizeCallback (window, OnResize); // notify the Simulation class of the initial window dimensions int width, height; glfwGetFramebufferSize (window, &width, &height); simulation->Resize (width, height); } /** Cleanup. */ void cleanup (void) { // release simulation class if (simulation != NULL) delete simulation; // release signleton classes FullscreenQuad::Release (); // destroy window and shutdown glfw if (window != NULL) glfwDestroyWindow (window); glfwTerminate (); } bool IsExtensionSupported (const std::string &name) { GLint n = 0; glGetIntegerv (GL_NUM_EXTENSIONS, &n); for (int i = 0; i < n; i++) { const char *ext = reinterpret_cast<const char*> (glGetStringi (GL_EXTENSIONS, i)); if (ext != NULL && !name.compare (ext)) return true; } return false; } /** Main. * Main entry point. * \param argc number of arguments * \param argv argument array * \returns error code */ int main (int argc, char *argv[]) { // initialize GLFW if (!glfwInit ()) { std::cerr << "Cannot initialize GLFW." << std::endl; return -1; } try { // initialization initialize (); // simulation loop while (!glfwWindowShouldClose (window)) { if (!simulation->Frame ()) break; glfwSwapBuffers (window); glfwPollEvents (); } // cleanup cleanup (); return 0; } catch (std::exception &e) { cleanup (); std::cerr << "Exception: " << e.what () << std::endl; return -1; } } <commit_msg>More elaborate workaround for AMD/ATI glMemoryBarrier.<commit_after>#include "common.h" #include "Simulation.h" #include "FullscreenQuad.h" /** \file main.cpp * Main source file. * The source file that contains the main entry point and performs initialization and cleanup. */ /** GLFW window. * The GLFW window. */ GLFWwindow *window = NULL; /** Simulation class. * The global Simulation object. */ Simulation *simulation = NULL; /** GLFW error callback. * Outputs error messages from GLFW. * \param error error id * \param msg error message */ void glfwErrorCallback (int error, const char *msg) { std::cerr << "GLFW error: " << msg << std::endl; } /** OpenGL debug callback. * Outputs a debug message from OpenGL. * \param source source of the debug message * \param type type of the debug message * \param id debug message id * \param severity severity of the debug message * \param length length of the debug message * \param message debug message * \param userParam user pointer * */ void glDebugCallback (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { std::cerr << "OpenGL debug message: " << std::string (message, length) << std::endl; } /** Cursor position. * Stores the last known cursor position. Used to calculate relative cursor movement. */ glm::dvec2 cursor; /** Mouse movement callback. * GLFW callback for mouse movement events. Passes the event to the Simulation class. * \param window GLFW window that produced the event * \param x new x coordinate of the cursor * \param y new y coordinate of the cursor */ void OnMouseMove (GLFWwindow *window, double x, double y) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); simulation->OnMouseMove (x - cursor.x, y - cursor.y); cursor.x = x; cursor.y = y; } /** Mouse button callback. * GLFW callback for mouse button events. Passes the event to the Simulation class. * \param window GLFW window that produced the event * \param button the mouse button that was pressed or released * \param action one of GLFW_PRESS or GLFW_RELEASE * \param mode bit field describing which modifier keys were hold down */ void OnMouseButton (GLFWwindow *window, int button, int action, int mods) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); if (action == GLFW_PRESS) simulation->OnMouseDown (button); else if (action == GLFW_RELEASE) simulation->OnMouseUp (button); } /** Key event callback. * GLFW callback for key events. Passes the event to the Simulation class. * \param window GLFW window that produced the event * \param key the key that was pressed or released * \param scancode system-specific scancode of the key * \param action GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT * \param mods Bit-field describing the modifier keys that were held down when the event ocurred */ void OnKeyEvent (GLFWwindow *window, int key, int scancode, int action, int mods) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); if (action == GLFW_RELEASE) simulation->OnKeyUp (key); else if (action == GLFW_PRESS) simulation->OnKeyDown (key); } /** Window resize callback. * GLFW callback for window resize events. Passes the event to the Simulation class. * \param window GLFW window that was resized * \param width new window width * \param height new window height */ void OnResize (GLFWwindow *window, int width, int height) { Simulation *simulation = reinterpret_cast<Simulation*> (glfwGetWindowUserPointer (window)); simulation->Resize (width, height); } /** Broken ATI glMemoryBarrier entry point. * This stores the non functional glMemoryBarrier entry point provided by ATI drivers. */ PFNGLMEMORYBARRIERPROC _glMemoryBarrier_BROKEN_ATIHACK = 0; /** Workaround for broken glMemoryBarrier provided by ATI drivers. * This is used as a hack to work around the broken implementation * of glMemoryBarrier provided by ATI drivers. It synchronizes * the GPU command queue using a sync object before calling the * apparently non functional entry point provided by the driver. * It is not clear whether this actually results in the desired * behavior, but it seems to produce much better results than * just calling glMemoryBarrier (which seems to have no effect * at all). * \param bitfield Specifies the barriers to insert. */ void _glMemoryBarrier_ATIHACK (GLbitfield bitfield) { GLsync syncobj = glFenceSync (GL_SYNC_GPU_COMMANDS_COMPLETE, 0); glWaitSync (syncobj, 0, GL_TIMEOUT_IGNORED); glDeleteSync (syncobj); _glMemoryBarrier_BROKEN_ATIHACK (bitfield); } /** Inialization. * Perform general initialization tasks. */ void initialize (void) { // set GLFW error callback glfwSetErrorCallback (glfwErrorCallback); // specify parameters for the opengl context glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint (GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); // open a window and an OpenGL context window = glfwCreateWindow (1280, 720, "PBF", NULL, NULL); if (window == NULL) throw std::runtime_error ("Cannot open window."); glfwMakeContextCurrent (window); // get OpenGL entry points glcorewInit ((glcorewGetProcAddressCallback) glfwGetProcAddress); std::string vendor (reinterpret_cast<const char*> (glGetString (GL_VENDOR))); if (!vendor.compare ("ATI Technologies Inc.")) { std::cout << "Enable ATI workarounds." << std::endl; _glMemoryBarrier_BROKEN_ATIHACK = glMemoryBarrier; glMemoryBarrier = _glMemoryBarrier_ATIHACK; } glDebugMessageCallback (glDebugCallback, NULL); glEnable (GL_DEBUG_OUTPUT); // create the simulation class simulation = new Simulation (); // setup event callbacks glfwSetWindowUserPointer (window, simulation); glfwGetCursorPos (window, &cursor.x, &cursor.y); glfwSetCursorPosCallback (window, OnMouseMove); glfwSetMouseButtonCallback (window, OnMouseButton); glfwSetKeyCallback (window, OnKeyEvent); glfwSetFramebufferSizeCallback (window, OnResize); // notify the Simulation class of the initial window dimensions int width, height; glfwGetFramebufferSize (window, &width, &height); simulation->Resize (width, height); } /** Cleanup. */ void cleanup (void) { // release simulation class if (simulation != NULL) delete simulation; // release signleton classes FullscreenQuad::Release (); // destroy window and shutdown glfw if (window != NULL) glfwDestroyWindow (window); glfwTerminate (); } bool IsExtensionSupported (const std::string &name) { GLint n = 0; glGetIntegerv (GL_NUM_EXTENSIONS, &n); for (int i = 0; i < n; i++) { const char *ext = reinterpret_cast<const char*> (glGetStringi (GL_EXTENSIONS, i)); if (ext != NULL && !name.compare (ext)) return true; } return false; } /** Main. * Main entry point. * \param argc number of arguments * \param argv argument array * \returns error code */ int main (int argc, char *argv[]) { // initialize GLFW if (!glfwInit ()) { std::cerr << "Cannot initialize GLFW." << std::endl; return -1; } try { // initialization initialize (); // simulation loop while (!glfwWindowShouldClose (window)) { if (!simulation->Frame ()) break; glfwSwapBuffers (window); glfwPollEvents (); } // cleanup cleanup (); return 0; } catch (std::exception &e) { cleanup (); std::cerr << "Exception: " << e.what () << std::endl; return -1; } } <|endoftext|>
<commit_before>#include "object.h" #include "engine.h" #include "napi.h" #ifdef NAPI_DEBUG #include <iostream> #endif Napi::Object CreateObject(const Napi::CallbackInfo &info) { const Napi::Env env = info.Env(); const Napi::Object config = info[0].As<Napi::Object>(); #ifdef NAPI_DEBUG // show system size values for types being used std::cout << "size of bool : " << sizeof(bool) << std::endl; std::cout << "size of std::string : " << sizeof(std::string) << std::endl; std::cout << "size of int_fast32_t : " << sizeof(int_fast32_t) << std::endl; std::cout << "size of uint_fast32_t : " << sizeof(uint_fast32_t) << std::endl; std::cout << "size of std::vector<bool> : " << sizeof(std::vector<bool>) << std::endl; std::cout << "size of std::vector<uint_fast8_t> : " << sizeof(std::vector<uint_fast8_t>) << std::endl; std::cout << "size of Region struct : " << sizeof(Region) << std::endl; std::cout << "size of PercentResult struct : " << sizeof(PercentResult) << std::endl; std::cout << "size of BoundsResult struct : " << sizeof(BoundsResult) << std::endl; if (config.Has("depth")) std::cout << "depth : " << config.Get("depth").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("width")) std::cout << "width : " << config.Get("width").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("height")) std::cout << "height : " << config.Get("height").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("response")) std::cout << "response : " << config.Get("response").As<Napi::String>().Utf8Value() << std::endl; if (config.Has("draw")) std::cout << "draw : " << config.Get("draw").As<Napi::Boolean>().Value() << std::endl; if (config.Has("async")) std::cout << "async : " << config.Get("async").As<Napi::Boolean>().Value() << std::endl; if (config.Has("target")) std::cout << "target : " << config.Get("target").As<Napi::String>().Utf8Value() << std::endl; if (config.Has("difference")) std::cout << "difference : " << config.Get("difference").As<Napi::Number>().Int32Value() << std::endl; if (config.Has("percent")) std::cout << "percent : " << config.Get("percent").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("bitsetCount")) std::cout << "bitsetCount : " << config.Get("bitsetCount").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("bitset")) std::cout << "bitset length : " << config.Get("bitset").As<Napi::Buffer<bool>>().Length() << std::endl; if (config.Has("minDiff")) std::cout << "minDiff : " << config.Get("minDiff").As<Napi::Number>().Int32Value() << std::endl; if (config.Has("minX")) std::cout << "minX : " << config.Get("minX").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("maxX")) std::cout << "maxX : " << config.Get("maxX").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("minY")) std::cout << "minY : " << config.Get("minY").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("maxY")) std::cout << "maxY : " << config.Get("maxY").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("regions")) { const Napi::Array regionsJs = config.Get("regions").As<Napi::Array>(); std::cout << "regions length : " << regionsJs.Length() << std::endl; for (uint_fast32_t r = 0; r < regionsJs.Length(); r++) { const std::string name = regionsJs.Get(r).As<Napi::Object>().Get("name").As<Napi::String>(); const uint_fast32_t diff = regionsJs.Get(r).As<Napi::Object>().Get("diff").As<Napi::Number>().Int32Value(); const uint_fast32_t percent = regionsJs.Get(r).As<Napi::Object>().Get("percent").As<Napi::Number>().Uint32Value(); const uint_fast32_t count = regionsJs.Get(r).As<Napi::Object>().Get("count").As<Napi::Number>().Uint32Value(); std::cout << name << " - " << diff << " - " << percent << " - " << count << " - " << regionsJs.Get(r).As<Napi::Object>().Get("bitset").As<Napi::Buffer<bool>>().Length() << std::endl; } } #endif const uint_fast32_t pixDepth = config.Get("depth").As<Napi::Number>().Uint32Value(); const std::string target = config.Get("target").As<Napi::String>().Utf8Value(); const std::string response = config.Get("response").As<Napi::String>().Utf8Value(); const bool async = config.Get("async").As<Napi::Boolean>().Value(); const uint_fast32_t engineType = EngineType(pixDepth, target, response, async); switch (engineType) { case GRAY_ALL_PERCENT_SYNC : return GrayAllPercentSync::NewInstance(env, config); case GRAY_ALL_PERCENT_ASYNC : return GrayAllPercentAsync::NewInstance(env, config); case GRAY_MASK_PERCENT_SYNC : return GrayMaskPercentSync::NewInstance(env, config); case GRAY_MASK_PERCENT_ASYNC : return GrayMaskPercentAsync::NewInstance(env, config); case GRAY_REGIONS_PERCENT_SYNC : return GrayRegionsPercentSync::NewInstance(env, config); case GRAY_REGIONS_PERCENT_ASYNC : return GrayRegionsPercentAsync::NewInstance(env, config); case GRAY_ALL_BOUNDS_SYNC : return GrayAllBoundsSync::NewInstance(env, config); case GRAY_ALL_BOUNDS_ASYNC : return GrayAllBoundsAsync::NewInstance(env, config); case GRAY_MASK_BOUNDS_SYNC : return GrayMaskBoundsSync::NewInstance(env, config); case GRAY_MASK_BOUNDS_ASYNC : return GrayMaskBoundsAsync::NewInstance(env, config); case GRAY_REGIONS_BOUNDS_SYNC : return GrayRegionsBoundsSync::NewInstance(env, config); case GRAY_REGIONS_BOUNDS_ASYNC : return GrayRegionsBoundsAsync::NewInstance(env, config); case RGB_ALL_PERCENT_SYNC : return RgbAllPercentSync::NewInstance(env, config); case RGB_ALL_PERCENT_ASYNC : return RgbAllPercentAsync::NewInstance(env, config); case RGB_MASK_PERCENT_SYNC : return RgbMaskPercentSync::NewInstance(env, config); case RGB_MASK_PERCENT_ASYNC : return RgbMaskPercentAsync::NewInstance(env, config); case RGB_REGIONS_PERCENT_SYNC : return RgbRegionsPercentSync::NewInstance(env, config); case RGB_REGIONS_PERCENT_ASYNC : return RgbRegionsPercentAsync::NewInstance(env, config); case RGB_ALL_BOUNDS_SYNC : return RgbAllBoundsSync::NewInstance(env, config); case RGB_ALL_BOUNDS_ASYNC : return RgbAllBoundsAsync::NewInstance(env, config); case RGB_MASK_BOUNDS_SYNC : return RgbMaskBoundsSync::NewInstance(env, config); case RGB_MASK_BOUNDS_ASYNC : return RgbMaskBoundsAsync::NewInstance(env, config); case RGB_REGIONS_BOUNDS_SYNC : return RgbRegionsBoundsSync::NewInstance(env, config); case RGB_REGIONS_BOUNDS_ASYNC : return RgbRegionsBoundsAsync::NewInstance(env, config); case GRAY_ALL_BLOBS_SYNC : return GrayAllBlobsSync::NewInstance(env, config); case GRAY_ALL_BLOBS_ASYNC : return GrayAllBlobsAsync::NewInstance(env, config); case GRAY_MASK_BLOBS_SYNC : return GrayMaskBlobsSync::NewInstance(env, config); case GRAY_MASK_BLOBS_ASYNC : return GrayMaskBlobsAsync::NewInstance(env, config); case GRAY_REGIONS_BLOBS_SYNC : return GrayRegionsBlobsSync::NewInstance(env, config); default: throw Napi::Error::New(env, "Engine not found for type " + std::to_string(engineType)); } } Napi::Object Init(Napi::Env env, Napi::Object exports) { exports = Napi::Function::New(env, CreateObject, "CreateObject"); GrayAllPercentSync::Init(env); GrayAllPercentAsync::Init(env); GrayMaskPercentSync::Init(env); GrayMaskPercentAsync::Init(env); GrayRegionsPercentSync::Init(env); GrayRegionsPercentAsync::Init(env); GrayAllBoundsSync::Init(env); GrayAllBoundsAsync::Init(env); GrayMaskBoundsSync::Init(env); GrayMaskBoundsAsync::Init(env); GrayRegionsBoundsSync::Init(env); GrayRegionsBoundsAsync::Init(env); RgbAllPercentSync::Init(env); RgbAllPercentAsync::Init(env); RgbMaskPercentSync::Init(env); RgbMaskPercentAsync::Init(env); RgbRegionsPercentSync::Init(env); RgbRegionsPercentAsync::Init(env); RgbAllBoundsSync::Init(env); RgbAllBoundsAsync::Init(env); RgbMaskBoundsSync::Init(env); RgbMaskBoundsAsync::Init(env); RgbRegionsBoundsSync::Init(env); RgbRegionsBoundsAsync::Init(env); GrayAllBlobsSync::Init(env); GrayAllBlobsAsync::Init(env); GrayMaskBlobsSync::Init(env); GrayMaskBlobsAsync::Init(env); GrayRegionsBlobsSync::Init(env); return exports; } NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)<commit_msg>add more debugging output<commit_after>#include "object.h" #include "engine.h" #include "napi.h" #ifdef NAPI_DEBUG #include <iostream> #endif Napi::Object CreateObject(const Napi::CallbackInfo &info) { const Napi::Env env = info.Env(); const Napi::Object config = info[0].As<Napi::Object>(); #ifdef NAPI_DEBUG // show system size values for types being used std::cout << "size of bool : " << sizeof(bool) << std::endl; std::cout << "size of std::string : " << sizeof(std::string) << std::endl; std::cout << "size of int_fast32_t : " << sizeof(int_fast32_t) << std::endl; std::cout << "size of uint_fast32_t : " << sizeof(uint_fast32_t) << std::endl; std::cout << "size of std::vector<bool> : " << sizeof(std::vector<bool>) << std::endl; std::cout << "size of std::vector<uint_fast8_t> : " << sizeof(std::vector<uint_fast8_t>) << std::endl; std::cout << "size of Region struct : " << sizeof(Region) << std::endl; std::cout << "size of PercentResult struct : " << sizeof(PercentResult) << std::endl; std::cout << "size of BoundsResult struct : " << sizeof(BoundsResult) << std::endl; if (config.Has("depth")) std::cout << "depth : " << config.Get("depth").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("width")) std::cout << "width : " << config.Get("width").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("height")) std::cout << "height : " << config.Get("height").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("response")) std::cout << "response : " << config.Get("response").As<Napi::String>().Utf8Value() << std::endl; if (config.Has("draw")) std::cout << "draw : " << config.Get("draw").As<Napi::Boolean>().Value() << std::endl; if (config.Has("async")) std::cout << "async : " << config.Get("async").As<Napi::Boolean>().Value() << std::endl; if (config.Has("target")) std::cout << "target : " << config.Get("target").As<Napi::String>().Utf8Value() << std::endl; if (config.Has("difference")) std::cout << "difference : " << config.Get("difference").As<Napi::Number>().Int32Value() << std::endl; if (config.Has("percent")) std::cout << "percent : " << config.Get("percent").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("bitsetCount")) std::cout << "bitsetCount : " << config.Get("bitsetCount").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("bitset")) std::cout << "bitset length : " << config.Get("bitset").As<Napi::Buffer<bool>>().Length() << std::endl; if (config.Has("minDiff")) std::cout << "minDiff : " << config.Get("minDiff").As<Napi::Number>().Int32Value() << std::endl; if (config.Has("minX")) std::cout << "minX : " << config.Get("minX").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("maxX")) std::cout << "maxX : " << config.Get("maxX").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("minY")) std::cout << "minY : " << config.Get("minY").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("maxY")) std::cout << "maxY : " << config.Get("maxY").As<Napi::Number>().Uint32Value() << std::endl; if (config.Has("regions")) { const Napi::Array regionsJs = config.Get("regions").As<Napi::Array>(); std::cout << "regions length : " << regionsJs.Length() << std::endl; for (uint_fast32_t r = 0; r < regionsJs.Length(); r++) { const std::string name = regionsJs.Get(r).As<Napi::Object>().Get("name").As<Napi::String>(); const uint_fast32_t diff = regionsJs.Get(r).As<Napi::Object>().Get("diff").As<Napi::Number>().Int32Value(); const uint_fast32_t percent = regionsJs.Get(r).As<Napi::Object>().Get("percent").As<Napi::Number>().Uint32Value(); const uint_fast32_t count = regionsJs.Get(r).As<Napi::Object>().Get("count").As<Napi::Number>().Uint32Value(); const uint_fast32_t minX = regionsJs.Get(r).As<Napi::Object>().Get("minX").As<Napi::Number>().Uint32Value(); const uint_fast32_t maxX = regionsJs.Get(r).As<Napi::Object>().Get("maxX").As<Napi::Number>().Uint32Value(); const uint_fast32_t minY = regionsJs.Get(r).As<Napi::Object>().Get("minY").As<Napi::Number>().Uint32Value(); const uint_fast32_t maxY = regionsJs.Get(r).As<Napi::Object>().Get("maxY").As<Napi::Number>().Uint32Value(); std::cout << name << " - " << diff << " - " << minX << " - " << maxX << " - " << minY << " - " << maxY << " - " << percent << " - " << count << " - " << regionsJs.Get(r).As<Napi::Object>().Get("bitset").As<Napi::Buffer<bool>>().Length() << std::endl; } } #endif const uint_fast32_t pixDepth = config.Get("depth").As<Napi::Number>().Uint32Value(); const std::string target = config.Get("target").As<Napi::String>().Utf8Value(); const std::string response = config.Get("response").As<Napi::String>().Utf8Value(); const bool async = config.Get("async").As<Napi::Boolean>().Value(); const uint_fast32_t engineType = EngineType(pixDepth, target, response, async); switch (engineType) { case GRAY_ALL_PERCENT_SYNC : return GrayAllPercentSync::NewInstance(env, config); case GRAY_ALL_PERCENT_ASYNC : return GrayAllPercentAsync::NewInstance(env, config); case GRAY_MASK_PERCENT_SYNC : return GrayMaskPercentSync::NewInstance(env, config); case GRAY_MASK_PERCENT_ASYNC : return GrayMaskPercentAsync::NewInstance(env, config); case GRAY_REGIONS_PERCENT_SYNC : return GrayRegionsPercentSync::NewInstance(env, config); case GRAY_REGIONS_PERCENT_ASYNC : return GrayRegionsPercentAsync::NewInstance(env, config); case GRAY_ALL_BOUNDS_SYNC : return GrayAllBoundsSync::NewInstance(env, config); case GRAY_ALL_BOUNDS_ASYNC : return GrayAllBoundsAsync::NewInstance(env, config); case GRAY_MASK_BOUNDS_SYNC : return GrayMaskBoundsSync::NewInstance(env, config); case GRAY_MASK_BOUNDS_ASYNC : return GrayMaskBoundsAsync::NewInstance(env, config); case GRAY_REGIONS_BOUNDS_SYNC : return GrayRegionsBoundsSync::NewInstance(env, config); case GRAY_REGIONS_BOUNDS_ASYNC : return GrayRegionsBoundsAsync::NewInstance(env, config); case RGB_ALL_PERCENT_SYNC : return RgbAllPercentSync::NewInstance(env, config); case RGB_ALL_PERCENT_ASYNC : return RgbAllPercentAsync::NewInstance(env, config); case RGB_MASK_PERCENT_SYNC : return RgbMaskPercentSync::NewInstance(env, config); case RGB_MASK_PERCENT_ASYNC : return RgbMaskPercentAsync::NewInstance(env, config); case RGB_REGIONS_PERCENT_SYNC : return RgbRegionsPercentSync::NewInstance(env, config); case RGB_REGIONS_PERCENT_ASYNC : return RgbRegionsPercentAsync::NewInstance(env, config); case RGB_ALL_BOUNDS_SYNC : return RgbAllBoundsSync::NewInstance(env, config); case RGB_ALL_BOUNDS_ASYNC : return RgbAllBoundsAsync::NewInstance(env, config); case RGB_MASK_BOUNDS_SYNC : return RgbMaskBoundsSync::NewInstance(env, config); case RGB_MASK_BOUNDS_ASYNC : return RgbMaskBoundsAsync::NewInstance(env, config); case RGB_REGIONS_BOUNDS_SYNC : return RgbRegionsBoundsSync::NewInstance(env, config); case RGB_REGIONS_BOUNDS_ASYNC : return RgbRegionsBoundsAsync::NewInstance(env, config); case GRAY_ALL_BLOBS_SYNC : return GrayAllBlobsSync::NewInstance(env, config); case GRAY_ALL_BLOBS_ASYNC : return GrayAllBlobsAsync::NewInstance(env, config); case GRAY_MASK_BLOBS_SYNC : return GrayMaskBlobsSync::NewInstance(env, config); case GRAY_MASK_BLOBS_ASYNC : return GrayMaskBlobsAsync::NewInstance(env, config); case GRAY_REGIONS_BLOBS_SYNC : return GrayRegionsBlobsSync::NewInstance(env, config); default: throw Napi::Error::New(env, "Engine not found for type " + std::to_string(engineType)); } } Napi::Object Init(Napi::Env env, Napi::Object exports) { exports = Napi::Function::New(env, CreateObject, "CreateObject"); GrayAllPercentSync::Init(env); GrayAllPercentAsync::Init(env); GrayMaskPercentSync::Init(env); GrayMaskPercentAsync::Init(env); GrayRegionsPercentSync::Init(env); GrayRegionsPercentAsync::Init(env); GrayAllBoundsSync::Init(env); GrayAllBoundsAsync::Init(env); GrayMaskBoundsSync::Init(env); GrayMaskBoundsAsync::Init(env); GrayRegionsBoundsSync::Init(env); GrayRegionsBoundsAsync::Init(env); RgbAllPercentSync::Init(env); RgbAllPercentAsync::Init(env); RgbMaskPercentSync::Init(env); RgbMaskPercentAsync::Init(env); RgbRegionsPercentSync::Init(env); RgbRegionsPercentAsync::Init(env); RgbAllBoundsSync::Init(env); RgbAllBoundsAsync::Init(env); RgbMaskBoundsSync::Init(env); RgbMaskBoundsAsync::Init(env); RgbRegionsBoundsSync::Init(env); RgbRegionsBoundsAsync::Init(env); GrayAllBlobsSync::Init(env); GrayAllBlobsAsync::Init(env); GrayMaskBlobsSync::Init(env); GrayMaskBlobsAsync::Init(env); GrayRegionsBlobsSync::Init(env); return exports; } NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)<|endoftext|>
<commit_before>#include <unistd.h> #include <stdio.h> #include <errno.h> #include <iostream> #include <string> using namespace std; void terminal() { char host[32];//add to readme: 32 cuz max is 64 and i dont want long printing int pid; string arg; pid = gethostname(host, 32); if(pid == -1) { perror("gethostname"); } else { cout << getlogin() << '@' << host << ':'; pid = fork(); if(pid == -1) { perror("fork"); } else if(pid == 0){ if(-1 == execvp("pwd",NULL)) { perror("error in execvp"); } } else { cout << "dask" << endl; } } cin >> arg; if(arg == "penis") { cout << ' ' << '|' << '\n'; cout << ' ' << '|' << '\n'; cout << ' ' << '|' << '\n'; cout << 'o' << '|' << 'o' << endl; } else cout << arg << endl; } int main(int argc, char* argv[]) { cout << '$' << endl; terminal(); return 0; } <commit_msg>tokenizing wit spaces<commit_after>#include <unistd.h> #include <stdio.h> #include <errno.h> #include <iostream> #include <string> #include <vector> #include <cstring> using namespace std; vector<char*> parser(string text) { char *line = new char[text.length()+1]; //strtok requires char* strcpy(line, text.c_str()); char *token = strtok(line, " "); //can be any character vector<char*> words; words.push_back(token); while(token != NULL) { words.push_back(token); token = strtok(NULL, " "); } delete[] token; return words; } void terminal() { char host[32];//add to readme: 32 cuz max is 64 and i dont want long printing int pid; string arg; pid = gethostname(host, 32); if(pid == -1) { //error perror("gethostname"); } else { cout << getlogin() << '%' << host << ':' << ' '; } getline(cin, arg); vector<char*> words = parser(arg); //TESTING DELETE THIS LATER for(int i = 0; i < words.size(); i++) { cout << words.at(i) << endl; } } int main(int argc, char* argv[]) { cout << '$' << endl; terminal(); return 0; } <|endoftext|>
<commit_before> /* Author(s): Vincent Heins Description: This is the main file!? I mean, i know this file is a BIT shitty but who cares... */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> #include <string.h> #include <stdio.h> #include <curl/curl.h> #include <mutex> #include <thread> #include <vector> /*struct MemStruct { char * memory; size_t size; }; class FReqs { public: std::string URLGet(const char * input); //std::string URLPost(char *input); private: //static size_t writer(void *contents, size_t size, size_t nmemb, void *userp); //static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in); }; */ /*std::string FReqs::URLGet(const char * input) { std::cout << input << "\n"; CURL *curl; CURLcode res; struct curl_slist *headers=NULL; curl = curl_easy_init(); std::cout << input << "\n"; std::string str; if (curl) { std::cout << input << "\n"; curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, input); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter); res = curl_easy_perform(curl); std::cout << input << "\n"; if (res == CURLE_OK) { char *ct; res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); if ((CURLE_OK == res) && ct) return str; } } return str; }*/ //like the example from https://curl.haxx.se/libcurl/c/getinmemory.html static size_t CallbackWriter(void *contents, size_t size, size_t nmemb, void *buf) { ((std::string *)buf)->append((char *)contents, size * nmemb); return size * nmemb; }; std::string fetchGET(/*char *output, const int &outputSize,*/ const char *function) { CURL *curl; CURLcode res; struct curl_slist *headers = NULL; curl = curl_easy_init(); std::string str; if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, function); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter); res = curl_easy_perform(curl); if (res == CURLE_OK) { char *ct; res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); /*if ((CURLE_OK == res) && ct) break;*/ } } str.resize(10240); /*const char * c_str = str.c_str(); strncpy(output, c_str, str.size());*/ return str; }; struct FetchResult { bool finished; int key; std::string result; }; class FetchResulting { public: std::mutex resMtx; std::vector<FetchResult *> results; }; FetchResulting *fres; void fetchResult(const char * function) { fres->resMtx.lock(); FetchResult *nRes; nRes->finished = false; nRes->key = fres->results.size(); fres->results->push_back(&nRes); fres->resMtx.unlock(); nRes->result = fetchGET(function); nRes->finished = true; }; void newThread(const char *function) { std::thread fetchRequest(fetchResult, function); }; #ifdef __GNUC__ __attribute__((constructor)) void a3urlfetch_initialization() { std::cout << "Sentence which should be displayed on server whilst initializing!" << "\n"; }; extern "C" { void RVExtension(char *output, int outputSize, const char *function); }; void RVExtension(char *output, int outputSize, const char *function) { newThread(function); }; #elif _MSC_VER #include <windows.h> #include <shellapi.h> bool APIENTRY DllMain(HMODULE hMod, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { //call of dll } break; case DLL_PROCESS_DETACH: { //stop of dll } break; }; return true; }; extern "C" { _declspec(dllexport) void __stdcall RVExtension(char *output, int outputSize, const char *function); }; void __stdcall RVExtension(char *output, int outputSize, const char *function) { outputSize = -1; fhandle->callExtension(output, outputSize, function); }; #endif <commit_msg>Changed main.cpp<commit_after> /* Author(s): Vincent Heins Description: This is the main file!? I mean, i know this file is a BIT shitty but who cares... */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> #include <string.h> #include <stdio.h> #include <curl/curl.h> #include <mutex> #include <thread> #include <vector> /*struct MemStruct { char * memory; size_t size; }; class FReqs { public: std::string URLGet(const char * input); //std::string URLPost(char *input); private: //static size_t writer(void *contents, size_t size, size_t nmemb, void *userp); //static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in); }; */ /*std::string FReqs::URLGet(const char * input) { std::cout << input << "\n"; CURL *curl; CURLcode res; struct curl_slist *headers=NULL; curl = curl_easy_init(); std::cout << input << "\n"; std::string str; if (curl) { std::cout << input << "\n"; curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, input); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter); res = curl_easy_perform(curl); std::cout << input << "\n"; if (res == CURLE_OK) { char *ct; res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); if ((CURLE_OK == res) && ct) return str; } } return str; }*/ //like the example from https://curl.haxx.se/libcurl/c/getinmemory.html static size_t CallbackWriter(void *contents, size_t size, size_t nmemb, void *buf) { ((std::string *)buf)->append((char *)contents, size * nmemb); return size * nmemb; }; std::string fetchGET(/*char *output, const int &outputSize,*/ const char *function) { CURL *curl; CURLcode res; struct curl_slist *headers = NULL; curl = curl_easy_init(); std::string str; if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, function); curl_easy_setopt(curl, CURLOPT_HTTPGET, 1); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CallbackWriter); res = curl_easy_perform(curl); if (res == CURLE_OK) { char *ct; res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); /*if ((CURLE_OK == res) && ct) break;*/ } } str.resize(10240); /*const char * c_str = str.c_str(); strncpy(output, c_str, str.size());*/ return str; }; struct FetchResult { bool finished; int key; std::string result; }; class FetchResulting { public: std::mutex resMtx; std::vector<FetchResult *> results; }; FetchResulting *fres; void fetchResult(const char * function) { fres->resMtx.lock(); FetchResult *nRes; nRes->finished = false; nRes->key = fres->results.size(); fres->results.push_back(&nRes); fres->resMtx.unlock(); nRes->result = fetchGET(function); nRes->finished = true; }; void newThread(const char *function) { std::thread fetchRequest(fetchResult, function); }; #ifdef __GNUC__ __attribute__((constructor)) void a3urlfetch_initialization() { std::cout << "Sentence which should be displayed on server whilst initializing!" << "\n"; }; extern "C" { void RVExtension(char *output, int outputSize, const char *function); }; void RVExtension(char *output, int outputSize, const char *function) { newThread(function); }; #elif _MSC_VER #include <windows.h> #include <shellapi.h> bool APIENTRY DllMain(HMODULE hMod, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { //call of dll } break; case DLL_PROCESS_DETACH: { //stop of dll } break; }; return true; }; extern "C" { _declspec(dllexport) void __stdcall RVExtension(char *output, int outputSize, const char *function); }; void __stdcall RVExtension(char *output, int outputSize, const char *function) { outputSize = -1; fhandle->callExtension(output, outputSize, function); }; #endif <|endoftext|>
<commit_before>#include <cstdio> #include "argcv/ir/index/analyzer/lexicon.hh" #include "argcv/ir/index/analyzer/basic_tokenlizer.hh" #include "argcv/ir/index/analyzer/basic_cn_analyzer.hh" using namespace argcv::ir::index::analyzer; void lexicon_sample() { lexicon lex("data.ldb"); size_t sz = lex.load("../data/lexicon/webdict_with_freq.txt"); printf("dict loaded, with size: %zu \n", sz); char buff[1024]; while (scanf("%s", buff) > 0) { printf("%s : count : %zu , level : %zu \n", buff, lex.count(buff), lex.level(buff)); } } int main(int argc, char* argv[]) { lexicon lex("data.ldb"); if (argc > 1 && strcmp(argv[1], "load") == 0) { if (argc > 2) { printf("loading lexicon from %s ... ", argv[2]); fflush(NULL); size_t lsz = lex.load(argv[2]); printf(" done, size: [%zu]\n", lsz); } else { const char* lex_path = "../data/lexicon/webdict_with_freq.txt"; printf("loading lexicon from %s ... ", lex_path); fflush(NULL); size_t lsz = lex.load(lex_path); printf(" done, size: [%zu]\n", lsz); } } basic_tokenlizer tokens( "【废土科学指南:F代表辐射,A代表原子】战争,战争永不改变。今天是《辐射4》上市的日子,虽然距离1代已经" "过去了十八年," "但和战争一样不变的,只有废土,那个承载了五十年代原子未来想象的废土。现实的物理学虽然和游戏中不同," "但我们都有同样的梦想和同样的恐惧 ... some english words " "北京城连续几天阴天,然而在低空云层之上别有一番天地。云海遮住了城市灯光,冬季夜空格外耀眼。" "\n" "结婚的和尚未结婚的同志们" "\n" "只听得一个女子低低应了一声。绿竹翁道:“姑姑请看,这部琴谱可有些古怪。”那女子又嗯了一声,琴音响起,调" "了调弦,停了一会,似是在将断了的琴弦换去,又调了调弦,便奏了起来。初时所奏和绿竹翁相同,到后来越转越" "高,那琴韵竟然履险如夷,举重若轻,毫不费力的便转了上去。令狐冲又惊又喜,依稀记得便是那天晚上所听到曲" "洋所奏的琴韵。这一曲时而慷慨激昂,时而温柔雅致,令狐冲虽不明乐理,但觉这位婆婆所奏,和曲洋所奏的曲调" "虽同,意趣却大有差别。这婆婆所奏的曲调平和中正,令人听着只觉音乐之美,却无曲洋所奏热血如沸的激奋。奏" "了良久,琴韵渐缓,似乎乐音在不住远去,倒像奏琴之人走出了数十丈之遥,又走到数里之外,细微几不可再闻" "。"); basic_cn_analyzer bcanz(&tokens, &lex); bcanz.reset(); std::string term; while (bcanz.next(term)) { printf("%s ", term.c_str()); } printf("\n"); return 0; }<commit_msg>add some samples<commit_after>#include <cstdio> #include "argcv/ir/index/analyzer/lexicon.hh" #include "argcv/ir/index/analyzer/basic_tokenlizer.hh" #include "argcv/ir/index/analyzer/basic_cn_analyzer.hh" using namespace argcv::ir::index::analyzer; void lexicon_sample() { lexicon lex("data.ldb"); size_t sz = lex.load("../data/lexicon/webdict_with_freq.txt"); printf("dict loaded, with size: %zu \n", sz); char buff[1024]; while (scanf("%s", buff) > 0) { printf("%s : count : %zu , level : %zu \n", buff, lex.count(buff), lex.level(buff)); } } int main(int argc, char* argv[]) { lexicon lex("data.ldb"); if (argc > 1 && strcmp(argv[1], "load") == 0) { if (argc > 2) { printf("loading lexicon from %s ... ", argv[2]); fflush(NULL); size_t lsz = lex.load(argv[2]); printf(" done, size: [%zu]\n", lsz); } else { const char* lex_path = "../data/lexicon/webdict_with_freq.txt"; printf("loading lexicon from %s ... ", lex_path); fflush(NULL); size_t lsz = lex.load(lex_path); printf(" done, size: [%zu]\n", lsz); } } basic_tokenlizer tokens( "【废土科学指南:F代表辐射,A代表原子】战争,战争永不改变。今天是《辐射4》上市的日子,虽然距离1代已经" "过去了十八年," "但和战争一样不变的,只有废土,那个承载了五十年代原子未来想象的废土。现实的物理学虽然和游戏中不同," "但我们都有同样的梦想和同样的恐惧 ... some english words " "北京城连续几天阴天,然而在低空云层之上别有一番天地。云海遮住了城市灯光,冬季夜空格外耀眼。" "\n" "结婚的和尚未结婚的同志们" "\n" "只听得一个女子低低应了一声。绿竹翁道:“姑姑请看,这部琴谱可有些古怪。”那女子又嗯了一声,琴音响起,调" "了调弦,停了一会,似是在将断了的琴弦换去,又调了调弦,便奏了起来。初时所奏和绿竹翁相同,到后来越转越" "高,那琴韵竟然履险如夷,举重若轻,毫不费力的便转了上去。令狐冲又惊又喜,依稀记得便是那天晚上所听到曲" "洋所奏的琴韵。这一曲时而慷慨激昂,时而温柔雅致,令狐冲虽不明乐理,但觉这位婆婆所奏,和曲洋所奏的曲调" "虽同,意趣却大有差别。这婆婆所奏的曲调平和中正,令人听着只觉音乐之美,却无曲洋所奏热血如沸的激奋。奏" "了良久,琴韵渐缓,似乎乐音在不住远去,倒像奏琴之人走出了数十丈之遥,又走到数里之外,细微几不可再闻" "。" "\n" "工信处女干事每月经过下属科室都要亲口交代24口交换机等技术性器件的安装工作" "\n" "小明硕士毕业于中国科学院计算所" "\n" "检察院鲍绍坤检察长"); basic_cn_analyzer bcanz(&tokens, &lex); bcanz.reset(); std::string term; while (bcanz.next(term)) { printf("%s ", term.c_str()); } printf("\n"); return 0; }<|endoftext|>
<commit_before>#include "Solver.hpp" #include "ScreenCapture.hpp" #include "Execute.hpp" #include "SimulatedMouse.hpp" #include <iostream> #include <chrono> #include <thread> #include <fstream> #include <windows.h> unsigned int GetNumber(std::pair<int, int> position) { // Capture relevant part of screen. ScreenCapture::CapturePart(position.first, position.second, 93, 35, "temp.bmp"); // Use tesseract to get text. Execute::ExecuteCommandLine("tesseract.exe temp.bmp out"); // Read text file and get the number. std::ifstream file("out.txt"); unsigned int number; if (!(file >> number)) { file.close(); return 0; } file.close(); return number; } int main() { std::pair<int, int> positions[] = { {913, 137}, {817, 253}, {1010, 253}, {720, 369}, {913, 369}, {1106, 369}, {817, 484}, {1010, 484}, {720, 600}, {913, 600}, {1106, 600}, {817, 716}, {1010, 716}, {913, 831} }; Solver solver; unsigned int numbers[14]; // Instruct user to switch to Three Digits, then wait for them to do so. std::cout << "You have 10 seconds to switch to Three Digits and open the level you're currently on." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); // Get numbers. for (int i=0; i<14; ++i) { numbers[i] = GetNumber(positions[i]); std::cout << positions[i].first << ":" << positions[i].second << " - " << numbers[i] << std::endl; } // Solve. solver.SetNumbers(numbers); solver.Solve(); solver.Print(); // Test simulated mouse. SimulatedMouse::Click(positions[0].first, positions[0].second); } <commit_msg>Perform solution.<commit_after>#include "Solver.hpp" #include "ScreenCapture.hpp" #include "Execute.hpp" #include "SimulatedMouse.hpp" #include <iostream> #include <chrono> #include <thread> #include <fstream> #include <windows.h> unsigned int GetNumber(std::pair<int, int> position) { // Capture relevant part of screen. ScreenCapture::CapturePart(position.first, position.second, 93, 35, "temp.bmp"); // Use tesseract to get text. Execute::ExecuteCommandLine("tesseract.exe temp.bmp out"); // Read text file and get the number. std::ifstream file("out.txt"); unsigned int number; if (!(file >> number)) { file.close(); return 0; } file.close(); return number; } int main() { std::pair<int, int> positions[] = { {913, 137}, {817, 253}, {1010, 253}, {720, 369}, {913, 369}, {1106, 369}, {817, 484}, {1010, 484}, {720, 600}, {913, 600}, {1106, 600}, {817, 716}, {1010, 716}, {913, 831} }; Solver solver; unsigned int numbers[14]; // Instruct user to switch to Three Digits, then wait for them to do so. std::cout << "You have 10 seconds to switch to Three Digits and open the level you're currently on." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); // Get numbers. for (int i=0; i<14; ++i) { numbers[i] = GetNumber(positions[i]); std::cout << positions[i].first << ":" << positions[i].second << " - " << numbers[i] << std::endl; } // Solve. solver.SetNumbers(numbers); solver.Solve(); const unsigned char* solution = solver.GetSolution(); for (int i=0; i<14; ++i) { for (unsigned char times = 0; times < solution[i]; ++times) SimulatedMouse::Click(positions[i].first, positions[i].second); } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <getopt.h> #include <errno.h> #include <limits.h> #include <unistd.h> #include <inttypes.h> #include <openssl/md5.h> #include <sys/time.h> #include <sys/resource.h> #include <map> #include <string> #include "btree.hpp" #include "misc.hpp" #include "storage.hpp" struct options { size_t blockSize; char forceCreateNewDb; char urlMode; char verbose; size_t cacheSize; size_t prefetchSize; // fields control int keyField; int keyFieldSeparator; }; struct statistic { size_t lineNumber; }; /* ------------------------------------- */ static struct options OPTS; static struct statistic STAT; void usage(); const char *getHost(const char *url, size_t len); const unsigned char *getHash(const char *string, int string_len); int getStdinLine(char *buf, int buf_size, char **line_start, int *line_len); void onSignal(int sig); void onAlarm(int sig); size_t parseSize(const char *str); int main(int argc, char *argv[]) { const char *filename = ""; unsigned long blockSize; unsigned long keyField; size_t cacheSize; unsigned long prefetchSize; char ch; STAT.lineNumber = 0; OPTS.blockSize = 4096*2; OPTS.forceCreateNewDb = 0; OPTS.verbose = 0; OPTS.urlMode = 0; OPTS.cacheSize = SIZE_T_MAX; // fields control OPTS.keyField = 0; OPTS.keyFieldSeparator = ','; while ((ch = getopt(argc, argv, "sicvub:t:S:f:d:m:p:")) != -1) { switch (ch) { case 'b': blockSize = strtoul(optarg, NULL, 0); if(blockSize < 32 || blockSize == ULONG_MAX) fatalInUserOptions("Block size must be >32\n"); OPTS.blockSize = blockSize; break; case 't': filename = optarg; break; case 'c': OPTS.forceCreateNewDb = 1; break; case 'u': OPTS.urlMode = 1; break; case 'v': OPTS.verbose = 1; break; case 'f': keyField = strtoul(optarg, NULL, 0); if(keyField == ULONG_MAX || keyField > INT_MAX) fatalInUserOptions("Field must be int"); OPTS.keyField = keyField; break; case 'm': cacheSize = parseSize(optarg); if(cacheSize == SIZE_T_MAX) fatalInUserOptions("Cache size must be positive"); OPTS.cacheSize = cacheSize; break; case 'p': prefetchSize = strtoul(optarg, NULL, 0); if(prefetchSize == ULONG_MAX || prefetchSize > SIZE_T_MAX || prefetchSize == 0) fatalInUserOptions("Prefetch size must be positive"); OPTS.prefetchSize = (size_t)prefetchSize; break; case 'd': if(strlen(optarg) != 1) fatalInUserOptions("Field separator must be char"); OPTS.keyFieldSeparator = *(char *)optarg; break; case '?': default: usage(); exit(255); } } if(!strlen(filename)) { usage(); exit(255); } signal(SIGHUP, onSignal); signal(SIGINT, onSignal); signal(SIGKILL, onSignal); signal(SIGPIPE, onSignal); signal(SIGTERM, onSignal); signal(SIGALRM, onAlarm); UniqueBTree tree(filename); tree.setPrefetchSize(OPTS.prefetchSize); if(access(filename, R_OK | W_OK) == 0 && !OPTS.forceCreateNewDb) { tree.load(); if(OPTS.verbose) fprintf(stderr, "Btree from %s with blockSize=%u was loaded\n", filename, (unsigned int)tree.blockSize); } else { tree.create(OPTS.blockSize); if(OPTS.verbose) fprintf(stderr, "New btree in %s with blockSize=%u was created\n", filename, (unsigned int)tree.blockSize); } if(OPTS.verbose) onAlarm(SIGALRM); setlinebuf(stdin); setlinebuf(stdout); char line[1024]; char *linePtr; int lineLen; if(OPTS.cacheSize < tree.blockSize) { fprintf(stderr, "Cache size must be >=blockSize [%u]\n", (unsigned int)tree.blockSize); exit(255); } tree.setCacheSize(OPTS.cacheSize / tree.blockSize); while(getStdinLine(line, sizeof(line), &linePtr, &lineLen)) { STAT.lineNumber++; if(tree.add(getHash(linePtr, lineLen))) fputs(line, stdout); } return EXIT_SUCCESS; } void onSignal(int sig) { fclose(stdin); } void onAlarm(int sig) { static double lastCallTime = -1; static size_t lastCallLineNumber = -1; static double firstCallTime = gettimed(); static size_t firstCallLineNumber = STAT.lineNumber; if(lastCallTime > 0) { fprintf( stderr, "\rSpeed [i/s]: %u avg, %u cur ", (unsigned int)((STAT.lineNumber - firstCallLineNumber) / (gettimed() - firstCallTime)), (unsigned int)((STAT.lineNumber - lastCallLineNumber) / (gettimed() - lastCallTime)) ); } lastCallLineNumber = STAT.lineNumber; lastCallTime = gettimed(); alarm(1); } // returns 0 on EOF, 1 on success int getStdinLine(char *buf, int bufSize, char **lineStart, int *lineLen){ int curField; char *cur, *next; do { if(!fgets(buf, bufSize, stdin)) return 0; if(OPTS.keyField == -1){ *lineStart = buf; *lineLen = strlen(buf); return 1; } cur = buf; curField = 1; do { next = strchr(cur, OPTS.keyFieldSeparator); if(!next){ if(curField == OPTS.keyField){ *lineStart = cur; *lineLen = strlen(cur) - 1; return 1; } break; } if(curField == OPTS.keyField){ *lineStart = cur; *lineLen = next - cur; return 1; } cur = next + 1; // skip field sep curField++; } while(cur); } while(1); } const char *getHost(const char *url, size_t len) { static char host[128]; size_t hostLen = 0; int numSlashes = 0; size_t i; for(i=0; i < len && url[i]; i++) { if(numSlashes == 2) { if(url[i] == '/') break; host[hostLen] = url[i]; hostLen++; if(hostLen >= sizeof(host) - 1) break; } if(url[i] == '/') numSlashes++; } host[hostLen] = 0; return host; } void usage() { fputs("Usage: uq [-ucv] [-f N] [-d C] [-b N] [-f S] [-p S] -t storage\n", stderr); fputs(" -t <path>: path to storage\n", stderr); fputs(" -c: force creation of storage\n", stderr); fputs(" -u: url mode\n", stderr); fputs(" -v: verbose\n", stderr); fputs(" -f <number>: select key field\n", stderr); fputs(" -d <char>: use given delimiter instead of ','\n", stderr); fputs(" -b <number>: block size\n", stderr); fputs(" -f <size>: cache size\n", stderr); fputs(" -p <size>: buffer prefetch size\n", stderr); } const unsigned char *getHash(const char *string, int string_len) { static unsigned char hashBuf[32]; string = string; if(OPTS.urlMode) { const char *host = getHost(string, string_len); MD5((const unsigned char *)host, strlen(host), hashBuf); MD5((const unsigned char *)string, string_len, hashBuf + 3); } else { MD5((const unsigned char *)string, string_len, hashBuf); } return hashBuf; } size_t parseSize(const char *str) { char mul[] = {'b', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y'}; char *inv; unsigned long l = strtoul(str, &inv, 0); if(l == ULONG_MAX) return SIZE_T_MAX; if(*inv != '\0') { size_t i; bool founded = false; for(i=0; i<sizeof(mul); i++) { if(tolower(*inv) == mul[i]) { l <<= 10 * i; founded = true; break; } } if(!founded) return SIZE_T_MAX; if(*(inv + 1) != '\0' && tolower(*(inv + 1)) != 'b') return SIZE_T_MAX; } if(l > SIZE_T_MAX) return SIZE_T_MAX; return (size_t)l; } /* THE END */ <commit_msg>Default delimiter was changed to TAB (for `cut` compatibility)<commit_after>#include <stdlib.h> #include <stdio.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <getopt.h> #include <errno.h> #include <limits.h> #include <unistd.h> #include <inttypes.h> #include <openssl/md5.h> #include <sys/time.h> #include <sys/resource.h> #include <map> #include <string> #include "btree.hpp" #include "misc.hpp" #include "storage.hpp" struct options { size_t blockSize; char forceCreateNewDb; char urlMode; char verbose; size_t cacheSize; size_t prefetchSize; // fields control int keyField; int keyFieldSeparator; }; struct statistic { size_t lineNumber; }; /* ------------------------------------- */ static struct options OPTS; static struct statistic STAT; void usage(); const char *getHost(const char *url, size_t len); const unsigned char *getHash(const char *string, int string_len); int getStdinLine(char *buf, int buf_size, char **line_start, int *line_len); void onSignal(int sig); void onAlarm(int sig); size_t parseSize(const char *str); int main(int argc, char *argv[]) { const char *filename = ""; unsigned long blockSize; unsigned long keyField; size_t cacheSize; unsigned long prefetchSize; char ch; STAT.lineNumber = 0; OPTS.blockSize = 4096*2; OPTS.forceCreateNewDb = 0; OPTS.verbose = 0; OPTS.urlMode = 0; OPTS.cacheSize = SIZE_T_MAX; // fields control OPTS.keyField = 0; OPTS.keyFieldSeparator = '\t'; while ((ch = getopt(argc, argv, "cvub:t:f:d:m:p:")) != -1) { switch (ch) { case 'b': blockSize = strtoul(optarg, NULL, 0); if(blockSize < 32 || blockSize == ULONG_MAX) fatalInUserOptions("Block size must be >32\n"); OPTS.blockSize = blockSize; break; case 't': filename = optarg; break; case 'c': OPTS.forceCreateNewDb = 1; break; case 'u': OPTS.urlMode = 1; break; case 'v': OPTS.verbose = 1; break; case 'f': keyField = strtoul(optarg, NULL, 0); if(keyField == ULONG_MAX || keyField > INT_MAX) fatalInUserOptions("Field must be int"); OPTS.keyField = keyField; break; case 'm': cacheSize = parseSize(optarg); if(cacheSize == SIZE_T_MAX) fatalInUserOptions("Cache size must be positive"); OPTS.cacheSize = cacheSize; break; case 'p': prefetchSize = strtoul(optarg, NULL, 0); if(prefetchSize == ULONG_MAX || prefetchSize > SIZE_T_MAX || prefetchSize == 0) fatalInUserOptions("Prefetch size must be positive"); OPTS.prefetchSize = (size_t)prefetchSize; break; case 'd': if(strlen(optarg) != 1) fatalInUserOptions("Field separator must be char"); OPTS.keyFieldSeparator = *(char *)optarg; break; case '?': default: usage(); exit(255); } } if(!strlen(filename)) { usage(); exit(255); } signal(SIGHUP, onSignal); signal(SIGINT, onSignal); signal(SIGKILL, onSignal); signal(SIGPIPE, onSignal); signal(SIGTERM, onSignal); signal(SIGALRM, onAlarm); UniqueBTree tree(filename); tree.setPrefetchSize(OPTS.prefetchSize); if(access(filename, R_OK | W_OK) == 0 && !OPTS.forceCreateNewDb) { tree.load(); if(OPTS.verbose) fprintf(stderr, "Btree from %s with blockSize=%u was loaded\n", filename, (unsigned int)tree.blockSize); } else { tree.create(OPTS.blockSize); if(OPTS.verbose) fprintf(stderr, "New btree in %s with blockSize=%u was created\n", filename, (unsigned int)tree.blockSize); } if(OPTS.verbose) onAlarm(SIGALRM); setlinebuf(stdin); setlinebuf(stdout); char line[1024]; char *linePtr; int lineLen; if(OPTS.cacheSize < tree.blockSize) { fprintf(stderr, "Cache size must be >=blockSize [%u]\n", (unsigned int)tree.blockSize); exit(255); } tree.setCacheSize(OPTS.cacheSize / tree.blockSize); while(getStdinLine(line, sizeof(line), &linePtr, &lineLen)) { STAT.lineNumber++; if(tree.add(getHash(linePtr, lineLen))) fputs(line, stdout); } return EXIT_SUCCESS; } void onSignal(int sig) { fclose(stdin); } void onAlarm(int sig) { static double lastCallTime = -1; static size_t lastCallLineNumber = -1; static double firstCallTime = gettimed(); static size_t firstCallLineNumber = STAT.lineNumber; if(lastCallTime > 0) { fprintf( stderr, "\rSpeed [i/s]: %u avg, %u cur ", (unsigned int)((STAT.lineNumber - firstCallLineNumber) / (gettimed() - firstCallTime)), (unsigned int)((STAT.lineNumber - lastCallLineNumber) / (gettimed() - lastCallTime)) ); } lastCallLineNumber = STAT.lineNumber; lastCallTime = gettimed(); alarm(1); } // returns 0 on EOF, 1 on success int getStdinLine(char *buf, int bufSize, char **lineStart, int *lineLen){ int curField; char *cur, *next; do { if(!fgets(buf, bufSize, stdin)) return 0; if(OPTS.keyField == -1){ *lineStart = buf; *lineLen = strlen(buf); return 1; } cur = buf; curField = 1; do { next = strchr(cur, OPTS.keyFieldSeparator); if(!next){ if(curField == OPTS.keyField){ *lineStart = cur; *lineLen = strlen(cur) - 1; return 1; } break; } if(curField == OPTS.keyField){ *lineStart = cur; *lineLen = next - cur; return 1; } cur = next + 1; // skip field sep curField++; } while(cur); } while(1); } const char *getHost(const char *url, size_t len) { static char host[128]; size_t hostLen = 0; int numSlashes = 0; size_t i; for(i=0; i < len && url[i]; i++) { if(numSlashes == 2) { if(url[i] == '/') break; host[hostLen] = url[i]; hostLen++; if(hostLen >= sizeof(host) - 1) break; } if(url[i] == '/') numSlashes++; } host[hostLen] = 0; return host; } void usage() { fputs("Usage: uq [-ucv] [-f N] [-d C] [-b N] [-f S] [-p S] -t storage\n", stderr); fputs(" -t <path>: path to storage\n", stderr); fputs(" -c: force creation of storage\n", stderr); fputs(" -u: url mode\n", stderr); fputs(" -v: verbose\n", stderr); fputs(" -f <number>: select key field\n", stderr); fputs(" -d <char>: use given delimiter instead of TAB for field delimiter\n", stderr); fputs(" -b <number>: block size\n", stderr); fputs(" -f <size>: cache size\n", stderr); fputs(" -p <size>: buffer prefetch size\n", stderr); } const unsigned char *getHash(const char *string, int string_len) { static unsigned char hashBuf[32]; string = string; if(OPTS.urlMode) { const char *host = getHost(string, string_len); MD5((const unsigned char *)host, strlen(host), hashBuf); MD5((const unsigned char *)string, string_len, hashBuf + 3); } else { MD5((const unsigned char *)string, string_len, hashBuf); } return hashBuf; } size_t parseSize(const char *str) { char mul[] = {'b', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y'}; char *inv; unsigned long l = strtoul(str, &inv, 0); if(l == ULONG_MAX) return SIZE_T_MAX; if(*inv != '\0') { size_t i; bool founded = false; for(i=0; i<sizeof(mul); i++) { if(tolower(*inv) == mul[i]) { l <<= 10 * i; founded = true; break; } } if(!founded) return SIZE_T_MAX; if(*(inv + 1) != '\0' && tolower(*(inv + 1)) != 'b') return SIZE_T_MAX; } if(l > SIZE_T_MAX) return SIZE_T_MAX; return (size_t)l; } /* THE END */ <|endoftext|>