text
stringlengths
54
60.6k
<commit_before>#include <getopt.h> #include <locale.h> #include <charconv> #include <iostream> #include "auracle/auracle.hh" #include "auracle/sort.hh" #include "auracle/terminal.hh" constexpr char kAurBaseurl[] = "https://aur.archlinux.org"; constexpr char kPacmanConf[] = "/etc/pacman.conf"; struct Flags { std::string baseurl = kAurBaseurl; std::string pacman_config = kPacmanConf; int max_connections = 5; int connect_timeout = 10; terminal::WantColor color = terminal::WantColor::AUTO; auracle::Auracle::CommandOptions command_options; }; __attribute__((noreturn)) void usage(void) { fputs( "auracle [options] command\n" "\n" "Query the AUR or download snapshots of packages.\n" "\n" " -h, --help Show this help\n" " --version Show software version\n" "\n" " -q, --quiet Output less, when possible\n" " -r, --recurse Recurse through dependencies on download\n" " --literal Disallow regex in searches\n" " --searchby=BY Change search-by dimension\n" " --connect-timeout=N Set connection timeout in seconds\n" " --max-connections=N Limit active connections\n" " --color=WHEN One of 'auto', 'never', or 'always'\n" " --sort=KEY Sort results in ascending order by KEY\n" " --rsort=KEY Sort results in descending order by KEY\n" " -C DIR, --chdir=DIR Change directory to DIR before downloading\n" "\n" "Commands:\n" " buildorder Show build order\n" " clone Clone or update git repos for packages\n" " download Download tarball snapshots\n" " info Show detailed information\n" " pkgbuild Show PKGBUILDs\n" " search Search for packages\n" " sync Check for updates for foreign packages\n" " rawinfo Dump unformatted JSON for info query\n" " rawsearch Dump unformatted JSON for search query\n", stdout); exit(0); } __attribute__((noreturn)) void version(void) { std::cout << "auracle " << PACKAGE_VERSION << "\n"; exit(0); } bool ParseFlags(int* argc, char*** argv, Flags* flags) { enum { ARG_COLOR = 1000, ARG_CONNECT_TIMEOUT, ARG_LITERAL, ARG_MAX_CONNECTIONS, ARG_SEARCHBY, ARG_VERSION, ARG_BASEURL, ARG_SORT, ARG_RSORT, ARG_PACMAN_CONFIG, }; static constexpr struct option opts[] = { // clang-format off { "help", no_argument, 0, 'h' }, { "quiet", no_argument, 0, 'q' }, { "recurse", no_argument, 0, 'r' }, { "chdir", required_argument, 0, 'C' }, { "color", required_argument, 0, ARG_COLOR }, { "connect-timeout", required_argument, 0, ARG_CONNECT_TIMEOUT }, { "literal", no_argument, 0, ARG_LITERAL }, { "max-connections", required_argument, 0, ARG_MAX_CONNECTIONS }, { "rsort", required_argument, 0, ARG_RSORT }, { "searchby", required_argument, 0, ARG_SEARCHBY }, { "sort", required_argument, 0, ARG_SORT }, { "version", no_argument, 0, ARG_VERSION }, { "baseurl", required_argument, 0, ARG_BASEURL }, { "pacmanconfig", required_argument, 0, ARG_PACMAN_CONFIG }, {}, // clang-format on }; const auto stoi = [](std::string_view s, int* i) -> bool { return std::from_chars(s.data(), s.data() + s.size(), *i).ec == std::errc{}; }; int opt; while ((opt = getopt_long(*argc, *argv, "C:hqr", opts, nullptr)) != -1) { std::string_view sv_optarg(optarg); switch (opt) { case 'h': usage(); case 'q': flags->command_options.quiet = true; break; case 'r': flags->command_options.recurse = true; break; case 'C': if (sv_optarg.empty()) { std::cerr << "error: meaningless option: -C ''\n"; return false; } flags->command_options.directory = optarg; break; case ARG_LITERAL: flags->command_options.allow_regex = false; break; case ARG_SEARCHBY: using SearchBy = aur::SearchRequest::SearchBy; flags->command_options.search_by = aur::SearchRequest::ParseSearchBy(sv_optarg); if (flags->command_options.search_by == SearchBy::INVALID) { std::cerr << "error: invalid arg to --searchby: " << sv_optarg << "\n"; return false; } break; case ARG_CONNECT_TIMEOUT: if (!stoi(sv_optarg, &flags->connect_timeout) || flags->max_connections < 0) { std::cerr << "error: invalid value to --connect-timeout: " << sv_optarg << "\n"; return false; } break; case ARG_MAX_CONNECTIONS: if (!stoi(sv_optarg, &flags->max_connections) || flags->max_connections < 0) { std::cerr << "error: invalid value to --max-connections: " << sv_optarg << "\n"; return false; } break; case ARG_COLOR: if (sv_optarg == "auto") { flags->color = terminal::WantColor::AUTO; } else if (sv_optarg == "never") { flags->color = terminal::WantColor::NO; } else if (sv_optarg == "always") { flags->color = terminal::WantColor::YES; } else { std::cerr << "error: invalid arg to --color: " << sv_optarg << "\n"; return false; } break; case ARG_SORT: flags->command_options.sorter = sort::MakePackageSorter(sv_optarg, sort::OrderBy::ORDER_ASC); if (flags->command_options.sorter == nullptr) { std::cerr << "error: invalid arg to --sort: " << sv_optarg << "\n"; } break; case ARG_RSORT: flags->command_options.sorter = sort::MakePackageSorter(sv_optarg, sort::OrderBy::ORDER_DESC); if (flags->command_options.sorter == nullptr) { std::cerr << "error: invalid arg to --rsort: " << sv_optarg << "\n"; } break; case ARG_BASEURL: flags->baseurl = std::string(sv_optarg); break; case ARG_PACMAN_CONFIG: flags->pacman_config = std::string(sv_optarg); break; case ARG_VERSION: version(); break; default: return false; } } *argc -= optind - 1; *argv += optind - 1; return true; } int main(int argc, char** argv) { Flags flags; if (!ParseFlags(&argc, &argv, &flags)) { return 1; } if (argc < 2) { std::cerr << "error: no operation specified (use -h for help)\n"; return 1; } setlocale(LC_ALL, ""); terminal::Init(flags.color); const auto pacman = auracle::Pacman::NewFromConfig(flags.pacman_config); if (pacman == nullptr) { std::cerr << "error: failed to parse " << flags.pacman_config << "\n"; return 1; } auracle::Auracle auracle(auracle::Auracle::Options() .set_aur_baseurl(flags.baseurl) .set_pacman(pacman.get()) .set_connection_timeout(flags.connect_timeout) .set_max_connections(flags.max_connections)); std::string_view action(argv[1]); std::vector<std::string> args(argv + 2, argv + argc); std::unordered_map<std::string_view, int (auracle::Auracle::*)( const std::vector<std::string>& args, const auracle::Auracle::CommandOptions& options)> cmds{ {"buildorder", &auracle::Auracle::BuildOrder}, {"clone", &auracle::Auracle::Clone}, {"download", &auracle::Auracle::Download}, {"info", &auracle::Auracle::Info}, {"pkgbuild", &auracle::Auracle::Pkgbuild}, {"rawinfo", &auracle::Auracle::RawInfo}, {"rawsearch", &auracle::Auracle::RawSearch}, {"search", &auracle::Auracle::Search}, {"sync", &auracle::Auracle::Sync}, }; if (auto iter = cmds.find(action); iter != cmds.end()) { return (auracle.*iter->second)(args, flags.command_options) < 0 ? 1 : 0; } std::cerr << "Unknown action " << action << "\n"; return 1; } /* vim: set et ts=2 sw=2: */ <commit_msg>Add missing error return on bad value to --sort/--rsort<commit_after>#include <getopt.h> #include <locale.h> #include <charconv> #include <iostream> #include "auracle/auracle.hh" #include "auracle/sort.hh" #include "auracle/terminal.hh" constexpr char kAurBaseurl[] = "https://aur.archlinux.org"; constexpr char kPacmanConf[] = "/etc/pacman.conf"; struct Flags { std::string baseurl = kAurBaseurl; std::string pacman_config = kPacmanConf; int max_connections = 5; int connect_timeout = 10; terminal::WantColor color = terminal::WantColor::AUTO; auracle::Auracle::CommandOptions command_options; }; __attribute__((noreturn)) void usage(void) { fputs( "auracle [options] command\n" "\n" "Query the AUR or download snapshots of packages.\n" "\n" " -h, --help Show this help\n" " --version Show software version\n" "\n" " -q, --quiet Output less, when possible\n" " -r, --recurse Recurse through dependencies on download\n" " --literal Disallow regex in searches\n" " --searchby=BY Change search-by dimension\n" " --connect-timeout=N Set connection timeout in seconds\n" " --max-connections=N Limit active connections\n" " --color=WHEN One of 'auto', 'never', or 'always'\n" " --sort=KEY Sort results in ascending order by KEY\n" " --rsort=KEY Sort results in descending order by KEY\n" " -C DIR, --chdir=DIR Change directory to DIR before downloading\n" "\n" "Commands:\n" " buildorder Show build order\n" " clone Clone or update git repos for packages\n" " download Download tarball snapshots\n" " info Show detailed information\n" " pkgbuild Show PKGBUILDs\n" " search Search for packages\n" " sync Check for updates for foreign packages\n" " rawinfo Dump unformatted JSON for info query\n" " rawsearch Dump unformatted JSON for search query\n", stdout); exit(0); } __attribute__((noreturn)) void version(void) { std::cout << "auracle " << PACKAGE_VERSION << "\n"; exit(0); } bool ParseFlags(int* argc, char*** argv, Flags* flags) { enum { ARG_COLOR = 1000, ARG_CONNECT_TIMEOUT, ARG_LITERAL, ARG_MAX_CONNECTIONS, ARG_SEARCHBY, ARG_VERSION, ARG_BASEURL, ARG_SORT, ARG_RSORT, ARG_PACMAN_CONFIG, }; static constexpr struct option opts[] = { // clang-format off { "help", no_argument, 0, 'h' }, { "quiet", no_argument, 0, 'q' }, { "recurse", no_argument, 0, 'r' }, { "chdir", required_argument, 0, 'C' }, { "color", required_argument, 0, ARG_COLOR }, { "connect-timeout", required_argument, 0, ARG_CONNECT_TIMEOUT }, { "literal", no_argument, 0, ARG_LITERAL }, { "max-connections", required_argument, 0, ARG_MAX_CONNECTIONS }, { "rsort", required_argument, 0, ARG_RSORT }, { "searchby", required_argument, 0, ARG_SEARCHBY }, { "sort", required_argument, 0, ARG_SORT }, { "version", no_argument, 0, ARG_VERSION }, { "baseurl", required_argument, 0, ARG_BASEURL }, { "pacmanconfig", required_argument, 0, ARG_PACMAN_CONFIG }, {}, // clang-format on }; const auto stoi = [](std::string_view s, int* i) -> bool { return std::from_chars(s.data(), s.data() + s.size(), *i).ec == std::errc{}; }; int opt; while ((opt = getopt_long(*argc, *argv, "C:hqr", opts, nullptr)) != -1) { std::string_view sv_optarg(optarg); switch (opt) { case 'h': usage(); case 'q': flags->command_options.quiet = true; break; case 'r': flags->command_options.recurse = true; break; case 'C': if (sv_optarg.empty()) { std::cerr << "error: meaningless option: -C ''\n"; return false; } flags->command_options.directory = optarg; break; case ARG_LITERAL: flags->command_options.allow_regex = false; break; case ARG_SEARCHBY: using SearchBy = aur::SearchRequest::SearchBy; flags->command_options.search_by = aur::SearchRequest::ParseSearchBy(sv_optarg); if (flags->command_options.search_by == SearchBy::INVALID) { std::cerr << "error: invalid arg to --searchby: " << sv_optarg << "\n"; return false; } break; case ARG_CONNECT_TIMEOUT: if (!stoi(sv_optarg, &flags->connect_timeout) || flags->max_connections < 0) { std::cerr << "error: invalid value to --connect-timeout: " << sv_optarg << "\n"; return false; } break; case ARG_MAX_CONNECTIONS: if (!stoi(sv_optarg, &flags->max_connections) || flags->max_connections < 0) { std::cerr << "error: invalid value to --max-connections: " << sv_optarg << "\n"; return false; } break; case ARG_COLOR: if (sv_optarg == "auto") { flags->color = terminal::WantColor::AUTO; } else if (sv_optarg == "never") { flags->color = terminal::WantColor::NO; } else if (sv_optarg == "always") { flags->color = terminal::WantColor::YES; } else { std::cerr << "error: invalid arg to --color: " << sv_optarg << "\n"; return false; } break; case ARG_SORT: flags->command_options.sorter = sort::MakePackageSorter(sv_optarg, sort::OrderBy::ORDER_ASC); if (flags->command_options.sorter == nullptr) { std::cerr << "error: invalid arg to --sort: " << sv_optarg << "\n"; return false; } break; case ARG_RSORT: flags->command_options.sorter = sort::MakePackageSorter(sv_optarg, sort::OrderBy::ORDER_DESC); if (flags->command_options.sorter == nullptr) { std::cerr << "error: invalid arg to --rsort: " << sv_optarg << "\n"; return false; } break; case ARG_BASEURL: flags->baseurl = std::string(sv_optarg); break; case ARG_PACMAN_CONFIG: flags->pacman_config = std::string(sv_optarg); break; case ARG_VERSION: version(); break; default: return false; } } *argc -= optind - 1; *argv += optind - 1; return true; } int main(int argc, char** argv) { Flags flags; if (!ParseFlags(&argc, &argv, &flags)) { return 1; } if (argc < 2) { std::cerr << "error: no operation specified (use -h for help)\n"; return 1; } setlocale(LC_ALL, ""); terminal::Init(flags.color); const auto pacman = auracle::Pacman::NewFromConfig(flags.pacman_config); if (pacman == nullptr) { std::cerr << "error: failed to parse " << flags.pacman_config << "\n"; return 1; } auracle::Auracle auracle(auracle::Auracle::Options() .set_aur_baseurl(flags.baseurl) .set_pacman(pacman.get()) .set_connection_timeout(flags.connect_timeout) .set_max_connections(flags.max_connections)); std::string_view action(argv[1]); std::vector<std::string> args(argv + 2, argv + argc); std::unordered_map<std::string_view, int (auracle::Auracle::*)( const std::vector<std::string>& args, const auracle::Auracle::CommandOptions& options)> cmds{ {"buildorder", &auracle::Auracle::BuildOrder}, {"clone", &auracle::Auracle::Clone}, {"download", &auracle::Auracle::Download}, {"info", &auracle::Auracle::Info}, {"pkgbuild", &auracle::Auracle::Pkgbuild}, {"rawinfo", &auracle::Auracle::RawInfo}, {"rawsearch", &auracle::Auracle::RawSearch}, {"search", &auracle::Auracle::Search}, {"sync", &auracle::Auracle::Sync}, }; if (auto iter = cmds.find(action); iter != cmds.end()) { return (auracle.*iter->second)(args, flags.command_options) < 0 ? 1 : 0; } std::cerr << "Unknown action " << action << "\n"; return 1; } /* vim: set et ts=2 sw=2: */ <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_TIMER_INCLUDED #define MAPNIK_TIMER_INCLUDED #include <cstdlib> #include <string> #include <sys/time.h> namespace mapnik { // Measure times in both wall clock time and CPU times. Results are returned in milliseconds. class timer { public: timer() { restart(); } void restart() { _stopped = false; gettimeofday(&_wall_clock_start, NULL); _cpu_start = clock(); } virtual void stop() const { _stopped = true; _cpu_end = clock(); gettimeofday(&_wall_clock_end, NULL); } double cpu_elapsed() const { // return elapsed CPU time in ms if (!_stopped) stop(); return ((double) (_cpu_end - _cpu_start)) / CLOCKS_PER_SEC * 1000.0; } double wall_clock_elapsed() const { // return elapsed wall clock time in ms if (!_stopped) stop(); long seconds = _wall_clock_end.tv_sec - _wall_clock_start.tv_sec; long useconds = _wall_clock_end.tv_usec - _wall_clock_start.tv_usec; return ((seconds) * 1000 + useconds / 1000.0) + 0.5; } protected: mutable timeval _wall_clock_start, _wall_clock_end; mutable clock_t _cpu_start, _cpu_end; mutable bool _stopped; }; // A progress_timer behaves like a timer except that the destructor displays // an elapsed time message at an appropriate place in an appropriate form. class progress_timer : public timer { public: progress_timer(std::ostream & os, std::string const& base_message): os_(os), base_message_(base_message) {} ~progress_timer() { if (!_stopped) stop(); } void stop() const { timer::stop(); try { std::ostringstream s; s.precision(2); s << std::fixed; s << wall_clock_elapsed() << "ms (cpu " << cpu_elapsed() << "ms)"; s << std::setw(30 - (int)s.tellp()) << std::right << "| " << base_message_ << "\n"; os_ << s.str(); } catch (...) {} // eat any exceptions } void discard() { _stopped = true; } private: std::ostream & os_; std::string base_message_; }; }; #endif // MAPNIK_TIMER_INCLUDED<commit_msg>more includes for timer<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_TIMER_INCLUDED #define MAPNIK_TIMER_INCLUDED #include <cstdlib> #include <string> #include <sstream> #include <iomanip> #include <sys/time.h> namespace mapnik { // Measure times in both wall clock time and CPU times. Results are returned in milliseconds. class timer { public: timer() { restart(); } void restart() { _stopped = false; gettimeofday(&_wall_clock_start, NULL); _cpu_start = clock(); } virtual void stop() const { _stopped = true; _cpu_end = clock(); gettimeofday(&_wall_clock_end, NULL); } double cpu_elapsed() const { // return elapsed CPU time in ms if (!_stopped) stop(); return ((double) (_cpu_end - _cpu_start)) / CLOCKS_PER_SEC * 1000.0; } double wall_clock_elapsed() const { // return elapsed wall clock time in ms if (!_stopped) stop(); long seconds = _wall_clock_end.tv_sec - _wall_clock_start.tv_sec; long useconds = _wall_clock_end.tv_usec - _wall_clock_start.tv_usec; return ((seconds) * 1000 + useconds / 1000.0) + 0.5; } protected: mutable timeval _wall_clock_start, _wall_clock_end; mutable clock_t _cpu_start, _cpu_end; mutable bool _stopped; }; // A progress_timer behaves like a timer except that the destructor displays // an elapsed time message at an appropriate place in an appropriate form. class progress_timer : public timer { public: progress_timer(std::ostream & os, std::string const& base_message): os_(os), base_message_(base_message) {} ~progress_timer() { if (!_stopped) stop(); } void stop() const { timer::stop(); try { std::ostringstream s; s.precision(2); s << std::fixed; s << wall_clock_elapsed() << "ms (cpu " << cpu_elapsed() << "ms)"; s << std::setw(30 - (int)s.tellp()) << std::right << "| " << base_message_ << "\n"; os_ << s.str(); } catch (...) {} // eat any exceptions } void discard() { _stopped = true; } private: std::ostream & os_; std::string base_message_; }; }; #endif // MAPNIK_TIMER_INCLUDED<|endoftext|>
<commit_before>// Copyright 2020 The gVisor 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 <poll.h> #include <stdio.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/un.h> #include "gtest/gtest.h" #include "test/syscalls/linux/ip_socket_test_util.h" #include "test/syscalls/linux/socket_test_util.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected sockets. using ConnectStressTest = SocketPairTest; TEST_P(ConnectStressTest, Reset65kTimes) { for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); // Send some data to ensure that the connection gets reset and the port gets // released immediately. This avoids either end entering TIME-WAIT. char sent_data[100] = {}; ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)), SyscallSucceedsWithValue(sizeof(sent_data))); // Poll the other FD to make sure that the data is in the receive buffer // before closing it to ensure a RST is triggered. const int kTimeout = 10000; struct pollfd pfd = { .fd = sockets->second_fd(), .events = POLL_IN, }; ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1)); } } INSTANTIATE_TEST_SUITE_P( AllConnectedSockets, ConnectStressTest, ::testing::Values(IPv6UDPBidirectionalBindSocketPair(0), IPv4UDPBidirectionalBindSocketPair(0), DualStackUDPBidirectionalBindSocketPair(0), // Without REUSEADDR, we get port exhaustion on Linux. SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(IPv6TCPAcceptBindSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(IPv4TCPAcceptBindSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( DualStackTCPAcceptBindSocketPair(0)))); // Test fixture for tests that apply to pairs of connected sockets created with // a persistent listener (if applicable). using PersistentListenerConnectStressTest = SocketPairTest; TEST_P(PersistentListenerConnectStressTest, 65kTimesShutdownCloseFirst) { for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); ASSERT_THAT(shutdown(sockets->first_fd(), SHUT_RDWR), SyscallSucceeds()); if (GetParam().type == SOCK_STREAM) { // Poll the other FD to make sure that we see the FIN from the other // side before closing the second_fd. This ensures that the first_fd // enters TIME-WAIT and not second_fd. const int kTimeout = 10000; struct pollfd pfd = { .fd = sockets->second_fd(), .events = POLL_IN, }; ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1)); } ASSERT_THAT(shutdown(sockets->second_fd(), SHUT_RDWR), SyscallSucceeds()); } } TEST_P(PersistentListenerConnectStressTest, 65kTimesShutdownCloseSecond) { for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); ASSERT_THAT(shutdown(sockets->second_fd(), SHUT_RDWR), SyscallSucceeds()); if (GetParam().type == SOCK_STREAM) { // Poll the other FD to make sure that we see the FIN from the other // side before closing the first_fd. This ensures that the second_fd // enters TIME-WAIT and not first_fd. const int kTimeout = 10000; struct pollfd pfd = { .fd = sockets->first_fd(), .events = POLL_IN, }; ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1)); } ASSERT_THAT(shutdown(sockets->first_fd(), SHUT_RDWR), SyscallSucceeds()); } } TEST_P(PersistentListenerConnectStressTest, 65kTimesClose) { for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); } } INSTANTIATE_TEST_SUITE_P( AllConnectedSockets, PersistentListenerConnectStressTest, ::testing::Values( IPv6UDPBidirectionalBindSocketPair(0), IPv4UDPBidirectionalBindSocketPair(0), DualStackUDPBidirectionalBindSocketPair(0), // Without REUSEADDR, we get port exhaustion on Linux. SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( IPv6TCPAcceptBindPersistentListenerSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( IPv4TCPAcceptBindPersistentListenerSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( DualStackTCPAcceptBindPersistentListenerSocketPair(0)))); } // namespace testing } // namespace gvisor <commit_msg>Skip socket stress tests on KVM platform.<commit_after>// Copyright 2020 The gVisor 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 <poll.h> #include <stdio.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/un.h> #include "gtest/gtest.h" #include "test/syscalls/linux/ip_socket_test_util.h" #include "test/syscalls/linux/socket_test_util.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { // Test fixture for tests that apply to pairs of connected sockets. using ConnectStressTest = SocketPairTest; TEST_P(ConnectStressTest, Reset65kTimes) { // TODO(b/165912341): These are too slow on KVM platform with nested virt. SKIP_IF(GvisorPlatform() == Platform::kKVM); for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); // Send some data to ensure that the connection gets reset and the port gets // released immediately. This avoids either end entering TIME-WAIT. char sent_data[100] = {}; ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)), SyscallSucceedsWithValue(sizeof(sent_data))); // Poll the other FD to make sure that the data is in the receive buffer // before closing it to ensure a RST is triggered. const int kTimeout = 10000; struct pollfd pfd = { .fd = sockets->second_fd(), .events = POLL_IN, }; ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1)); } } INSTANTIATE_TEST_SUITE_P( AllConnectedSockets, ConnectStressTest, ::testing::Values(IPv6UDPBidirectionalBindSocketPair(0), IPv4UDPBidirectionalBindSocketPair(0), DualStackUDPBidirectionalBindSocketPair(0), // Without REUSEADDR, we get port exhaustion on Linux. SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(IPv6TCPAcceptBindSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(IPv4TCPAcceptBindSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( DualStackTCPAcceptBindSocketPair(0)))); // Test fixture for tests that apply to pairs of connected sockets created with // a persistent listener (if applicable). using PersistentListenerConnectStressTest = SocketPairTest; TEST_P(PersistentListenerConnectStressTest, 65kTimesShutdownCloseFirst) { // TODO(b/165912341): These are too slow on KVM platform with nested virt. SKIP_IF(GvisorPlatform() == Platform::kKVM); for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); ASSERT_THAT(shutdown(sockets->first_fd(), SHUT_RDWR), SyscallSucceeds()); if (GetParam().type == SOCK_STREAM) { // Poll the other FD to make sure that we see the FIN from the other // side before closing the second_fd. This ensures that the first_fd // enters TIME-WAIT and not second_fd. const int kTimeout = 10000; struct pollfd pfd = { .fd = sockets->second_fd(), .events = POLL_IN, }; ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1)); } ASSERT_THAT(shutdown(sockets->second_fd(), SHUT_RDWR), SyscallSucceeds()); } } TEST_P(PersistentListenerConnectStressTest, 65kTimesShutdownCloseSecond) { // TODO(b/165912341): These are too slow on KVM platform with nested virt. SKIP_IF(GvisorPlatform() == Platform::kKVM); for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); ASSERT_THAT(shutdown(sockets->second_fd(), SHUT_RDWR), SyscallSucceeds()); if (GetParam().type == SOCK_STREAM) { // Poll the other FD to make sure that we see the FIN from the other // side before closing the first_fd. This ensures that the second_fd // enters TIME-WAIT and not first_fd. const int kTimeout = 10000; struct pollfd pfd = { .fd = sockets->first_fd(), .events = POLL_IN, }; ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1)); } ASSERT_THAT(shutdown(sockets->first_fd(), SHUT_RDWR), SyscallSucceeds()); } } TEST_P(PersistentListenerConnectStressTest, 65kTimesClose) { // TODO(b/165912341): These are too slow on KVM platform with nested virt. SKIP_IF(GvisorPlatform() == Platform::kKVM); for (int i = 0; i < 1 << 16; ++i) { auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair()); } } INSTANTIATE_TEST_SUITE_P( AllConnectedSockets, PersistentListenerConnectStressTest, ::testing::Values( IPv6UDPBidirectionalBindSocketPair(0), IPv4UDPBidirectionalBindSocketPair(0), DualStackUDPBidirectionalBindSocketPair(0), // Without REUSEADDR, we get port exhaustion on Linux. SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( IPv6TCPAcceptBindPersistentListenerSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( IPv4TCPAcceptBindPersistentListenerSocketPair(0)), SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)( DualStackTCPAcceptBindPersistentListenerSocketPair(0)))); } // namespace testing } // namespace gvisor <|endoftext|>
<commit_before>// @(#)root/tree:$Name: $:$Id: TLeafC.cxx,v 1.14 2002/12/13 22:12:55 brun Exp $ // Author: Rene Brun 17/03/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf for a variable length string. // ////////////////////////////////////////////////////////////////////////// #include "TLeafC.h" #include "TBranch.h" ClassImp(TLeafC) //______________________________________________________________________________ TLeafC::TLeafC(): TLeaf() { //*-*-*-*-*-*Default constructor for LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::TLeafC(const char *name, const char *type) :TLeaf(name,type) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============== //*-* fLenType = 1; fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::~TLeafC() { //*-*-*-*-*-*Default destructor for a LeafC*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== if (ResetAddress(0,kTRUE)) delete [] fValue; } //______________________________________________________________________________ void TLeafC::Export(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-* //*-* ==================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::FillBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================== if (fPointer) fValue = *fPointer; Int_t len = strlen(fValue); if (len >= fMaximum) fMaximum = len+1; if (len >= fLen) fLen = len+1; if (len < 255) { b << (UChar_t)len; } else { b << (UChar_t)255; b << len; } if (len) b.WriteFastArray(fValue,len); } //______________________________________________________________________________ const char *TLeafC::GetTypeName() const { //*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= if (fIsUnsigned) return "UChar_t"; return "Char_t"; } //______________________________________________________________________________ void TLeafC::Import(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-* //*-* ====================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy(&fValue[j],(char*)list->UncheckedAt(i) + fOffset, 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::PrintValue(Int_t) const { // Prints leaf value char *value = (char*)GetValuePointer(); printf("%s",value); } //______________________________________________________________________________ void TLeafC::ReadBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* //*-* =========================================== Int_t len; UChar_t lenchar; b >> lenchar; if (lenchar < 255) { len = lenchar; } else { b >> len; } if (len) { if (len >= fLen) len = fLen-1; b.ReadFastArray(fValue,len); fValue[len] = 0; } else { fValue[0] = 0; } } //______________________________________________________________________________ void TLeafC::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* // and export buffer to TClonesArray objects UChar_t len; b >> len; if (len) { if (len >= fLen) len = fLen-1; b.ReadFastArray(fValue,len); fValue[len] = 0; } else { fValue[0] = 0; } Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::ReadValue(ifstream &s) { // read a string from ifstream s and store it into the branch buffer char *value = (char*)GetValuePointer(); s >> value; } //______________________________________________________________________________ void TLeafC::SetAddress(void *add) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ if (ResetAddress(add)) { delete [] fValue; } if (add) { if (TestBit(kIndirectAddress)) { fPointer = (char**)add; Int_t ncountmax = fLen; if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1); if (ncountmax > fNdata || *fPointer == 0) { if (*fPointer) delete [] *fPointer; if (ncountmax > fNdata) fNdata = ncountmax; *fPointer = new char[fNdata]; } fValue = *fPointer; } else { fValue = (char*)add; } } else { fValue = new char[fNdata]; fValue[0] = 0; } } <commit_msg>factor the string storage into TBuffer<commit_after>// @(#)root/tree:$Name: $:$Id: TLeafC.cxx,v 1.15 2004/10/18 12:32:12 brun Exp $ // Author: Rene Brun 17/03/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf for a variable length string. // ////////////////////////////////////////////////////////////////////////// #include "TLeafC.h" #include "TBranch.h" ClassImp(TLeafC) //______________________________________________________________________________ TLeafC::TLeafC(): TLeaf() { //*-*-*-*-*-*Default constructor for LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::TLeafC(const char *name, const char *type) :TLeaf(name,type) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============== //*-* fLenType = 1; fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::~TLeafC() { //*-*-*-*-*-*Default destructor for a LeafC*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== if (ResetAddress(0,kTRUE)) delete [] fValue; } //______________________________________________________________________________ void TLeafC::Export(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-* //*-* ==================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::FillBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================== if (fPointer) fValue = *fPointer; Int_t len = strlen(fValue); if (len >= fMaximum) fMaximum = len+1; if (len >= fLen) fLen = len+1; if (len) b.WriteFastArrayString(fValue,len); } //______________________________________________________________________________ const char *TLeafC::GetTypeName() const { //*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= if (fIsUnsigned) return "UChar_t"; return "Char_t"; } //______________________________________________________________________________ void TLeafC::Import(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-* //*-* ====================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy(&fValue[j],(char*)list->UncheckedAt(i) + fOffset, 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::PrintValue(Int_t) const { // Prints leaf value char *value = (char*)GetValuePointer(); printf("%s",value); } //______________________________________________________________________________ void TLeafC::ReadBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* //*-* =========================================== b.ReadFastArrayString(fValue,fLen); } //______________________________________________________________________________ void TLeafC::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n) { //*-*-*-*-*-*-*-*-*-*-*Read leaf elements from Basket input buffer*-*-*-*-*-* // and export buffer to TClonesArray objects UChar_t len; b >> len; if (len) { if (len >= fLen) len = fLen-1; b.ReadFastArray(fValue,len); fValue[len] = 0; } else { fValue[0] = 0; } Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::ReadValue(ifstream &s) { // read a string from ifstream s and store it into the branch buffer char *value = (char*)GetValuePointer(); s >> value; } //______________________________________________________________________________ void TLeafC::SetAddress(void *add) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ if (ResetAddress(add)) { delete [] fValue; } if (add) { if (TestBit(kIndirectAddress)) { fPointer = (char**)add; Int_t ncountmax = fLen; if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1); if (ncountmax > fNdata || *fPointer == 0) { if (*fPointer) delete [] *fPointer; if (ncountmax > fNdata) fNdata = ncountmax; *fPointer = new char[fNdata]; } fValue = *fPointer; } else { fValue = (char*)add; } } else { fValue = new char[fNdata]; fValue[0] = 0; } } <|endoftext|>
<commit_before>#ifndef __NATIVE_ERROR_HPP__ #define __NATIVE_ERROR_HPP__ #include "base/base_utils.hpp" namespace native { class Exception { public: struct CallStack { CallStack() = delete; CallStack(const std::string &iFile, const int iLine, const std::string &iFunction) : _file(iFile), _line(iLine), _function(iFunction) {} std::string _file; int _line; std::string _function; }; Exception(const std::string &message) : _message(message), _uvError(0) {} Exception(const std::string &message, const std::string &iFile, const int iLine, const std::string &iFunction) : _message(message), _uvError(0) { CallStack item(iFile, iLine, iFunction); _callStack.push_back(item); } Exception(const std::string &message, const std::string &iFile, const int iLine, const std::string &iFunction, const int iuvError) : _message(message), _uvError(iuvError) { CallStack item(iFile, iLine, iFunction); _callStack.push_back(item); } Exception(const Exception &iOther, const std::string &iFile, const int iLine, const std::string &iFunction) { CallStack item(iFile, iLine, iFunction); _callStack.push_back(item); for (const CallStack &i : iOther._callStack) { _callStack.push_back(i); } _message = iOther._message; _uvError = iOther._uvError; } virtual ~Exception() {} const std::string &message() const { return _message; } private: std::string _message; std::list<CallStack> _callStack; int _uvError; }; class Error { public: Error() : _uv_err(0) {} Error(int iErrCode) : _uv_err(iErrCode) {} Error(const std::string &str) : _uv_err(-1), _str(str) {} ~Error() = default; bool isError() { return (_uv_err < 0); } bool isOK() { return (_uv_err > 0); } operator bool() { return isError(); } virtual Error &operator=(int iErrCode) { setError(iErrCode); return *this; } void setError(int iErrCode) { _uv_err = iErrCode; } int code() const { return _uv_err; } virtual const char *name() const { if (_str.empty() && _uv_err < 0) { return uv_err_name(_uv_err); } return 0; } virtual const char *str() const { if (!_str.empty()) { return _str.c_str(); } else if (_uv_err < 0) { return uv_strerror(_uv_err); } return 0; } private: int _uv_err; std::string _str; }; } #endif /* __NATIVE_ERROR_HPP__ */ <commit_msg>error: resolve isOK method<commit_after>#ifndef __NATIVE_ERROR_HPP__ #define __NATIVE_ERROR_HPP__ #include "base/base_utils.hpp" namespace native { class Exception { public: struct CallStack { CallStack() = delete; CallStack(const std::string &iFile, const int iLine, const std::string &iFunction) : _file(iFile), _line(iLine), _function(iFunction) {} std::string _file; int _line; std::string _function; }; Exception(const std::string &message) : _message(message), _uvError(0) {} Exception(const std::string &message, const std::string &iFile, const int iLine, const std::string &iFunction) : _message(message), _uvError(0) { CallStack item(iFile, iLine, iFunction); _callStack.push_back(item); } Exception(const std::string &message, const std::string &iFile, const int iLine, const std::string &iFunction, const int iuvError) : _message(message), _uvError(iuvError) { CallStack item(iFile, iLine, iFunction); _callStack.push_back(item); } Exception(const Exception &iOther, const std::string &iFile, const int iLine, const std::string &iFunction) { CallStack item(iFile, iLine, iFunction); _callStack.push_back(item); for (const CallStack &i : iOther._callStack) { _callStack.push_back(i); } _message = iOther._message; _uvError = iOther._uvError; } virtual ~Exception() {} const std::string &message() const { return _message; } private: std::string _message; std::list<CallStack> _callStack; int _uvError; }; class Error { public: Error() : _uv_err(0) {} Error(int iErrCode) : _uv_err(iErrCode) {} Error(const std::string &str) : _uv_err(-1), _str(str) {} ~Error() = default; bool isError() { return (_uv_err < 0); } bool isOK() { return !isError(); } operator bool() { return isError(); } virtual Error &operator=(int iErrCode) { setError(iErrCode); return *this; } void setError(int iErrCode) { _uv_err = iErrCode; } int code() const { return _uv_err; } virtual const char *name() const { if (_str.empty() && _uv_err < 0) { return uv_err_name(_uv_err); } return 0; } virtual const char *str() const { if (!_str.empty()) { return _str.c_str(); } else if (_uv_err < 0) { return uv_strerror(_uv_err); } return 0; } private: int _uv_err; std::string _str; }; } #endif /* __NATIVE_ERROR_HPP__ */ <|endoftext|>
<commit_before> #ifndef NDHIST_DTYPE_H_INCLUDED #define NDHIST_DTYPE_H_INCLUDED 1 #include <stdint.h> namespace ndhist { /** * The dtype_desc class provides a base class for all data type classes * usable with ndhist. It stores the size of the particular data type in bytes. */ class dtype_desc { public: dtype_desc() : size_(0) {} dtype_desc(size_t size) : size_(size) {} inline size_t GetSize() const { return size_; } protected: /// The size of the data type in bytes. size_t size_; }; template <CPPType> class dtype : public dtype_desc { public: typedef CPPType cpp_type; dtype() : dtype_desc(sizeof(cpp_type)) {} }; class float64 : public dtype<double> { public: typedef dtype<double> base; typedef typename base::cpp_type cpp_type; float64() : base() {} }; class uint64 : public dtype<uint64_t> { public: typedef dtype<uint64_t> base; typedef typename base::cpp_type cpp_type; uint64() : base() {} }; class dtype_value { public: dtype_value(dtype_desc const & dt) : dtype_desc_(dt) , data_(NULL) {} template <typename T> bool set(T value) { size_t sizeT = sizeof(T); // Check if T is compatible with the given dtype_desc. dtype<T> dt; if(dt.GetSize() != sizeT) { return false; } // Allocate memory, if not done so alreay before. if(data_ == NULL) { data_ = malloc(sizeT); if(data_ == NULL) { return false; } } memcpy(data_, &value, sizeT); return true; } template <typename T> T& get() { } protected: char* data_; dtype_desc dtype_desc_; }; }// namespace ndhist #endif <commit_msg>Get rid of an old file/idea.<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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. ****************************************************************************/ #ifndef INCLUDED_OPTIONS_HPP #define INCLUDED_OPTIONS_HPP #include <pdal/pdal.hpp> #include <pdal/exceptions.hpp> #include <pdal/Bounds.hpp> #include <boost/property_tree/ptree.hpp> namespace pdal { class PDAL_DLL OptionsOld { private: boost::property_tree::ptree m_tree; public: OptionsOld() { m_tree.put("is3d", false); } OptionsOld(boost::property_tree::ptree const& tree) { m_tree = tree; } boost::property_tree::ptree& GetPTree() { return m_tree; } boost::property_tree::ptree const& GetPTree() const { return m_tree; } }; // An Option is just a record with three fields: name, value, and description. // // Dumped as XML, it looks like this: // <?xml...> // <Name>myname</Name> // <Description>my descr</Description> // <Value>17</Value> // although of course that's not valid XML, since it has no single root element. template <typename T> class PDAL_DLL Option { public: // construct it manually Option(std::string const& name, T value, std::string const& description="") : m_name(name) , m_description(description) , m_value(value) {} // construct it from an xml stream Option(std::istream& istr) { boost::property_tree::ptree t; boost::property_tree::xml_parser::read_xml(istr, t); m_name = t.get<std::string>("Name"); m_value = t.get<T>("Value"); m_description = t.get<std::string>("Description", ""); } // construct it from a ptree Option(const boost::property_tree::ptree t) { m_name = t.get<std::string>("Name"); m_value = t.get<T>("Value"); m_description = t.get<std::string>("Description", ""); } // getters std::string const& getName() const { return m_name; } std::string const& getDescription() const { return m_description; } T const& getValue() const { return m_value; } // return a ptree representation boost::property_tree::ptree getPTree() const { boost::property_tree::ptree t; t.put("Name", getName()); t.put("Description", getDescription()); t.put("Value", getValue()); return t; } // return an xml representation void write_xml(std::ostream& ostr) const { const boost::property_tree::ptree tree = getPTree(); boost::property_tree::xml_parser::write_xml(ostr, tree); return; } private: std::string m_name; std::string m_description; T m_value; }; // An Options object is just a tree of Option objects. // // Dumped as XML, an Options object with two Option objects looks like this: // <?xml...> // <option> // <name>myname</name> // <description>my descr</description> // <value>17</value> // </option> // <option> // <name>myname2</name> // <description>my descr2</description> // <value>13</value> // </option> // although of course that's not valid XML, since it has no single root element. class PDAL_DLL Options { public: // defult ctor, empy options list Options() {} Options(boost::property_tree::ptree t); // read options from an xml stream Options(std::istream& istr); // add an option template<class T> void add(Option<T> const& option) { boost::property_tree::ptree fields = option.getPTree(); m_tree.add_child("Option", fields); } // add an option (shortcut version, bypass need for an Option object) template<class T> void add(const std::string& name, T value, const std::string& description="") { Option<T> opt(name, value, description); add(opt); } // get an option, by name // throws pdal::option_not_found if the option name is not valid template<typename T> Option<T> getOption(std::string const& name) const { boost::property_tree::ptree::const_iterator iter = m_tree.begin(); while (iter != m_tree.end()) { if (iter->first != "Option") throw pdal_error("malformed Options ptree"); const boost::property_tree::ptree& optionTree = iter->second; if (optionTree.get_child("Name").get_value<std::string>() == name) { Option<T> option(optionTree); return option; } ++iter; } throw option_not_found(name); } // returns true iff the option name is valid template<typename T> bool hasOption(std::string const& name) const { bool ok = false; try { Option<T> option = getOption<T>(name); ok = true; } catch (option_not_found&) { ok = false; } // any other exception will bubble up return ok; } // get the ptree for the whole option block const boost::property_tree::ptree& getPTree() const; // the empty options list // BUG: this should be a member variable, not a function, but doing so causes vs2010 to fail to link static const Options& empty(); private: // get the ptree for an option // throws pdal::option_not_found if the option name is not valid const boost::property_tree::ptree getOptionPTree(const std::string& name) const; boost::property_tree::ptree m_tree; }; PDAL_DLL std::ostream& operator<<(std::ostream& ostr, const OptionsOld&); } // namespace pdal #endif <commit_msg>include xml_parser from property_tree<commit_after>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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. ****************************************************************************/ #ifndef INCLUDED_OPTIONS_HPP #define INCLUDED_OPTIONS_HPP #include <pdal/pdal.hpp> #include <pdal/exceptions.hpp> #include <pdal/Bounds.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> namespace pdal { class PDAL_DLL OptionsOld { private: boost::property_tree::ptree m_tree; public: OptionsOld() { m_tree.put("is3d", false); } OptionsOld(boost::property_tree::ptree const& tree) { m_tree = tree; } boost::property_tree::ptree& GetPTree() { return m_tree; } boost::property_tree::ptree const& GetPTree() const { return m_tree; } }; // An Option is just a record with three fields: name, value, and description. // // Dumped as XML, it looks like this: // <?xml...> // <Name>myname</Name> // <Description>my descr</Description> // <Value>17</Value> // although of course that's not valid XML, since it has no single root element. template <typename T> class PDAL_DLL Option { public: // construct it manually Option(std::string const& name, T value, std::string const& description="") : m_name(name) , m_description(description) , m_value(value) {} // construct it from an xml stream Option(std::istream& istr) { boost::property_tree::ptree t; boost::property_tree::xml_parser::read_xml(istr, t); m_name = t.get<std::string>("Name"); m_value = t.get<T>("Value"); m_description = t.get<std::string>("Description", ""); } // construct it from a ptree Option(const boost::property_tree::ptree t) { m_name = t.get<std::string>("Name"); m_value = t.get<T>("Value"); m_description = t.get<std::string>("Description", ""); } // getters std::string const& getName() const { return m_name; } std::string const& getDescription() const { return m_description; } T const& getValue() const { return m_value; } // return a ptree representation boost::property_tree::ptree getPTree() const { boost::property_tree::ptree t; t.put("Name", getName()); t.put("Description", getDescription()); t.put("Value", getValue()); return t; } // return an xml representation void write_xml(std::ostream& ostr) const { const boost::property_tree::ptree tree = getPTree(); boost::property_tree::xml_parser::write_xml(ostr, tree); return; } private: std::string m_name; std::string m_description; T m_value; }; // An Options object is just a tree of Option objects. // // Dumped as XML, an Options object with two Option objects looks like this: // <?xml...> // <option> // <name>myname</name> // <description>my descr</description> // <value>17</value> // </option> // <option> // <name>myname2</name> // <description>my descr2</description> // <value>13</value> // </option> // although of course that's not valid XML, since it has no single root element. class PDAL_DLL Options { public: // defult ctor, empy options list Options() {} Options(boost::property_tree::ptree t); // read options from an xml stream Options(std::istream& istr); // add an option template<class T> void add(Option<T> const& option) { boost::property_tree::ptree fields = option.getPTree(); m_tree.add_child("Option", fields); } // add an option (shortcut version, bypass need for an Option object) template<class T> void add(const std::string& name, T value, const std::string& description="") { Option<T> opt(name, value, description); add(opt); } // get an option, by name // throws pdal::option_not_found if the option name is not valid template<typename T> Option<T> getOption(std::string const& name) const { boost::property_tree::ptree::const_iterator iter = m_tree.begin(); while (iter != m_tree.end()) { if (iter->first != "Option") throw pdal_error("malformed Options ptree"); const boost::property_tree::ptree& optionTree = iter->second; if (optionTree.get_child("Name").get_value<std::string>() == name) { Option<T> option(optionTree); return option; } ++iter; } throw option_not_found(name); } // returns true iff the option name is valid template<typename T> bool hasOption(std::string const& name) const { bool ok = false; try { Option<T> option = getOption<T>(name); ok = true; } catch (option_not_found&) { ok = false; } // any other exception will bubble up return ok; } // get the ptree for the whole option block const boost::property_tree::ptree& getPTree() const; // the empty options list // BUG: this should be a member variable, not a function, but doing so causes vs2010 to fail to link static const Options& empty(); private: // get the ptree for an option // throws pdal::option_not_found if the option name is not valid const boost::property_tree::ptree getOptionPTree(const std::string& name) const; boost::property_tree::ptree m_tree; }; PDAL_DLL std::ostream& operator<<(std::ostream& ostr, const OptionsOld&); } // namespace pdal #endif <|endoftext|>
<commit_before>#include "testing/gtest.hh" #include "viewer/colors/viridis.hh" #include "viewer/primitives/box.hh" #include "viewer/primitives/simple_geometry.hh" #include "viewer/window_3d.hh" #include "viewer/window_manager.hh" #include "geometry/import/read_stl.hh" #include "geometry/spatial/bounding_volume_hierarchy.hh" #include "geometry/spatial/sphere_volume.hh" #include "geometry/spatial/triangle_volume.hh" #include "eigen_helpers.hh" #include "util/heap.hh" #include <map> #include <set> #include <stack> using Vec3 = Eigen::Vector3d; using Vec4 = Eigen::Vector4d; void verify_all_leaves_unique(const geometry::spatial::BoundingVolumeHierarchy &bvh) { std::set<int> already_used; for (const auto &node : bvh.tree()) { if (node.is_leaf) { for (int k = node.leaf.start; k < node.leaf.end; ++k) { EXPECT_EQ(already_used.count(k), 0u); already_used.insert(k); } } } } void draw_children(const geometry::spatial::BoundingVolumeHierarchy &bvh, int base_node_ind) { auto win = gl_viewer::get_window3d("Window A"); auto draw_children_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); Heap<int> stack; stack.push(base_node_ind); while (!stack.empty()) { const int next_index = stack.pop(); const auto &node = bvh.tree()[next_index]; if (node.is_leaf) { for (int k = node.leaf.start; k < node.leaf.end; ++k) { const auto & aabb = bvh.aabb()[k]; gl_viewer::AxisAlignedBox gl_aabb; gl_aabb.lower = aabb.bbox.lower(); gl_aabb.upper = aabb.bbox.upper(); draw_children_geometry->add_box(gl_aabb); } } else { stack.push(node.node.left_child_index); stack.push(node.node.left_child_index + 1); } } win->spin_until_step(); draw_children_geometry->clear(); } void climb_tree(const geometry::spatial::BoundingVolumeHierarchy &bvh) { auto win = gl_viewer::get_window3d("Window A"); auto tree_climb_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); // Explore first branch every time struct ExplorationCandidate { int index; int depth; }; ExplorationCandidate cnd; cnd.index = 0; cnd.depth = 0; Heap<ExplorationCandidate> heap( [](const ExplorationCandidate &a, const ExplorationCandidate &b) { return a.depth < b.depth; }); heap.push(cnd); std::map<int, Eigen::Vector4d> colors; const auto tree = bvh.tree(); while (heap.size()) { const auto next = heap.pop(); const auto &node = tree[next.index]; if (!node.is_leaf) { heap.push({node.node.left_child_index, next.depth + 1}); heap.push({node.node.left_child_index + 1, next.depth + 1}); auto bbox = tree[node.node.left_child_index].bounding_box; bbox.expand(tree[node.node.left_child_index + 1].bounding_box); // if (next.depth != 3) { // continue; // } gl_viewer::AxisAlignedBox aabb; aabb.lower = node.bounding_box.lower(); aabb.upper = node.bounding_box.upper(); if (colors.count(next.depth) == 0) { colors[next.depth] = Eigen::Vector4d::Random(); const double t = next.depth * (1.0 / 10.0); colors[next.depth] = jcc::augment(gl_viewer::colors::viridis(t), 1.0); } aabb.color = colors[next.depth]; tree_climb_geometry->add_box(aabb); draw_children(bvh, next.index); win->spin_until_step(); } } } TEST(BoundingVolumeHierarchyTest, intersection) { auto win = gl_viewer::get_window3d("Window A"); const std::string file_path = "/home/jacob/repos/experiments/data/test_stuff2.stl"; const auto tri = geometry::import::read_stl(file_path); gl_viewer::WindowManager::draw(); auto scene_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); auto visitor_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); std::vector<geometry::spatial::Volume *> tri_ptrs; tri_ptrs.reserve(tri.triangles.size()); std::vector<geometry::spatial::TriangleVolume> triangles; triangles.reserve(tri.triangles.size()); for (size_t k = 0; k < tri.triangles.size(); ++k) { triangles.emplace_back(tri.triangles[k].vertices); tri_ptrs.push_back(&triangles.back()); } for (size_t k = 0; k < tri.triangles.size(); ++k) { scene_geometry->add_line({tri.triangles[k].vertices[0], tri.triangles[k].vertices[1]}); scene_geometry->add_line({tri.triangles[k].vertices[1], tri.triangles[k].vertices[2]}); scene_geometry->add_line({tri.triangles[k].vertices[2], tri.triangles[k].vertices[0]}); } const auto visitor = [&visitor_geometry, &win](const geometry::spatial::BoundingVolumeHierarchy::TreeElement &element, const bool intersected) { gl_viewer::AxisAlignedBox aabb; aabb.lower = element.bounding_box.lower(); aabb.upper = element.bounding_box.upper(); if (element.is_leaf) { aabb.color = Eigen::Vector4d(0.0, 0.0, 1.0, 0.8); } else { aabb.color = Eigen::Vector4d(1.0, 0.0, 0.0, 1.0); } if (intersected) { aabb.color(1) = 1.0; } visitor_geometry->add_box(aabb); win->spin_until_step(); }; geometry::spatial::BoundingVolumeHierarchy bvh; bvh.build(tri_ptrs); { geometry::Ray ray; ray.origin = Vec3(0.0, 0.0, 0.0); ray.direction = Vec3(1.0, 1.0, 1.0).normalized(); scene_geometry->add_ray(ray, 10.0, Vec4(1.0, 0.0, 0.0, 1.0)); const auto intersection = bvh.intersect(ray, visitor); EXPECT_FALSE(intersection.intersected); } { visitor_geometry->clear(); geometry::Ray ray; ray.origin = Vec3(0.0, 0.0, 0.75); ray.direction = Vec3(-1.0, -1.0, 0.0).normalized(); scene_geometry->add_ray(ray, 10.0, Vec4(1.0, 0.0, 0.0, 1.0)); const auto intersection = bvh.intersect(ray, visitor); EXPECT_TRUE(intersection.intersected); constexpr double EPS = 1e-4; EXPECT_NEAR(intersection.distance, 2.80121, EPS); } win->spin_until_step(); visitor_geometry->clear(); } TEST(BoundingVolumeHierarchyTest, bounding_volumes) { /* auto win = gl_viewer::get_window3d("Window A"); const std::string file_path = "/home/jacob/repos/experiments/data/test_stuff2.stl"; const auto tri = geometry::import::read_stl(file_path); gl_viewer::WindowManager::draw(); auto scene_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); auto visitor_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); std::vector<geometry::spatial::Volume *> tri_ptrs; tri_ptrs.reserve(tri.triangles.size()); std::vector<geometry::spatial::TriangleVolume> triangles; triangles.reserve(tri.triangles.size()); for (size_t k = 0; k < tri.triangles.size(); ++k) { triangles.emplace_back(tri.triangles[k].vertices); tri_ptrs.push_back(&triangles.back()); } win->spin_until_step(); { geometry::spatial::BoundingVolumeHierarchy bvh; bvh.build(tri_ptrs); verify_all_leaves_unique(bvh); climb_tree(bvh); } return; std::map<int, Eigen::Vector4d> colors; for (int stop_depth = 0; stop_depth < 10; ++stop_depth) { const auto visitor = [&visitor_geometry, &win, &colors, stop_depth](const geometry::spatial::BoundingBox<3> &box, int depth, bool leaf) { if ((depth != stop_depth) && !leaf) { return; } gl_viewer::AxisAlignedBox aabb; aabb.lower = box.lower(); aabb.upper = box.upper(); if (colors.count(depth) == 0) { colors[depth] = Eigen::Vector4d::Random(); } if (leaf) { aabb.color = Eigen::Vector4d(0.0, 1.0, 0.0, 0.8); } else { aabb.color = colors[depth]; } aabb.color[3] = 0.6; aabb.color[0] = 1.0; visitor_geometry->add_box(aabb); }; geometry::spatial::BoundingVolumeHierarchy bvh; bvh.build(tri_ptrs, visitor); win->spin_until_step(); visitor_geometry->clear(); } */ } <commit_msg>Enable all bvh tests<commit_after>#include "testing/gtest.hh" #include "viewer/colors/viridis.hh" #include "viewer/primitives/box.hh" #include "viewer/primitives/simple_geometry.hh" #include "viewer/window_3d.hh" #include "geometry/import/read_stl.hh" #include "geometry/spatial/bounding_volume_hierarchy.hh" #include "geometry/spatial/sphere_volume.hh" #include "geometry/spatial/triangle_volume.hh" #include "eigen_helpers.hh" #include "util/heap.hh" #include <map> #include <set> #include <stack> using Vec3 = Eigen::Vector3d; using Vec4 = Eigen::Vector4d; void verify_all_leaves_unique(const geometry::spatial::BoundingVolumeHierarchy &bvh) { std::set<int> already_used; for (const auto &node : bvh.tree()) { if (node.is_leaf) { for (int k = node.leaf.start; k < node.leaf.end; ++k) { EXPECT_EQ(already_used.count(k), 0u); already_used.insert(k); } } } } void draw_children(const geometry::spatial::BoundingVolumeHierarchy &bvh, int base_node_ind) { auto win = gl_viewer::get_window3d("Window A"); auto draw_children_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); Heap<int> stack; stack.push(base_node_ind); while (!stack.empty()) { const int next_index = stack.pop(); const auto &node = bvh.tree()[next_index]; if (node.is_leaf) { for (int k = node.leaf.start; k < node.leaf.end; ++k) { const auto &aabb = bvh.aabb()[k]; gl_viewer::AxisAlignedBox gl_aabb; gl_aabb.lower = aabb.bbox.lower(); gl_aabb.upper = aabb.bbox.upper(); draw_children_geometry->add_box(gl_aabb); } } else { stack.push(node.node.left_child_index); stack.push(node.node.left_child_index + 1); } } win->spin_until_step(); draw_children_geometry->clear(); } void climb_tree(const geometry::spatial::BoundingVolumeHierarchy &bvh) { auto win = gl_viewer::get_window3d("Window A"); auto tree_climb_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); // Explore first branch every time struct ExplorationCandidate { int index; int depth; }; ExplorationCandidate cnd; cnd.index = 0; cnd.depth = 0; Heap<ExplorationCandidate> heap( [](const ExplorationCandidate &a, const ExplorationCandidate &b) { return a.depth < b.depth; }); heap.push(cnd); std::map<int, Eigen::Vector4d> colors; const auto tree = bvh.tree(); while (heap.size()) { const auto next = heap.pop(); const auto &node = tree[next.index]; if (!node.is_leaf) { heap.push({node.node.left_child_index, next.depth + 1}); heap.push({node.node.left_child_index + 1, next.depth + 1}); auto bbox = tree[node.node.left_child_index].bounding_box; bbox.expand(tree[node.node.left_child_index + 1].bounding_box); // if (next.depth != 3) { // continue; // } gl_viewer::AxisAlignedBox aabb; aabb.lower = node.bounding_box.lower(); aabb.upper = node.bounding_box.upper(); if (colors.count(next.depth) == 0) { colors[next.depth] = Eigen::Vector4d::Random(); const double t = next.depth * (1.0 / 10.0); colors[next.depth] = jcc::augment(gl_viewer::colors::viridis(t), 1.0); } aabb.color = colors[next.depth]; tree_climb_geometry->add_box(aabb); draw_children(bvh, next.index); win->spin_until_step(); } } } TEST(BoundingVolumeHierarchyTest, intersection) { auto win = gl_viewer::get_window3d("Window A"); const std::string file_path = "/home/jacob/repos/experiments/data/test_stuff2.stl"; const auto tri = geometry::import::read_stl(file_path); auto scene_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); auto visitor_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); std::vector<geometry::spatial::Volume *> tri_ptrs; tri_ptrs.reserve(tri.triangles.size()); std::vector<geometry::spatial::TriangleVolume> triangles; triangles.reserve(tri.triangles.size()); for (size_t k = 0; k < tri.triangles.size(); ++k) { triangles.emplace_back(tri.triangles[k].vertices); tri_ptrs.push_back(&triangles.back()); } for (size_t k = 0; k < tri.triangles.size(); ++k) { scene_geometry->add_line({tri.triangles[k].vertices[0], tri.triangles[k].vertices[1]}); scene_geometry->add_line({tri.triangles[k].vertices[1], tri.triangles[k].vertices[2]}); scene_geometry->add_line({tri.triangles[k].vertices[2], tri.triangles[k].vertices[0]}); } const auto visitor = [&visitor_geometry, &win](const geometry::spatial::BoundingVolumeHierarchy::TreeElement &element, const bool intersected) { gl_viewer::AxisAlignedBox aabb; aabb.lower = element.bounding_box.lower(); aabb.upper = element.bounding_box.upper(); if (element.is_leaf) { aabb.color = Eigen::Vector4d(0.0, 0.0, 1.0, 0.8); } else { aabb.color = Eigen::Vector4d(1.0, 0.0, 0.0, 1.0); } if (intersected) { aabb.color(1) = 1.0; } visitor_geometry->add_box(aabb); win->spin_until_step(); }; geometry::spatial::BoundingVolumeHierarchy bvh; bvh.build(tri_ptrs); { geometry::Ray ray; ray.origin = Vec3(0.0, 0.0, 0.0); ray.direction = Vec3(1.0, 1.0, 1.0).normalized(); scene_geometry->add_ray(ray, 10.0, Vec4(1.0, 0.0, 0.0, 1.0)); const auto intersection = bvh.intersect(ray, visitor); EXPECT_FALSE(intersection.intersected); } { visitor_geometry->clear(); geometry::Ray ray; ray.origin = Vec3(0.0, 0.0, 0.75); ray.direction = Vec3(-1.0, -1.0, 0.0).normalized(); scene_geometry->add_ray(ray, 10.0, Vec4(1.0, 0.0, 0.0, 1.0)); const auto intersection = bvh.intersect(ray, visitor); EXPECT_TRUE(intersection.intersected); constexpr double EPS = 1e-4; EXPECT_NEAR(intersection.distance, 2.80121, EPS); } win->spin_until_step(); visitor_geometry->clear(); } TEST(BoundingVolumeHierarchyTest, bounding_volumes) { auto win = gl_viewer::get_window3d("Window A"); const std::string file_path = "/home/jacob/repos/experiments/data/test_stuff2.stl"; const auto tri = geometry::import::read_stl(file_path); auto scene_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); auto visitor_geometry = win->add_primitive<gl_viewer::SimpleGeometry>(); std::vector<geometry::spatial::Volume *> tri_ptrs; tri_ptrs.reserve(tri.triangles.size()); std::vector<geometry::spatial::TriangleVolume> triangles; triangles.reserve(tri.triangles.size()); for (size_t k = 0; k < tri.triangles.size(); ++k) { triangles.emplace_back(tri.triangles[k].vertices); tri_ptrs.push_back(&triangles.back()); } win->spin_until_step(); { geometry::spatial::BoundingVolumeHierarchy bvh; bvh.build(tri_ptrs); verify_all_leaves_unique(bvh); climb_tree(bvh); } return; std::map<int, Eigen::Vector4d> colors; for (int stop_depth = 0; stop_depth < 10; ++stop_depth) { const auto visitor = [&visitor_geometry, &win, &colors, stop_depth](const geometry::spatial::BoundingBox<3> &box, int depth, bool leaf) { if ((depth != stop_depth) && !leaf) { return; } gl_viewer::AxisAlignedBox aabb; aabb.lower = box.lower(); aabb.upper = box.upper(); if (colors.count(depth) == 0) { colors[depth] = Eigen::Vector4d::Random(); } if (leaf) { aabb.color = Eigen::Vector4d(0.0, 1.0, 0.0, 0.8); } else { aabb.color = colors[depth]; } aabb.color[3] = 0.6; aabb.color[0] = 1.0; visitor_geometry->add_box(aabb); }; geometry::spatial::BoundingVolumeHierarchy bvh; bvh.build(tri_ptrs, visitor); win->spin_until_step(); visitor_geometry->clear(); } win->spin_until_step(); } <|endoftext|>
<commit_before>#include "backenddata.h" #include "debug.h" #include "tasks-tarsnap.h" BackendData::BackendData() { } QMap<QString, JobPtr> BackendData::jobs() { return _jobMap; } QMap<QString, ArchivePtr> BackendData::archives() { return _archiveMap; } quint64 BackendData::numArchives() { return static_cast<quint64>(_archiveMap.count()); } bool BackendData::loadArchives() { _archiveMap.clear(); // Get data from the store. if(!global_store->initialized()) { DEBUG << "PersistentStore was not initialized properly."; return false; } QSqlQuery query = global_store->createQuery(); if(!query.prepare(QLatin1String("select name from archives"))) { DEBUG << query.lastError().text(); return false; } if(!global_store->runQuery(query)) { DEBUG << "loadArchives query failed."; return false; } // Process data from the store. const int index = query.record().indexOf("name"); while(query.next()) { ArchivePtr archive(new Archive); archive->setName(query.value(index).toString()); archive->load(); _archiveMap[archive->name()] = archive; } return true; } QList<ArchivePtr> BackendData::findMatchingArchives(const QString &jobPrefix) { const QString prefix = jobPrefix + QChar('_'); // Get all archives beginning with the relevant prefix who do // not already belong to a job. QList<ArchivePtr> matching; for(const ArchivePtr &archive : _archiveMap) { if(archive->name().startsWith(prefix) && archive->jobRef().isEmpty()) matching << archive; } return matching; } ArchivePtr BackendData::newArchive(BackupTaskDataPtr backupTaskData, bool truncated) { ArchivePtr archive(new Archive); archive->setName(backupTaskData->name()); archive->setCommand(backupTaskData->command()); archive->setJobRef(backupTaskData->jobRef()); // Was the archive creation interrupted? if(truncated) { archive->setName(archive->name().append(".part")); archive->setTruncated(true); } // Lose milliseconds precision by converting to Unix timestamp and back. // So that a subsequent comparison in getArchiveListFinished won't fail. archive->setTimestamp( QDateTime::fromTime_t(backupTaskData->timestamp().toTime_t())); // Save data and add to the map. archive->save(); backupTaskData->setArchive(archive); _archiveMap.insert(archive->name(), archive); // Ensure that the archive is attached to the job (if applicable). for(const JobPtr &job : _jobMap) { if(job->objectKey() == archive->jobRef()) emit job->loadArchives(); } return archive; } QList<ArchivePtr> BackendData::setArchivesFromList(QList<struct archive_list_data> metadatas) { QList<ArchivePtr> newArchives; QMap<QString, ArchivePtr> nextArchiveMap; for(const struct archive_list_data &metadata : metadatas) { ArchivePtr archive = _archiveMap.value(metadata.archiveName, ArchivePtr(new Archive)); if(!archive->objectKey().isEmpty() && (archive->timestamp() != metadata.timestamp)) { // There is a different archive with the same name on the remote archive->purge(); archive.clear(); archive = archive.create(); } if(archive->objectKey().isEmpty()) { // New archive archive->setName(metadata.archiveName); archive->setTimestamp(metadata.timestamp); archive->setCommand(metadata.command); // Automagically set Job ownership for(const JobPtr &job : _jobMap) { if(archive->name().startsWith(job->archivePrefix())) archive->setJobRef(job->objectKey()); } archive->save(); newArchives.append(archive); } nextArchiveMap.insert(archive->name(), archive); _archiveMap.remove(archive->name()); } // Purge archives left in old _archiveMap (not mirrored by the remote) for(const ArchivePtr &archive : _archiveMap) { archive->purge(); } _archiveMap.clear(); _archiveMap = nextArchiveMap; for(const JobPtr &job : _jobMap) { emit job->loadArchives(); } return newArchives; } void BackendData::removeArchives(QList<ArchivePtr> archives) { for(const ArchivePtr &archive : archives) { _archiveMap.remove(archive->name()); archive->purge(); } } bool BackendData::loadJobs() { _jobMap.clear(); // Get data from the store. if(!global_store->initialized()) { DEBUG << "PersistentStore was not initialized properly."; return false; } QSqlQuery query = global_store->createQuery(); if(!query.prepare(QLatin1String("select name from jobs"))) { DEBUG << query.lastError().text(); return false; } if(!global_store->runQuery(query)) { DEBUG << "loadJobs query failed."; return false; } // Process data from the store. const int index = query.record().indexOf("name"); while(query.next()) { JobPtr job(new Job); job->setName(query.value(index).toString()); connect(job.data(), &Job::loadArchives, this, &BackendData::loadJobArchives); job->load(); _jobMap[job->name()] = job; } return true; } void BackendData::deleteJob(JobPtr job) { // Clear JobRef for assigned Archives. for(const ArchivePtr &archive : job->archives()) { archive->setJobRef(""); archive->save(); } job->purge(); _jobMap.remove(job->name()); } void BackendData::loadJobArchives() { Job * job = qobject_cast<Job *>(sender()); QList<ArchivePtr> archives; for(const ArchivePtr &archive : _archiveMap) { if(archive->jobRef() == job->objectKey()) archives << archive; } job->setArchives(archives); } void BackendData::addJob(JobPtr job) { _jobMap[job->name()] = job; connect(job.data(), &Job::loadArchives, this, &BackendData::loadJobArchives); } <commit_msg>BackendData: don't search for an empty jobRef()<commit_after>#include "backenddata.h" #include "debug.h" #include "tasks-tarsnap.h" BackendData::BackendData() { } QMap<QString, JobPtr> BackendData::jobs() { return _jobMap; } QMap<QString, ArchivePtr> BackendData::archives() { return _archiveMap; } quint64 BackendData::numArchives() { return static_cast<quint64>(_archiveMap.count()); } bool BackendData::loadArchives() { _archiveMap.clear(); // Get data from the store. if(!global_store->initialized()) { DEBUG << "PersistentStore was not initialized properly."; return false; } QSqlQuery query = global_store->createQuery(); if(!query.prepare(QLatin1String("select name from archives"))) { DEBUG << query.lastError().text(); return false; } if(!global_store->runQuery(query)) { DEBUG << "loadArchives query failed."; return false; } // Process data from the store. const int index = query.record().indexOf("name"); while(query.next()) { ArchivePtr archive(new Archive); archive->setName(query.value(index).toString()); archive->load(); _archiveMap[archive->name()] = archive; } return true; } QList<ArchivePtr> BackendData::findMatchingArchives(const QString &jobPrefix) { const QString prefix = jobPrefix + QChar('_'); // Get all archives beginning with the relevant prefix who do // not already belong to a job. QList<ArchivePtr> matching; for(const ArchivePtr &archive : _archiveMap) { if(archive->name().startsWith(prefix) && archive->jobRef().isEmpty()) matching << archive; } return matching; } ArchivePtr BackendData::newArchive(BackupTaskDataPtr backupTaskData, bool truncated) { ArchivePtr archive(new Archive); archive->setName(backupTaskData->name()); archive->setCommand(backupTaskData->command()); archive->setJobRef(backupTaskData->jobRef()); // Was the archive creation interrupted? if(truncated) { archive->setName(archive->name().append(".part")); archive->setTruncated(true); } // Lose milliseconds precision by converting to Unix timestamp and back. // So that a subsequent comparison in getArchiveListFinished won't fail. archive->setTimestamp( QDateTime::fromTime_t(backupTaskData->timestamp().toTime_t())); // Save data and add to the map. archive->save(); backupTaskData->setArchive(archive); _archiveMap.insert(archive->name(), archive); // Ensure that the archive is attached to the job (if applicable). if(!archive->jobRef().isEmpty()) { for(const JobPtr &job : _jobMap) { if(job->objectKey() == archive->jobRef()) emit job->loadArchives(); } } return archive; } QList<ArchivePtr> BackendData::setArchivesFromList(QList<struct archive_list_data> metadatas) { QList<ArchivePtr> newArchives; QMap<QString, ArchivePtr> nextArchiveMap; for(const struct archive_list_data &metadata : metadatas) { ArchivePtr archive = _archiveMap.value(metadata.archiveName, ArchivePtr(new Archive)); if(!archive->objectKey().isEmpty() && (archive->timestamp() != metadata.timestamp)) { // There is a different archive with the same name on the remote archive->purge(); archive.clear(); archive = archive.create(); } if(archive->objectKey().isEmpty()) { // New archive archive->setName(metadata.archiveName); archive->setTimestamp(metadata.timestamp); archive->setCommand(metadata.command); // Automagically set Job ownership for(const JobPtr &job : _jobMap) { if(archive->name().startsWith(job->archivePrefix())) archive->setJobRef(job->objectKey()); } archive->save(); newArchives.append(archive); } nextArchiveMap.insert(archive->name(), archive); _archiveMap.remove(archive->name()); } // Purge archives left in old _archiveMap (not mirrored by the remote) for(const ArchivePtr &archive : _archiveMap) { archive->purge(); } _archiveMap.clear(); _archiveMap = nextArchiveMap; for(const JobPtr &job : _jobMap) { emit job->loadArchives(); } return newArchives; } void BackendData::removeArchives(QList<ArchivePtr> archives) { for(const ArchivePtr &archive : archives) { _archiveMap.remove(archive->name()); archive->purge(); } } bool BackendData::loadJobs() { _jobMap.clear(); // Get data from the store. if(!global_store->initialized()) { DEBUG << "PersistentStore was not initialized properly."; return false; } QSqlQuery query = global_store->createQuery(); if(!query.prepare(QLatin1String("select name from jobs"))) { DEBUG << query.lastError().text(); return false; } if(!global_store->runQuery(query)) { DEBUG << "loadJobs query failed."; return false; } // Process data from the store. const int index = query.record().indexOf("name"); while(query.next()) { JobPtr job(new Job); job->setName(query.value(index).toString()); connect(job.data(), &Job::loadArchives, this, &BackendData::loadJobArchives); job->load(); _jobMap[job->name()] = job; } return true; } void BackendData::deleteJob(JobPtr job) { // Clear JobRef for assigned Archives. for(const ArchivePtr &archive : job->archives()) { archive->setJobRef(""); archive->save(); } job->purge(); _jobMap.remove(job->name()); } void BackendData::loadJobArchives() { Job * job = qobject_cast<Job *>(sender()); QList<ArchivePtr> archives; for(const ArchivePtr &archive : _archiveMap) { if(archive->jobRef() == job->objectKey()) archives << archive; } job->setArchives(archives); } void BackendData::addJob(JobPtr job) { _jobMap[job->name()] = job; connect(job.data(), &Job::loadArchives, this, &BackendData::loadJobArchives); } <|endoftext|>
<commit_before>/* * Copyright 2016 Luca Zanconato * * 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 <gtest/gtest.h> #include <fstream> #include <saltpack.h> #include <sodium.h> TEST(signature, attached) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, true); out.flush(); delete sig; // verify message std::stringstream in(out.str()); std::stringstream msg; saltpack::MessageReader *dec = new saltpack::MessageReader(in); while (dec->hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec->getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; ASSERT_EQ(msg.str(), "a signed message"); } TEST(signature, attached_failure) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, true); out.flush(); delete sig; try { // verify message std::string mmsg = out.str(); mmsg[mmsg.size() - 80] = (char)((int)mmsg[mmsg.size() - 80] + 1); std::stringstream in(mmsg); std::stringstream msg; saltpack::MessageReader dec(in); while (dec.hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec.getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature was forged or corrupt."); } } TEST(signature, attached_armor) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_ATTACHED_SIGNATURE); saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' '}, false); sig->addBlock({'m', 'e', 's', 's', 'a', 'g', 'e'}, true); aOut.finalise(); out.flush(); delete sig; // verify message std::stringstream in(out.str()); saltpack::ArmoredInputStream is(in); std::stringstream msg; saltpack::MessageReader *dec = new saltpack::MessageReader(is); while (dec->hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec->getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; ASSERT_EQ(msg.str(), "a signed message"); } TEST(signature, detached) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm'}, false); sig->addBlock({'E', '$', 's', '4', 'g', '['}, true); out.flush(); delete sig; // verify message std::stringstream in(out.str()); std::stringstream msg("Th3 mE$s4g["); saltpack::MessageReader *dec = new saltpack::MessageReader(in, msg); ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; try { std::stringstream in2(out.str()); std::stringstream msg2("Wrong"); saltpack::MessageReader(in2, msg2); throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature was forged or corrupt."); } } TEST(signature, detached_armor) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_DETACHED_SIGNATURE); saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm', 'E', '$', 's', '4', 'g', '!'}, true); aOut.finalise(); out.flush(); delete sig; // verify message std::stringstream in(out.str()); std::stringstream msg("Th3 mE$s4g!"); saltpack::ArmoredInputStream is(in); saltpack::MessageReader *dec = new saltpack::MessageReader(is, msg); ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; try { std::stringstream in2(out.str()); saltpack::ArmoredInputStream is2(in2); std::stringstream msg2("Wrong"); saltpack::MessageReader(is2, msg2); throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature was forged or corrupt."); } } TEST(signature, attached_message_truncated) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, false); out.flush(); delete sig; try { // verify message std::stringstream in(out.str()); std::stringstream msg; saltpack::MessageReader dec(in); while (dec.hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec.getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Not enough data found to decode block (message truncated?)."); } } TEST(signature, detached_message_truncated) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm'}, false); sig->addBlock({'E', '$', 's', '4', 'g', '['}, false); out.flush(); delete sig; try { // verify message std::stringstream in(out.str()); std::stringstream msg("Th3 mE$s4g["); saltpack::MessageReader *dec = new saltpack::MessageReader(in, msg); ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature not found."); } } TEST(signature, attached_final_block) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); try { // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, true); sig->addBlock({' ', 'v', '2'}, true); out.flush(); delete sig; } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Final block already added."); } } TEST(signature, detached_final_block) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); try { // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm', 'E', '$', 's', '4', 'g', '!'}, true); sig->addBlock({'?'}, true); out.flush(); delete sig; } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Final block already added."); } } <commit_msg>Added tests for V1 compatibility<commit_after>/* * Copyright 2016-2017 Luca Zanconato * * 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 <gtest/gtest.h> #include <fstream> #include <saltpack.h> #include <sodium.h> TEST(signature, attached) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, true); out.flush(); delete sig; // verify message std::stringstream in(out.str()); std::stringstream msg; saltpack::MessageReader *dec = new saltpack::MessageReader(in); while (dec->hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec->getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; ASSERT_EQ(msg.str(), "a signed message"); } TEST(signature, attached_failure) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, true); out.flush(); delete sig; try { // verify message std::string mmsg = out.str(); mmsg[mmsg.size() - 80] = (char)((int)mmsg[mmsg.size() - 80] + 1); std::stringstream in(mmsg); std::stringstream msg; saltpack::MessageReader dec(in); while (dec.hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec.getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature was forged or corrupt."); } } TEST(signature, attached_armor) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_ATTACHED_SIGNATURE); saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' '}, false); sig->addBlock({'m', 'e', 's', 's', 'a', 'g', 'e'}, true); aOut.finalise(); out.flush(); delete sig; // verify message std::stringstream in(out.str()); saltpack::ArmoredInputStream is(in); std::stringstream msg; saltpack::MessageReader *dec = new saltpack::MessageReader(is); while (dec->hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec->getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; ASSERT_EQ(msg.str(), "a signed message"); } TEST(signature, detached) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm'}, false); sig->addBlock({'E', '$', 's', '4', 'g', '['}, true); out.flush(); delete sig; // verify message std::stringstream in(out.str()); std::stringstream msg("Th3 mE$s4g["); saltpack::MessageReader *dec = new saltpack::MessageReader(in, msg); ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; try { std::stringstream in2(out.str()); std::stringstream msg2("Wrong"); saltpack::MessageReader(in2, msg2); throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature was forged or corrupt."); } } TEST(signature, detached_armor) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::ArmoredOutputStream aOut(out, saltpack::MODE_DETACHED_SIGNATURE); saltpack::MessageWriter *sig = new saltpack::MessageWriter(aOut, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm', 'E', '$', 's', '4', 'g', '!'}, true); aOut.finalise(); out.flush(); delete sig; // verify message std::stringstream in(out.str()); std::stringstream msg("Th3 mE$s4g!"); saltpack::ArmoredInputStream is(in); saltpack::MessageReader *dec = new saltpack::MessageReader(is, msg); ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; try { std::stringstream in2(out.str()); saltpack::ArmoredInputStream is2(in2); std::stringstream msg2("Wrong"); saltpack::MessageReader(is2, msg2); throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature was forged or corrupt."); } } TEST(signature, attached_message_truncated) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, false); out.flush(); delete sig; try { // verify message std::stringstream in(out.str()); std::stringstream msg; saltpack::MessageReader dec(in); while (dec.hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec.getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Not enough data found to decode block (message truncated?)."); } } TEST(signature, detached_message_truncated) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm'}, false); sig->addBlock({'E', '$', 's', '4', 'g', '['}, false); out.flush(); delete sig; try { // verify message std::stringstream in(out.str()); std::stringstream msg("Th3 mE$s4g["); saltpack::MessageReader *dec = new saltpack::MessageReader(in, msg); ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; throw std::bad_exception(); } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Signature not found."); } } TEST(signature, attached_final_block) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); try { // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, false); sig->addBlock({'a', ' ', 's', 'i', 'g', 'n', 'e', 'd', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e'}, true); sig->addBlock({' ', 'v', '2'}, true); out.flush(); delete sig; } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Final block already added."); } } TEST(signature, detached_final_block) { saltpack::BYTE_ARRAY signer_secretkey(crypto_sign_SECRETKEYBYTES); saltpack::BYTE_ARRAY signer_publickey(crypto_sign_PUBLICKEYBYTES); saltpack::Utils::generateSignKeypair(signer_publickey, signer_secretkey); try { // sign message std::stringstream out; saltpack::MessageWriter *sig = new saltpack::MessageWriter(out, signer_secretkey, true); sig->addBlock({'T', 'h', '3', ' ', 'm', 'E', '$', 's', '4', 'g', '!'}, true); sig->addBlock({'?'}, true); out.flush(); delete sig; } catch (const saltpack::SaltpackException ex) { ASSERT_STREQ(ex.what(), "Final block already added."); } } TEST(signature, attached_version_one) { saltpack::BYTE_ARRAY signer_secretkey({245, 6, 38, 38, 136, 83, 114, 248, 171, 127, 74, 11, 45, 29, 126, 213, 7, 236, 174, 197, 99, 201, 193, 207, 16, 91, 166, 133, 141, 50, 144, 211, 199, 45, 196, 24, 141, 60, 173, 36, 11, 156, 148, 221, 212, 160, 252, 133, 136, 160, 73, 11, 23, 129, 243, 218, 57, 180, 252, 17, 133, 46, 244, 139}); saltpack::BYTE_ARRAY signer_publickey({199, 45, 196, 24, 141, 60, 173, 36, 11, 156, 148, 221, 212, 160, 252, 133, 136, 160, 73, 11, 23, 129, 243, 218, 57, 180, 252, 17, 133, 46, 244, 139}); std::string ciphertext = "BEGIN SALTPACK SIGNED MESSAGE. kYM5h1pg6qz9UMn j6G7KB2OUmwXTFd 8hHAxRyMXKWKOxs " "bECTM8qEn3zYPTA s94LWmdVgpRAw9I fxsGWxHAkkzEaL1 PfDAsXLp9Zq5ymY 5dySiZQZ5uC3IKy 9VGvkwoHiY8tLW1 " "iF5oHeppoqzIN0N 6ySAuKEqldHH8TL j4z3Q4x5C7Rp1lt 7uQljohrfLUO7qx 5EbIJbUQqM22Geh VFAaePwM5YjWGEg " "k2um83NphtgtIZQ fW0Aivnts1DYmJ7 bZHBN0yidHwJ2FY 5kmC0vApVJrJfni PwhFaGfjlMnghwS Y5G2v0olHriQMTV " "rEEy. END SALTPACK SIGNED MESSAGE."; // verify message std::stringstream in(ciphertext); saltpack::ArmoredInputStream is(in); std::stringstream msg; saltpack::MessageReader *dec = new saltpack::MessageReader(is); while (dec->hasMoreBlocks()) { saltpack::BYTE_ARRAY message = dec->getBlock(); msg.write(reinterpret_cast<const char *>(message.data()), message.size()); } ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; ASSERT_EQ(msg.str(), "Signed message\n"); } TEST(signature, detached_version_one) { saltpack::BYTE_ARRAY signer_secretkey({245, 6, 38, 38, 136, 83, 114, 248, 171, 127, 74, 11, 45, 29, 126, 213, 7, 236, 174, 197, 99, 201, 193, 207, 16, 91, 166, 133, 141, 50, 144, 211, 199, 45, 196, 24, 141, 60, 173, 36, 11, 156, 148, 221, 212, 160, 252, 133, 136, 160, 73, 11, 23, 129, 243, 218, 57, 180, 252, 17, 133, 46, 244, 139}); saltpack::BYTE_ARRAY signer_publickey({199, 45, 196, 24, 141, 60, 173, 36, 11, 156, 148, 221, 212, 160, 252, 133, 136, 160, 73, 11, 23, 129, 243, 218, 57, 180, 252, 17, 133, 46, 244, 139}); std::string ciphertext = "BEGIN SALTPACK DETACHED SIGNATURE. kYM5h1pg6qz9UMn j6G7KBABYp9npL6 oT1KkalFeaDwWxs " "bECTM8qEn3zYPTA s94LWmdVgpbwCki T35ZsJvycdnnkp5 xjaos54GAI71l9u lGzcrkDkh1iVWXY j8FY4EefSR9qMdi " "p8bqfMDseqX84Y2 5dtmyvwTiGQKs1O B40DzEV9VHZbchf PVh04NGL8rZHdQf 1wzeX5z. END SALTPACK DETACHED SIGNATURE."; // verify message std::stringstream in(ciphertext); std::stringstream msg("Signed message 2\n"); saltpack::ArmoredInputStream is(in); saltpack::MessageReader *dec = new saltpack::MessageReader(is, msg); ASSERT_EQ(signer_publickey, dec->getSender()); delete dec; } <|endoftext|>
<commit_before>#ifndef RESOURCE_MANAGER_HPP #define RESOURCE_MANAGER_HPP #include <iostream> #include <SDL2/SDL.h> #include <string> #include <map> #include <iostream> #include <SDL2/SDL_image.h> #ifdef __EMSCRIPTEN__ #include <SDL/SDL_mixer.h> #else #include <SDL2/SDL_mixer.h> #endif class ResourceManager { public: /***/ ~ResourceManager() { for(auto e : m_textures) { SDL_DestroyTexture(e.second); } for(auto e : m_sounds) { Mix_FreeChunk(e.second); } } /***/ bool load_surface(const std::string &key, const std::string &path, SDL_Renderer *ren) { SDL_Texture *texture; texture = IMG_LoadTexture(ren, path.c_str()); if (!texture) { std::cerr << "IMG_Load:" << IMG_GetError() << std::endl; return false; } m_textures[key] = texture; return true; } /***/ bool load_sound(std::string key, std::string &path) { Mix_Chunk *new_sound = Mix_LoadWAV(path.c_str()); if (new_sound == NULL) { std::cerr << "Error: could not load sound from" << path << std::endl; return false; } m_sounds[key] = new_sound; return true; } /***/ bool load_music(std::string key, std::string &path) { Mix_Music *new_music = Mix_LoadMUS(path.c_str()); if (new_music == NULL) { std::cerr << "Error: could not load sound from " << path << ": "<< Mix_GetError() << std::endl; return false; } m_music[key] = new_music; return true; } /***/ SDL_Texture* get_texture(std::string texture_key) { return m_textures.at(texture_key); } /***/ Mix_Chunk* get_sound(std::string sound_key) { return m_sounds.at(sound_key); } /***/ Mix_Music* get_music(std::string music_key) { return m_music.at(music_key); } private: std::map<std::string, SDL_Texture*> m_textures; std::map<std::string, Mix_Chunk*> m_sounds; std::map<std::string, Mix_Music*> m_music; }; #endif <commit_msg>ResourceManager: Rename load_surface to load_texture<commit_after>#ifndef RESOURCE_MANAGER_HPP #define RESOURCE_MANAGER_HPP #include <iostream> #include <SDL2/SDL.h> #include <string> #include <map> #include <iostream> #include <SDL2/SDL_image.h> #ifdef __EMSCRIPTEN__ #include <SDL/SDL_mixer.h> #else #include <SDL2/SDL_mixer.h> #endif class ResourceManager { public: /***/ ~ResourceManager() { for(auto e : m_textures) { SDL_DestroyTexture(e.second); } for(auto e : m_sounds) { Mix_FreeChunk(e.second); } } /***/ bool load_texture(const std::string &key, const std::string &path, SDL_Renderer *ren) { SDL_Texture *texture; texture = IMG_LoadTexture(ren, path.c_str()); if (!texture) { std::cerr << "IMG_Load:" << IMG_GetError() << std::endl; return false; } m_textures[key] = texture; return true; } /***/ bool load_sound(std::string key, std::string &path) { Mix_Chunk *new_sound = Mix_LoadWAV(path.c_str()); if (new_sound == NULL) { std::cerr << "Error: could not load sound from" << path << std::endl; return false; } m_sounds[key] = new_sound; return true; } /***/ bool load_music(std::string key, std::string &path) { Mix_Music *new_music = Mix_LoadMUS(path.c_str()); if (new_music == NULL) { std::cerr << "Error: could not load sound from " << path << ": "<< Mix_GetError() << std::endl; return false; } m_music[key] = new_music; return true; } /***/ SDL_Texture* get_texture(std::string texture_key) { return m_textures.at(texture_key); } /***/ Mix_Chunk* get_sound(std::string sound_key) { return m_sounds.at(sound_key); } /***/ Mix_Music* get_music(std::string music_key) { return m_music.at(music_key); } private: std::map<std::string, SDL_Texture*> m_textures; std::map<std::string, Mix_Chunk*> m_sounds; std::map<std::string, Mix_Music*> m_music; }; #endif <|endoftext|>
<commit_before>#ifndef RECURSE_HPP #define RECURSE_HPP #include <QCoreApplication> #include <QObject> #include <QTcpServer> #include <QTcpSocket> #include <QHostAddress> #include <QHash> #include <QStringBuilder> #include <QVector> #include "request.hpp" #include "response.hpp" #include <functional> using std::function; using std::bind; using std::ref; typedef function<void(Request &request, Response &response, function<void()> next)> next_f; //! //! \brief The Recurse class //! main class of the app //! class Recurse : public QObject { public: Recurse(int & argc, char ** argv, QObject *parent = NULL); ~Recurse(); bool listen(quint64 port, QHostAddress address = QHostAddress::Any); void use(next_f next); private: QCoreApplication app; QTcpServer m_tcp_server; quint64 m_port; QVector<next_f> m_middleware; int current_middleware = 0; void m_next(Request &request, Response &response); void http_parse(Request &request); QString http_build_header(const Response &response); }; Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv) { Q_UNUSED(parent); }; Recurse::~Recurse() { }; //! //! \brief Recurse::listen //! listen for tcp requests //! //! \param port tcp server port //! \param address tcp server listening address //! //! \return true on success //! bool Recurse::listen(quint64 port, QHostAddress address) { m_port = port; int bound = m_tcp_server.listen(address, port); if (!bound) return false; connect(&m_tcp_server, &QTcpServer::newConnection, [this] { qDebug() << "client connected"; QTcpSocket *client = m_tcp_server.nextPendingConnection(); connect(client, &QTcpSocket::readyRead, [this, client] { Request request; Response response; request.data = client->readAll(); http_parse(request); qDebug() << "client request: " << request.data; if (m_middleware.count() > 0) m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response))); current_middleware = 0; QString header; response.method = request.method; response.proto = request.proto; if (response.status == 0) response.status = 200; header = http_build_header(response); QString response_data = header + response.body; // send response to the client qint64 check = client->write(response_data.toStdString().c_str(), response_data.size()); qDebug() << "socket write debug:" << check; client->close(); }); }); return app.exec(); }; //! //! \brief Recurse::m_next //! call next middleware //! void Recurse::m_next(Request &request, Response &response) { qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size(); if (++current_middleware >= m_middleware.size()) { return; }; m_middleware[current_middleware](request, response, bind(&Recurse::m_next, this, ref(request), ref(response))); }; //! //! \brief Recurse::use //! add new middleware //! //! \param f middleware function that will be called later //! void Recurse::use(next_f f) { m_middleware.push_back(f); }; //! //! \brief Recurse::http_parse //! parse http data //! //! \param data reference to data received from the tcp connection //! void Recurse::http_parse(Request &request) { QStringList data_list = request.data.split("\r\n"); bool is_body = false; for (int i = 0; i < data_list.size(); ++i) { if (is_body) { request.body.append(data_list.at(i)); continue; } QStringList entity_item = data_list.at(i).split(":"); if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) { is_body = true; continue; } else if (i == 0 && entity_item.length() < 2) { QStringList first_line = entity_item.at(0).split(" "); request.method = first_line.at(0); request.url = first_line.at(1).trimmed(); request.proto = first_line.at(2).trimmed(); continue; } request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed(); } qDebug() << "request object populated: " << request.method << request.url << request.header << request.proto << request.body; }; //! //! \brief Recurse::http_build_header //! build http header for response //! //! \param response reference to the Response instance //! QString Recurse::http_build_header(const Response &response) { QString header = response.proto % " " % QString::number(response.status) % " " % response.http_codes[response.status] % "\r\n"; // set default header fields QHash<QString, QString>::const_iterator i; for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) { if (i.key() == "content-length" && response.header[i.key()] == "") header += i.key() % ": " % QString::number(response.body.size()) % "\r\n"; else if (response.header[i.key()] == "") header += i.key() % ": " % i.value() % "\r\n"; } // set user-defined header fields QHash<QString, QString>::const_iterator j; for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) { header += j.key() % ": " % j.value() % "\r\n"; } qDebug() << "response header" << header; return header + "\r\n"; } #endif // RECURSE_HPP <commit_msg>store connections in a QHash which gets instantiated with an application<commit_after>#ifndef RECURSE_HPP #define RECURSE_HPP #include <QCoreApplication> #include <QObject> #include <QTcpServer> #include <QTcpSocket> #include <QHostAddress> #include <QHash> #include <QStringBuilder> #include <QVector> #include "request.hpp" #include "response.hpp" #include <functional> using std::function; using std::bind; using std::ref; typedef function<void(Request &request, Response &response, function<void()> next)> next_f; //! //! \brief The Recurse class //! main class of the app //! class Recurse : public QObject { public: Recurse(int & argc, char ** argv, QObject *parent = NULL); ~Recurse(); bool listen(quint64 port, QHostAddress address = QHostAddress::Any); void use(next_f next); private: QCoreApplication app; QTcpServer m_tcp_server; quint64 m_port; QVector<next_f> m_middleware; int current_middleware = 0; void m_next(int &socket_id); void http_parse(Request &request); QString http_build_header(const Response &response); struct Client { QTcpSocket *socket; Request request; Response response; }; QHash<int, Client> connections; }; Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv) { Q_UNUSED(parent); }; Recurse::~Recurse() { }; //! //! \brief Recurse::listen //! listen for tcp requests //! //! \param port tcp server port //! \param address tcp server listening address //! //! \return true on success //! bool Recurse::listen(quint64 port, QHostAddress address) { m_port = port; int bound = m_tcp_server.listen(address, port); if (!bound) return false; connect(&m_tcp_server, &QTcpServer::newConnection, [this] { qDebug() << "client connected"; int socket_id = rand(); connections[socket_id] = { m_tcp_server.nextPendingConnection() }; connect(connections[socket_id].socket, &QTcpSocket::readyRead, [this, socket_id] { connections[socket_id].request.data = connections[socket_id].socket->readAll(); http_parse(connections[socket_id].request); qDebug() << "client request: " << connections[socket_id].request.data; if (m_middleware.count() > 0) m_middleware[current_middleware]( connections[socket_id].request, connections[socket_id].response, bind(&Recurse::m_next, this, socket_id)); current_middleware = 0; QString header; connections[socket_id].response.method = connections[socket_id].request.method; connections[socket_id].response.proto = connections[socket_id].request.proto; if (connections[socket_id].response.status == 0) connections[socket_id].response.status = 200; header = http_build_header(connections[socket_id].response); QString response_data = header + connections[socket_id].response.body; // send response to the client qint64 check = connections[socket_id].socket->write( response_data.toStdString().c_str(), response_data.size()); qDebug() << "socket write debug:" << check; connections[socket_id].socket->close(); }); }); return app.exec(); }; //! //! \brief Recurse::m_next //! call next middleware //! void Recurse::m_next(int &socket_id) { qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size(); if (++current_middleware >= m_middleware.size()) { return; }; m_middleware[current_middleware]( connections[socket_id].request, connections[socket_id].response, bind(&Recurse::m_next, this, socket_id)); }; //! //! \brief Recurse::use //! add new middleware //! //! \param f middleware function that will be called later //! void Recurse::use(next_f f) { m_middleware.push_back(f); }; //! //! \brief Recurse::http_parse //! parse http data //! //! \param data reference to data received from the tcp connection //! void Recurse::http_parse(Request &request) { QStringList data_list = request.data.split("\r\n"); bool is_body = false; for (int i = 0; i < data_list.size(); ++i) { if (is_body) { request.body.append(data_list.at(i)); continue; } QStringList entity_item = data_list.at(i).split(":"); if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) { is_body = true; continue; } else if (i == 0 && entity_item.length() < 2) { QStringList first_line = entity_item.at(0).split(" "); request.method = first_line.at(0); request.url = first_line.at(1).trimmed(); request.proto = first_line.at(2).trimmed(); continue; } request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed(); } qDebug() << "request object populated: " << request.method << request.url << request.header << request.proto << request.body; }; //! //! \brief Recurse::http_build_header //! build http header for response //! //! \param response reference to the Response instance //! QString Recurse::http_build_header(const Response &response) { QString header = response.proto % " " % QString::number(response.status) % " " % response.http_codes[response.status] % "\r\n"; // set default header fields QHash<QString, QString>::const_iterator i; for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) { if (i.key() == "content-length" && response.header[i.key()] == "") header += i.key() % ": " % QString::number(response.body.size()) % "\r\n"; else if (response.header[i.key()] == "") header += i.key() % ": " % i.value() % "\r\n"; } // set user-defined header fields QHash<QString, QString>::const_iterator j; for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) { header += j.key() % ": " % j.value() % "\r\n"; } qDebug() << "response header" << header; return header + "\r\n"; } #endif // RECURSE_HPP <|endoftext|>
<commit_before>/* Filename: intelhex.cc * Routines for reading/writing Intel INHX8M and INHX32 files * Copyright Brandon Fosdick 2001 * This software and all of its components are available under the BSD License * For a copy of the BSD License see http://www.freebsd.org * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "intelhex.h" namespace intelhex { hex_data::hex_data() { format = HEX_FORMAT_INHX8M; } //Extend the data block array by one element // and return a pointer to the new element dblock* hex_data::new_block() { dblock b; blocks.push_back(b); return &blocks.back(); } //Extend the data block array by one element // and return a pointer to the new element // Initialize the element with address and length dblock* hex_data::add_block(uint16_t address, uint16_t length) { dblock db; //A list of pointers would be faster, but this isn't too bad blocks.push_back(db); blocks.back().first = address; blocks.back().second.resize(length); return &blocks.back(); } //Array access operator //Assumes that the blocks have been sorted by address in ascending order uint16_t &hex_data::operator[](uint16_t addr) { //Start at the end of the list and find the first (last) block with an address // less than addr lst_dblock::reverse_iterator i = blocks.rbegin(); while( (i!=blocks.rend()) && (i->first > addr)) ++i; if(i==blocks.rend()) //If a suitable block wasn't found, return something return blocks.begin()->second[0]; return i->second[addr - i->first]; } // Delete all allocated memory void hex_data::cleanup() { format = HEX_FORMAT_INHX8M; blocks.clear(); } //Load a hex file from disk //Destroys any data that has already been loaded bool hex_data::load(const char *path) { FILE *fp; unsigned int hi, lo, address, count, rtype, i, j; dblock *db; //Temporary pointer if( (fp=fopen(path, "r"))==NULL ) { printf("%s: Can't open %s\n", __FUNCTION__, path); return false; } cleanup(); //First, clean house //Start parsing the file while(!feof(fp)) { if(fgetc(fp)==':') //First character of every line should be ':' { fscanf(fp, "%2x", &count); //Read in byte count fscanf(fp, "%4x", &address); //Read in address fscanf(fp, "%2x", &rtype); //Read type /* printf("Count: %02X\t", count); printf("Address: %04X\t", address); printf("Type: %02X\n", rtype); */ count /= 2; //Convert byte count to word count address /= 2; //Byte address to word address switch(rtype) //What type of record? { case 0: //Data block so store it db = add_block(address, count); //Make a data block for(i=0; i<count; i++) //Read all of the data bytes { fscanf(fp, "%2x", &lo); //Low byte fscanf(fp, "%2x", &hi); //High byte db->second[i] = ((hi<<8)&0xFF00) | (lo&0x00FF); //Assemble the word } break; case 1: //EOF break; case 2: //Segment address record (INHX32) break; case 4: //Linear address record (INHX32) break; } fscanf(fp,"%*[^\n]\n"); //Ignore the checksum and the newline } else { printf("%s: Bad line\n", __FUNCTION__); fscanf(fp, "%*[^\n]\n"); //Ignore the rest of the line } } fclose(fp); blocks.sort(); //Sort the data blocks by address (ascending) return true; } //Write all data to a file void hex_data::write(const char *path) { FILE *fp; // int i, j; u_int8_t checksum; if( (fp=fopen(path, "w"))==NULL ) { printf("%s: Can't open %s\n", __FUNCTION__, path); return; } truncate(8); //Truncate each record to length=8 blocks.sort(); //Sort the data blocks by address (ascending) for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++) { checksum = 0; if(i->first < 0x2100) { //Program memory and fuses require special consideration fprintf(fp, ":%02X%04X00", i->second.size()*2, i->first*2); //Record length and address for(int j=0; j<i->second.size(); j++) //Store the data bytes, LSB first, ASCII HEX { fprintf(fp, "%02X%02X", i->second[j] & 0x00FF, (i->second[j]>>8) & 0x00FF); checksum += i->second[j]; } } else //EEPROM can just be written out { fprintf(fp, ":%02X%04X00", i->second.size(), i->first); //Record length and address for(int j=0; j<i->second.size(); j++) //Store the data bytes, LSB first, ASCII HEX { fprintf(fp, "%02X", i->second[j] & 0x00FF); checksum += i->second[j]; } } fprintf(fp, "00\n"); //Bogus checksum and a newline } fprintf(fp, ":00000001FF\n"); //EOF marker fclose(fp); } //Truncate all of the blocks to a given length void hex_data::truncate(uint16_t len) { for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++) if(i->second.size() > len) { dblock db; blocks.push_back(db); //Append a new block blocks.back().first = i->first + len; //Give the new block an address blocks.back().second.assign(&i->second[len], i->second.end()); //Insert the extra bytes into the new block i->second.resize(len); //Truncate the original block } } }<commit_msg>Added write(ostream&) for outputting to a string<commit_after>/* Filename: intelhex.cc * Routines for reading/writing Intel INHX8M and INHX32 files * Copyright Brandon Fosdick 2001 * This software and all of its components are available under the BSD License * For a copy of the BSD License see http://www.freebsd.org * */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "intelhex.h" namespace intelhex { hex_data::hex_data() { format = HEX_FORMAT_INHX8M; } //Extend the data block array by one element // and return a pointer to the new element dblock* hex_data::new_block() { dblock b; blocks.push_back(b); return &blocks.back(); } //Extend the data block array by one element // and return a pointer to the new element // Initialize the element with address and length dblock* hex_data::add_block(uint16_t address, uint16_t length) { dblock db; //A list of pointers would be faster, but this isn't too bad blocks.push_back(db); blocks.back().first = address; blocks.back().second.resize(length); return &blocks.back(); } //Array access operator //Assumes that the blocks have been sorted by address in ascending order uint16_t &hex_data::operator[](uint16_t addr) { //Start at the end of the list and find the first (last) block with an address // less than addr lst_dblock::reverse_iterator i = blocks.rbegin(); while( (i!=blocks.rend()) && (i->first > addr)) ++i; if(i==blocks.rend()) //If a suitable block wasn't found, return something return blocks.begin()->second[0]; return i->second[addr - i->first]; } // Delete all allocated memory void hex_data::cleanup() { format = HEX_FORMAT_INHX8M; blocks.clear(); } //Load a hex file from disk //Destroys any data that has already been loaded bool hex_data::load(const char *path) { FILE *fp; unsigned int hi, lo, address, count, rtype, i, j; dblock *db; //Temporary pointer if( (fp=fopen(path, "r"))==NULL ) { printf("%s: Can't open %s\n", __FUNCTION__, path); return false; } cleanup(); //First, clean house //Start parsing the file while(!feof(fp)) { if(fgetc(fp)==':') //First character of every line should be ':' { fscanf(fp, "%2x", &count); //Read in byte count fscanf(fp, "%4x", &address); //Read in address fscanf(fp, "%2x", &rtype); //Read type /* printf("Count: %02X\t", count); printf("Address: %04X\t", address); printf("Type: %02X\n", rtype); */ count /= 2; //Convert byte count to word count address /= 2; //Byte address to word address switch(rtype) //What type of record? { case 0: //Data block so store it db = add_block(address, count); //Make a data block for(i=0; i<count; i++) //Read all of the data bytes { fscanf(fp, "%2x", &lo); //Low byte fscanf(fp, "%2x", &hi); //High byte db->second[i] = ((hi<<8)&0xFF00) | (lo&0x00FF); //Assemble the word } break; case 1: //EOF break; case 2: //Segment address record (INHX32) break; case 4: //Linear address record (INHX32) break; } fscanf(fp,"%*[^\n]\n"); //Ignore the checksum and the newline } else { printf("%s: Bad line\n", __FUNCTION__); fscanf(fp, "%*[^\n]\n"); //Ignore the rest of the line } } fclose(fp); blocks.sort(); //Sort the data blocks by address (ascending) return true; } //Write all data to a file void hex_data::write(const char *path) { ofstream ofs(path); write(ofs); } //Write all data to an output stream void hex_data::write(ostream &os) { uint8_t checksum; truncate(8); //Truncate each record to length=8 (purely asthetic) blocks.sort(); //Sort the data blocks by address (ascending) os.setf(ios::hex, ios::basefield); //Set the stream to ouput hex instead of decimal os.setf(ios::uppercase); //Use uppercase hex notation os.fill('0'); //Pad with zeroes for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++) { checksum = 0; if(i->first < 0x2100) { //Program memory and fuses require special consideration os << ':'; //Every line begins with ':' os.width(2); os << i->second.size()*2; //Record length os.width(4); os << static_cast<uint16_t>(i->first*2); //Address os << "00"; //Record type for(int j=0; j<i->second.size(); j++) //Store the data bytes, LSB first, ASCII HEX { os.width(2); os << (i->second[j] & 0x00FF); os.width(2); os << ((i->second[j]>>8) & 0x00FF); checksum += i->second[j]; } } else //EEPROM can just be written out { os.width(2); os << i->second.size(); //Record length os.width(4); os << i->first << "00"; //Address and record type for(int j=0; j<i->second.size(); j++) //Store the data bytes, LSB first, ASCII HEX { os.width(2); os << (i->second[j] & 0x00FF); checksum += i->second[j]; } } os.width(2); os << static_cast<int>(checksum); //Bogus checksum byte os << endl; } os << ":00000001FF\n"; //EOF marker } //Truncate all of the blocks to a given length void hex_data::truncate(uint16_t len) { for(lst_dblock::iterator i=blocks.begin(); i!=blocks.end(); i++) if(i->second.size() > len) { dblock db; blocks.push_back(db); //Append a new block blocks.back().first = i->first + len; //Give the new block an address blocks.back().second.assign(&i->second[len], i->second.end()); //Insert the extra bytes into the new block i->second.resize(len); //Truncate the original block } } }<|endoftext|>
<commit_before>#ifndef V_SMC_SAMPLER_HPP #define V_SMC_SAMPLER_HPP #include <map> #include <stdexcept> #include <string> #include <vector> #include <gsl/gsl_cblas.h> #include <boost/function.hpp> #include <vDist/rng/gsl.hpp> #include <vDist/tool/buffer.hpp> #include <vSMC/history.hpp> #include <vSMC/monitor.hpp> #include <vSMC/particle.hpp> namespace vSMC { template <typename T> class Sampler { public : /// The type of particle values typedef T value_type; /// The type of partiles typedef Particle<T> particle_type; /// The type of initialize callable objects typedef boost::function<std::size_t (Particle<T> &, void *)> init_type; /// The type of move callable objects typedef boost::function<std::size_t (std::size_t, Particle<T> &)> move_type; /// The type of importance sampling integral typedef boost::function<void (std::size_t, const Particle<T> &, double *, void *)> integral_type; /// The type of path sampling integration typedef boost::function<double (std::size_t, const Particle<T> &, double *)> path_type; /// \brief Sampler does not have a default constructor /// /// \param N The number of particles /// \param init The functor used to initialize the particles /// \param move The functor used to move the particles and weights /// \param hist_mode The history storage mode. See HistoryMode /// \param rs_scheme The resampling scheme. See ResampleScheme /// \param seed The seed for the reampling RNG. See documentation of vDist /// \param brng The basic RNG for resampling RNG. See documentation of GSL Sampler ( std::size_t N, const init_type &init, const move_type &move, const typename Particle<T>::copy_type &copy, HistoryMode hist_mode = HISTORY_RAM, ResampleScheme rs_scheme = RESIDUAL, double rs_threshold = 0.5, const int seed = V_DIST_SEED, const gsl_rng_type *brng = V_DIST_GSL_BRNG) : initialized(false), init_particle(init), move_particle(move), rng(seed, brng), scheme(rs_scheme), threshold(rs_threshold* N), particle(N, copy), iter_num(0), mode(hist_mode), history(hist_mode), integrate_tmp(N), path_integral(NULL), path_estimate(0) {} /// \brief Get ESS /// /// \return The ESS value of the latest iteration double ESS () const { return ess_history.back(); } /// \brief Get all ESS /// /// \return History of ESS for all iterations std::vector<double> ESS_history () const { return ess_history; } /// \brief Get indicator of resampling /// /// \return A bool value, \b true if the latest iteration was resampled bool was_resampled () const { return resample_history.back(); } /// \brief Get history of resampling /// /// \return History of resampling for all iterations std::vector<bool> was_resampled_history () const { return resample_history; } /// \brief Get accept count /// /// \return The accept count of the latest iteration std::size_t accept_count () const { return accept_history.back(); } /// \brief Get history of accept count /// /// \return History of accept count for all iterations std::vector<std::size_t> accept_count_history () const { return accept_history; } /// \brief Read only access to the particle set /// /// \return A const reference to the latest particle set. /// \note Any operations that change the state of the sampler (e.g., an /// iteration) may invalidate the reference. const Particle<T> &getParticle () const { return particle; } /// \brief (Re)initialize the particle set /// /// \param param Additional parameters passed to initialization functor, /// the default is NULL void initialize (void *param = NULL) { history.clear(); ess_history.clear(); resample_history.clear(); accept_history.clear(); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor.begin(); imap != monitor.end(); ++imap) imap->second.clear(); path_sample.clear(); path_width.clear(); iter_num = 0; accept_history.push_back(init_particle(particle, param)); post_move(); initialized = true; } /// \brief Perform iteration void iterate () { if (!initialized) throw std::runtime_error( "ERROR: vSMC::Sampler::iterate: " "Sampler has not been initialized yet"); ++iter_num; accept_history.push_back(move_particle(iter_num, particle)); post_move(); } /// \brief Perform iteration /// /// \param n The number of iterations to be performed void iterate (std::size_t n) { for (std::size_t i = 0; i != n; ++i) iterate(); } /// \brief Perform importance sampling integration /// /// \param intgral The functor used to compute the integrands /// \param param Additional parameters to be passed to integral double integrate (integral_type integral, void *param) const { std::size_t n = particle.size(); integral(iter_num, particle, integrate_tmp, param); return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param integral The functor used to compute the integrands void add_monitor (const std::string &name, const typename Monitor<T>::integral_type &integral) { monitor.insert( typename std::map<std::string, Monitor<T> >::value_type( name, Monitor<T>(integral, particle.size()))); } /// \brief Get the iteration index of a monitor /// /// \param The name of the monitor /// \return A vector of the monitor index typename Monitor<T>::index_type get_monitor_index ( const std::string &name) const { return monitor.find(name)->second.get_index(); } /// \brief Get the record of Monite Carlo integration of a monitor /// /// \param name The name of the monitor /// \return A vector of the monitor record typename Monitor<T>::record_type get_monitor_record ( const std::string &name) const { return monitor.find(name)->second.get_record(); } /// \brief Get both the iteration index and record of a monitor typename Monitor<T>::value_type get_monitor_value ( const std::string &name) const { return monitor.find(name)->second.get(); } /// \brief Erase a monitor by name /// /// \param name The name of the monitor void erase_monitor (const std::string &name) { monitor.erase(name); } /// \brief Clear all monitors void clear_monitor () { monitor.clear(); } /// \brief Set the path sampling integral /// /// \param integral The functor used to compute the integrands void set_path_sampling (path_type integral) { path_integral = integral; } /// \brief Stop path sampling void clear_path_sampling () { path_integral = NULL; } /// \brief Get the results of path sampling double get_path_sampling () const { return 0; } private : /// Initialization indicator bool initialized; /// Initialization and movement init_type init_particle; move_type move_particle; /// Resampling vDist::RngGSL rng; ResampleScheme scheme; double threshold; /// Particle sets Particle<T> particle; std::size_t iter_num; std::vector<double> ess_history; std::vector<bool> resample_history; std::vector<std::size_t> accept_history; /// History HistoryMode mode; History<T> history; /// Monte Carlo estimation by integration mutable vDist::tool::Buffer<double> integrate_tmp; std::map<std::string, Monitor<T> > monitor; /// Path sampling path_type path_integral; std::vector<double> path_sample; std::vector<double> path_width; double path_estimate; void post_move () { bool res_indicator = false; if (particle.ESS() < threshold) { res_indicator = true; particle.resample(scheme, rng.get_rng()); } ess_history.push_back(particle.ESS()); resample_history.push_back(res_indicator); if (mode != HISTORY_NONE) history.push_back(particle); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor.begin(); imap != monitor.end(); ++imap) { if (!imap->second.empty()) imap->second.eval(iter_num, particle); } if (!path_integral.empty()) { double width; path_sample.push_back(eval_path(width)); path_width.push_back(width); } } double eval_path (double &width) { width = path_integral(iter_num, particle, integrate_tmp); return cblas_ddot(particle.size(), particle.get_weight_ptr(), 1, integrate_tmp, 1); } }; // class Sampler } // namespace vSMC #endif // V_SMC_SAMPLER_HPP <commit_msg>add normal model<commit_after>#ifndef V_SMC_SAMPLER_HPP #define V_SMC_SAMPLER_HPP #include <map> #include <stdexcept> #include <string> #include <vector> #include <gsl/gsl_cblas.h> #include <boost/function.hpp> #include <vDist/rng/gsl.hpp> #include <vDist/tool/buffer.hpp> #include <vSMC/history.hpp> #include <vSMC/monitor.hpp> #include <vSMC/particle.hpp> namespace vSMC { template <typename T> class Sampler { public : /// The type of particle values typedef T value_type; /// The type of partiles typedef Particle<T> particle_type; /// The type of initialize callable objects typedef boost::function<std::size_t (Particle<T> &, void *)> init_type; /// The type of move callable objects typedef boost::function<std::size_t (std::size_t, Particle<T> &)> move_type; /// The type of importance sampling integral typedef boost::function<void (std::size_t, const Particle<T> &, double *, void *)> integral_type; /// The type of path sampling integration typedef boost::function<double (std::size_t, const Particle<T> &, double *)> path_type; /// \brief Sampler does not have a default constructor /// /// \param N The number of particles /// \param init The functor used to initialize the particles /// \param move The functor used to move the particles and weights /// \param hist_mode The history storage mode. See HistoryMode /// \param rs_scheme The resampling scheme. See ResampleScheme /// \param seed The seed for the reampling RNG. See documentation of vDist /// \param brng The basic RNG for resampling RNG. See documentation of GSL Sampler ( std::size_t N, const init_type &init, const move_type &move, const typename Particle<T>::copy_type &copy, HistoryMode hist_mode = HISTORY_RAM, ResampleScheme rs_scheme = RESIDUAL, double rs_threshold = 0.5, const int seed = V_DIST_SEED, const gsl_rng_type *brng = V_DIST_GSL_BRNG) : initialized(false), init_particle(init), move_particle(move), rng(seed, brng), scheme(rs_scheme), threshold(rs_threshold* N), particle(N, copy), iter_num(0), mode(hist_mode), history(hist_mode), integrate_tmp(N), path_integral(NULL), path_estimate(0) {} /// \brief Get ESS /// /// \return The ESS value of the latest iteration double ESS () const { return ess_history.back(); } /// \brief Get all ESS /// /// \return History of ESS for all iterations std::vector<double> ESS_history () const { return ess_history; } /// \brief Get indicator of resampling /// /// \return A bool value, \b true if the latest iteration was resampled bool was_resampled () const { return resample_history.back(); } /// \brief Get history of resampling /// /// \return History of resampling for all iterations std::vector<bool> was_resampled_history () const { return resample_history; } /// \brief Get accept count /// /// \return The accept count of the latest iteration std::size_t accept_count () const { return accept_history.back(); } /// \brief Get history of accept count /// /// \return History of accept count for all iterations std::vector<std::size_t> accept_count_history () const { return accept_history; } /// \brief Read only access to the particle set /// /// \return A const reference to the latest particle set. /// \note Any operations that change the state of the sampler (e.g., an /// iteration) may invalidate the reference. const Particle<T> &getParticle () const { return particle; } /// \brief (Re)initialize the particle set /// /// \param param Additional parameters passed to initialization functor, /// the default is NULL void initialize (void *param = NULL) { history.clear(); ess_history.clear(); resample_history.clear(); accept_history.clear(); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor.begin(); imap != monitor.end(); ++imap) imap->second.clear(); path_sample.clear(); path_width.clear(); iter_num = 0; accept_history.push_back(init_particle(particle, param)); post_move(); initialized = true; } /// \brief Perform iteration void iterate () { if (!initialized) throw std::runtime_error( "ERROR: vSMC::Sampler::iterate: " "Sampler has not been initialized yet"); ++iter_num; accept_history.push_back(move_particle(iter_num, particle)); post_move(); } /// \brief Perform iteration /// /// \param n The number of iterations to be performed void iterate (std::size_t n) { for (std::size_t i = 0; i != n; ++i) iterate(); } /// \brief Perform importance sampling integration /// /// \param intgral The functor used to compute the integrands double integrate (typename Monitor<T>::integral_type integral) const { std::size_t n = particle.size(); integral(iter_num, particle, integrate_tmp); return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1); } /// \brief Perform importance sampling integration /// /// \param intgral The functor used to compute the integrands /// \param param Additional parameters to be passed to integral double integrate (integral_type integral, void *param) const { std::size_t n = particle.size(); integral(iter_num, particle, integrate_tmp, param); return cblas_ddot(n, particle.get_weight_ptr(), 1, integrate_tmp, 1); } /// \brief Add a monitor, similar to \b monitor in \b BUGS /// /// \param name The name of the monitor /// \param integral The functor used to compute the integrands void add_monitor (const std::string &name, const typename Monitor<T>::integral_type &integral) { monitor.insert( typename std::map<std::string, Monitor<T> >::value_type( name, Monitor<T>(integral, particle.size()))); } /// \brief Get the iteration index of a monitor /// /// \param The name of the monitor /// \return A vector of the monitor index typename Monitor<T>::index_type get_monitor_index ( const std::string &name) const { return monitor.find(name)->second.get_index(); } /// \brief Get the record of Monite Carlo integration of a monitor /// /// \param name The name of the monitor /// \return A vector of the monitor record typename Monitor<T>::record_type get_monitor_record ( const std::string &name) const { return monitor.find(name)->second.get_record(); } /// \brief Get both the iteration index and record of a monitor typename Monitor<T>::value_type get_monitor_value ( const std::string &name) const { return monitor.find(name)->second.get(); } /// \brief Erase a monitor by name /// /// \param name The name of the monitor void erase_monitor (const std::string &name) { monitor.erase(name); } /// \brief Clear all monitors void clear_monitor () { monitor.clear(); } /// \brief Set the path sampling integral /// /// \param integral The functor used to compute the integrands void set_path_sampling (path_type integral) { path_integral = integral; } /// \brief Stop path sampling void clear_path_sampling () { path_integral = NULL; } /// \brief Get the results of path sampling double get_path_sampling () const { return 0; } private : /// Initialization indicator bool initialized; /// Initialization and movement init_type init_particle; move_type move_particle; /// Resampling vDist::RngGSL rng; ResampleScheme scheme; double threshold; /// Particle sets Particle<T> particle; std::size_t iter_num; std::vector<double> ess_history; std::vector<bool> resample_history; std::vector<std::size_t> accept_history; /// History HistoryMode mode; History<T> history; /// Monte Carlo estimation by integration mutable vDist::tool::Buffer<double> integrate_tmp; std::map<std::string, Monitor<T> > monitor; /// Path sampling path_type path_integral; std::vector<double> path_sample; std::vector<double> path_width; double path_estimate; void post_move () { bool res_indicator = false; if (particle.ESS() < threshold) { res_indicator = true; particle.resample(scheme, rng.get_rng()); } ess_history.push_back(particle.ESS()); resample_history.push_back(res_indicator); if (mode != HISTORY_NONE) history.push_back(particle); for (typename std::map<std::string, Monitor<T> >::iterator imap = monitor.begin(); imap != monitor.end(); ++imap) { if (!imap->second.empty()) imap->second.eval(iter_num, particle); } if (!path_integral.empty()) { double width; path_sample.push_back(eval_path(width)); path_width.push_back(width); } } double eval_path (double &width) { width = path_integral(iter_num, particle, integrate_tmp); return cblas_ddot(particle.size(), particle.get_weight_ptr(), 1, integrate_tmp, 1); } }; // class Sampler } // namespace vSMC #endif // V_SMC_SAMPLER_HPP <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediametadataprovider.h" #include "s60mediaplayersession.h" #include <QtCore/qdebug.h> S60MediaMetaDataProvider::S60MediaMetaDataProvider(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMetaDataControl(parent) , m_mediaPlayerResolver(mediaPlayerResolver) , m_session(NULL) { } S60MediaMetaDataProvider::~S60MediaMetaDataProvider() { } bool S60MediaMetaDataProvider::isMetaDataAvailable() const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session) return m_session->isMetadataAvailable(); return false; } bool S60MediaMetaDataProvider::isWritable() const { return false; } QVariant S60MediaMetaDataProvider::metaData(QtMediaServices::MetaData key) const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session && m_session->isMetadataAvailable()) return m_session->metaData(metaDataKeyAsString(key)); return QVariant(); } void S60MediaMetaDataProvider::setMetaData(QtMediaServices::MetaData key, QVariant const &value) { Q_UNUSED(key); Q_UNUSED(value); } QList<QtMediaServices::MetaData> S60MediaMetaDataProvider::availableMetaData() const { m_session = m_mediaPlayerResolver.PlayerSession(); QList<QtMediaServices::MetaData> metaDataTags; if (m_session && m_session->isMetadataAvailable()) { for (int i = QtMediaServices::Title; i <= QtMediaServices::DeviceSettingDescription; i++) { QString metaData = metaDataKeyAsString((QtMediaServices::MetaData)i); if (!metaData.isEmpty()) { if (!m_session->metaData(metaData).toString().isEmpty()) { metaDataTags.append((QtMediaServices::MetaData)i); } } } } return metaDataTags; } QVariant S60MediaMetaDataProvider::extendedMetaData(const QString &key) const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session && m_session->isMetadataAvailable()) return m_session->metaData(key); return QVariant(); } void S60MediaMetaDataProvider::setExtendedMetaData(const QString &key, QVariant const &value) { Q_UNUSED(key); Q_UNUSED(value); } QStringList S60MediaMetaDataProvider::availableExtendedMetaData() const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session && m_session->isMetadataAvailable()) return m_session->availableMetaData().keys(); return QStringList(); } QString S60MediaMetaDataProvider::metaDataKeyAsString(QtMediaServices::MetaData key) const { switch(key) { case QtMediaServices::Title: return "title"; case QtMediaServices::AlbumArtist: return "artist"; case QtMediaServices::Comment: return "comment"; case QtMediaServices::Genre: return "genre"; case QtMediaServices::Year: return "year"; case QtMediaServices::Copyright: return "copyright"; case QtMediaServices::AlbumTitle: return "album"; case QtMediaServices::Composer: return "composer"; case QtMediaServices::TrackNumber: return "albumtrack"; case QtMediaServices::AudioBitRate: return "audiobitrate"; case QtMediaServices::VideoBitRate: return "videobitrate"; case QtMediaServices::Duration: return "duration"; case QtMediaServices::MediaType: return "contenttype"; case QtMediaServices::SubTitle: // TODO: Find the matching metadata keys case QtMediaServices::Description: case QtMediaServices::Category: case QtMediaServices::Date: case QtMediaServices::UserRating: case QtMediaServices::Keywords: case QtMediaServices::Language: case QtMediaServices::Publisher: case QtMediaServices::ParentalRating: case QtMediaServices::RatingOrganisation: case QtMediaServices::Size: case QtMediaServices::AudioCodec: case QtMediaServices::AverageLevel: case QtMediaServices::ChannelCount: case QtMediaServices::PeakValue: case QtMediaServices::SampleRate: case QtMediaServices::Author: case QtMediaServices::ContributingArtist: case QtMediaServices::Conductor: case QtMediaServices::Lyrics: case QtMediaServices::Mood: case QtMediaServices::TrackCount: case QtMediaServices::CoverArtUrlSmall: case QtMediaServices::CoverArtUrlLarge: case QtMediaServices::Resolution: case QtMediaServices::PixelAspectRatio: case QtMediaServices::VideoFrameRate: case QtMediaServices::VideoCodec: case QtMediaServices::PosterUrl: case QtMediaServices::ChapterNumber: case QtMediaServices::Director: case QtMediaServices::LeadPerformer: case QtMediaServices::Writer: case QtMediaServices::CameraManufacturer: case QtMediaServices::CameraModel: case QtMediaServices::Event: case QtMediaServices::Subject: default: break; } return QString(); } <commit_msg>Symbian: Changed backend to support recently added QtMediaServices::CoverArtImage metadata key.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** 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 qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediametadataprovider.h" #include "s60mediaplayersession.h" #include <QtCore/qdebug.h> S60MediaMetaDataProvider::S60MediaMetaDataProvider(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMetaDataControl(parent) , m_mediaPlayerResolver(mediaPlayerResolver) , m_session(NULL) { } S60MediaMetaDataProvider::~S60MediaMetaDataProvider() { } bool S60MediaMetaDataProvider::isMetaDataAvailable() const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session) return m_session->isMetadataAvailable(); return false; } bool S60MediaMetaDataProvider::isWritable() const { return false; } QVariant S60MediaMetaDataProvider::metaData(QtMediaServices::MetaData key) const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session && m_session->isMetadataAvailable()) return m_session->metaData(metaDataKeyAsString(key)); return QVariant(); } void S60MediaMetaDataProvider::setMetaData(QtMediaServices::MetaData key, QVariant const &value) { Q_UNUSED(key); Q_UNUSED(value); } QList<QtMediaServices::MetaData> S60MediaMetaDataProvider::availableMetaData() const { m_session = m_mediaPlayerResolver.PlayerSession(); QList<QtMediaServices::MetaData> metaDataTags; if (m_session && m_session->isMetadataAvailable()) { for (int i = QtMediaServices::Title; i <= QtMediaServices::DeviceSettingDescription; i++) { QString metaData = metaDataKeyAsString((QtMediaServices::MetaData)i); if (!metaData.isEmpty()) { if (!m_session->metaData(metaData).toString().isEmpty()) { metaDataTags.append((QtMediaServices::MetaData)i); } } } } return metaDataTags; } QVariant S60MediaMetaDataProvider::extendedMetaData(const QString &key) const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session && m_session->isMetadataAvailable()) return m_session->metaData(key); return QVariant(); } void S60MediaMetaDataProvider::setExtendedMetaData(const QString &key, QVariant const &value) { Q_UNUSED(key); Q_UNUSED(value); } QStringList S60MediaMetaDataProvider::availableExtendedMetaData() const { m_session = m_mediaPlayerResolver.PlayerSession(); if (m_session && m_session->isMetadataAvailable()) return m_session->availableMetaData().keys(); return QStringList(); } QString S60MediaMetaDataProvider::metaDataKeyAsString(QtMediaServices::MetaData key) const { switch(key) { case QtMediaServices::Title: return "title"; case QtMediaServices::AlbumArtist: return "artist"; case QtMediaServices::Comment: return "comment"; case QtMediaServices::Genre: return "genre"; case QtMediaServices::Year: return "year"; case QtMediaServices::Copyright: return "copyright"; case QtMediaServices::AlbumTitle: return "album"; case QtMediaServices::Composer: return "composer"; case QtMediaServices::TrackNumber: return "albumtrack"; case QtMediaServices::AudioBitRate: return "audiobitrate"; case QtMediaServices::VideoBitRate: return "videobitrate"; case QtMediaServices::Duration: return "duration"; case QtMediaServices::MediaType: return "contenttype"; case QtMediaServices::CoverArtImage: return "attachedpicture"; case QtMediaServices::SubTitle: // TODO: Find the matching metadata keys case QtMediaServices::Description: case QtMediaServices::Category: case QtMediaServices::Date: case QtMediaServices::UserRating: case QtMediaServices::Keywords: case QtMediaServices::Language: case QtMediaServices::Publisher: case QtMediaServices::ParentalRating: case QtMediaServices::RatingOrganisation: case QtMediaServices::Size: case QtMediaServices::AudioCodec: case QtMediaServices::AverageLevel: case QtMediaServices::ChannelCount: case QtMediaServices::PeakValue: case QtMediaServices::SampleRate: case QtMediaServices::Author: case QtMediaServices::ContributingArtist: case QtMediaServices::Conductor: case QtMediaServices::Lyrics: case QtMediaServices::Mood: case QtMediaServices::TrackCount: case QtMediaServices::CoverArtUrlSmall: case QtMediaServices::CoverArtUrlLarge: case QtMediaServices::Resolution: case QtMediaServices::PixelAspectRatio: case QtMediaServices::VideoFrameRate: case QtMediaServices::VideoCodec: case QtMediaServices::PosterUrl: case QtMediaServices::ChapterNumber: case QtMediaServices::Director: case QtMediaServices::LeadPerformer: case QtMediaServices::Writer: case QtMediaServices::CameraManufacturer: case QtMediaServices::CameraModel: case QtMediaServices::Event: case QtMediaServices::Subject: default: break; } return QString(); } <|endoftext|>
<commit_before>#include "sensorsConfigurationWidget.h" #include "ui_sensorsConfigurationWidget.h" #include "../../../../qrkernel/settingsManager.h" using namespace qReal::interpreters::robots; using namespace qReal::interpreters::robots::details; SensorsConfigurationWidget::SensorsConfigurationWidget(bool autosaveMode, QWidget *parent) : QWidget(parent) , mUi(new Ui::SensorsConfigurationWidget) { mUi->setupUi(this); reinitValues(); refresh(); if (autosaveMode) { startChangesListening(); } } SensorsConfigurationWidget::~SensorsConfigurationWidget() { delete mUi; } void SensorsConfigurationWidget::startChangesListening() { connect(mUi->port1ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); connect(mUi->port2ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); connect(mUi->port3ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); connect(mUi->port4ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); } void SensorsConfigurationWidget::reinitValues() { QStringList sensorNames; sensorNames << tr("Unused") << tr("Touch sensor (boolean value)") << tr("Touch sensor (raw value)") << tr("Sonar sensor") << tr("Light sensor") << tr("Color sensor (full colors)") << tr("Color sensor (red)") << tr("Color sensor (green)") << tr("Color sensor (blue)") << tr("Color sensor (passive)") << tr("Sound sensor") << tr("gyroscope(passive)") << tr("aks(passive)") ; mUi->port1ComboBox->clear(); mUi->port2ComboBox->clear(); mUi->port3ComboBox->clear(); mUi->port4ComboBox->clear(); mUi->port1ComboBox->addItems(sensorNames); mUi->port2ComboBox->addItems(sensorNames); mUi->port3ComboBox->addItems(sensorNames); mUi->port4ComboBox->addItems(sensorNames); } void SensorsConfigurationWidget::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: { retranslateUi(); break; } default: break; } } void SensorsConfigurationWidget::refresh() { sensorType::SensorTypeEnum const port1 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port1SensorType").toInt()); sensorType::SensorTypeEnum const port2 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port2SensorType").toInt()); sensorType::SensorTypeEnum const port3 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port3SensorType").toInt()); sensorType::SensorTypeEnum const port4 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port4SensorType").toInt()); mUi->port1ComboBox->setCurrentIndex(port1); mUi->port2ComboBox->setCurrentIndex(port2); mUi->port3ComboBox->setCurrentIndex(port3); mUi->port4ComboBox->setCurrentIndex(port4); } void SensorsConfigurationWidget::save() { SettingsManager::setValue("port1SensorType", selectedPort1Sensor()); SettingsManager::setValue("port2SensorType", selectedPort2Sensor()); SettingsManager::setValue("port3SensorType", selectedPort3Sensor()); SettingsManager::setValue("port4SensorType", selectedPort4Sensor()); emit saved(); } void SensorsConfigurationWidget::retranslateUi() { mUi->retranslateUi(this); reinitValues(); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort1Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port1ComboBox->currentIndex()); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort2Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port2ComboBox->currentIndex()); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort3Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port3ComboBox->currentIndex()); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort4Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port4ComboBox->currentIndex()); } <commit_msg>someChanges<commit_after>#include "sensorsConfigurationWidget.h" #include "ui_sensorsConfigurationWidget.h" #include "../../../../qrkernel/settingsManager.h" using namespace qReal::interpreters::robots; using namespace qReal::interpreters::robots::details; SensorsConfigurationWidget::SensorsConfigurationWidget(bool autosaveMode, QWidget *parent) : QWidget(parent) , mUi(new Ui::SensorsConfigurationWidget) { mUi->setupUi(this); reinitValues(); refresh(); if (autosaveMode) { startChangesListening(); } } SensorsConfigurationWidget::~SensorsConfigurationWidget() { delete mUi; } void SensorsConfigurationWidget::startChangesListening() { connect(mUi->port1ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); connect(mUi->port2ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); connect(mUi->port3ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); connect(mUi->port4ComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(save())); } void SensorsConfigurationWidget::reinitValues() { QStringList sensorNames; sensorNames << tr("Unused") << tr("Touch sensor (boolean value)") << tr("Touch sensor (raw value)") << tr("Sonar sensor") << tr("Light sensor") << tr("Color sensor (full colors)") << tr("Color sensor (red)") << tr("Color sensor (green)") << tr("Color sensor (blue)") << tr("Color sensor (passive)") << tr("Sound sensor") << tr("Gyroscope") << tr("Accelerometer") ; mUi->port1ComboBox->clear(); mUi->port2ComboBox->clear(); mUi->port3ComboBox->clear(); mUi->port4ComboBox->clear(); mUi->port1ComboBox->addItems(sensorNames); mUi->port2ComboBox->addItems(sensorNames); mUi->port3ComboBox->addItems(sensorNames); mUi->port4ComboBox->addItems(sensorNames); } void SensorsConfigurationWidget::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::LanguageChange: { retranslateUi(); break; } default: break; } } void SensorsConfigurationWidget::refresh() { sensorType::SensorTypeEnum const port1 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port1SensorType").toInt()); sensorType::SensorTypeEnum const port2 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port2SensorType").toInt()); sensorType::SensorTypeEnum const port3 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port3SensorType").toInt()); sensorType::SensorTypeEnum const port4 = static_cast<sensorType::SensorTypeEnum>(SettingsManager::value("port4SensorType").toInt()); mUi->port1ComboBox->setCurrentIndex(port1); mUi->port2ComboBox->setCurrentIndex(port2); mUi->port3ComboBox->setCurrentIndex(port3); mUi->port4ComboBox->setCurrentIndex(port4); } void SensorsConfigurationWidget::save() { SettingsManager::setValue("port1SensorType", selectedPort1Sensor()); SettingsManager::setValue("port2SensorType", selectedPort2Sensor()); SettingsManager::setValue("port3SensorType", selectedPort3Sensor()); SettingsManager::setValue("port4SensorType", selectedPort4Sensor()); emit saved(); } void SensorsConfigurationWidget::retranslateUi() { mUi->retranslateUi(this); reinitValues(); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort1Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port1ComboBox->currentIndex()); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort2Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port2ComboBox->currentIndex()); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort3Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port3ComboBox->currentIndex()); } sensorType::SensorTypeEnum SensorsConfigurationWidget::selectedPort4Sensor() const { return static_cast<sensorType::SensorTypeEnum>(mUi->port4ComboBox->currentIndex()); } <|endoftext|>
<commit_before>#include <mpi.h> #include <iostream> #include <vector> // using TCLAP for command line parsing #include <tclap/CmdLine.h> // parallel block decomposition of a file #include <mxx/file.hpp> // suffix array construction #include <suffix_array.hpp> #include <alphabet.hpp> // for random DNA #include <timer.hpp> void benchmark_k(const std::string& local_str, int k, MPI_Comm comm) { int p, rank; MPI_Comm_size(comm, &p); MPI_Comm_rank(comm, &rank); timer t; typedef suffix_array<std::string::const_iterator, std::size_t, false> sa_t; { // without LCP and fast std::string method_name = "reg-fast-nolcp"; double start = t.get_ms(); sa_t sa(local_str.begin(), local_str.end(), comm); sa.construct(true, k); double time = t.get_ms() - start; if (rank == 0) std::cout << p << ";" << method_name << ";" << time << std::endl; } { // without LCP and slow std::string method_name = "reg-nolcp"; double start = t.get_ms(); sa_t sa(local_str.begin(), local_str.end(), comm); sa.construct(false, k); double time = t.get_ms() - start; if (rank == 0) std::cout << p << ";" << method_name << ";" << time << std::endl; } // TODO: array construction with multiple } int main(int argc, char *argv[]) { // set up MPI MPI_Init(&argc, &argv); int p, rank; MPI_Comm_size(MPI_COMM_WORLD, &p); MPI_Comm_rank(MPI_COMM_WORLD, &rank); try { // define commandline usage TCLAP::CmdLine cmd("Benchmark different suffix array construction variants."); TCLAP::ValueArg<std::string> fileArg("f", "file", "Input filename.", true, "", "filename"); TCLAP::ValueArg<std::size_t> randArg("r", "random", "Random input size", true, 0, "size"); cmd.xorAdd(fileArg, randArg); TCLAP::ValueArg<int> iterArg("i", "iterations", "Number of iterations to run", false, 1, "num"); cmd.add(iterArg); TCLAP::ValueArg<int> kArg("k", "kmer-size", "The size of the `k` in the intial sorting.", false, 0, "size"); cmd.add(kArg); cmd.parse(argc, argv); std::string local_str; if (fileArg.getValue() != "") { local_str = mxx::file_block_decompose(fileArg.getValue().c_str()); } else { // TODO: proper parallel random generation!! local_str = rand_dna(randArg.getValue(), rank); } // run all benchmarks for (int i = 0; i < iterArg.getValue(); ++i) benchmark_k(local_str, kArg.getValue(), MPI_COMM_WORLD); // catch any TCLAP exception } catch (TCLAP::ArgException& e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; } // finalize MPI MPI_Finalize(); return 0; } <commit_msg>psac: output of `k` during benchmark<commit_after>#include <mpi.h> #include <iostream> #include <vector> // using TCLAP for command line parsing #include <tclap/CmdLine.h> // parallel block decomposition of a file #include <mxx/file.hpp> // suffix array construction #include <suffix_array.hpp> #include <alphabet.hpp> // for random DNA #include <timer.hpp> void benchmark_k(const std::string& local_str, int k, MPI_Comm comm) { int p, rank; MPI_Comm_size(comm, &p); MPI_Comm_rank(comm, &rank); timer t; typedef suffix_array<std::string::const_iterator, std::size_t, false> sa_t; { // without LCP and fast std::string method_name = "reg-fast-nolcp"; double start = t.get_ms(); sa_t sa(local_str.begin(), local_str.end(), comm); sa.construct(true, k); double time = t.get_ms() - start; if (rank == 0) std::cout << p << ";" << method_name << ";" << k << ";" << time << std::endl; } { // without LCP and slow std::string method_name = "reg-nolcp"; double start = t.get_ms(); sa_t sa(local_str.begin(), local_str.end(), comm); sa.construct(false, k); double time = t.get_ms() - start; if (rank == 0) std::cout << p << ";" << method_name << ";" << k << ";" << time << std::endl; } // TODO: array construction with multiple } int main(int argc, char *argv[]) { // set up MPI MPI_Init(&argc, &argv); int p, rank; MPI_Comm_size(MPI_COMM_WORLD, &p); MPI_Comm_rank(MPI_COMM_WORLD, &rank); try { // define commandline usage TCLAP::CmdLine cmd("Benchmark different suffix array construction variants."); TCLAP::ValueArg<std::string> fileArg("f", "file", "Input filename.", true, "", "filename"); TCLAP::ValueArg<std::size_t> randArg("r", "random", "Random input size", true, 0, "size"); cmd.xorAdd(fileArg, randArg); TCLAP::ValueArg<int> iterArg("i", "iterations", "Number of iterations to run", false, 1, "num"); cmd.add(iterArg); TCLAP::ValueArg<int> kArg("k", "kmer-size", "The size of the `k` in the intial sorting.", false, 0, "size"); cmd.add(kArg); cmd.parse(argc, argv); std::string local_str; if (fileArg.getValue() != "") { local_str = mxx::file_block_decompose(fileArg.getValue().c_str()); } else { // TODO: proper parallel random generation!! local_str = rand_dna(randArg.getValue(), rank); } // run all benchmarks for (int i = 0; i < iterArg.getValue(); ++i) benchmark_k(local_str, kArg.getValue(), MPI_COMM_WORLD); // catch any TCLAP exception } catch (TCLAP::ArgException& e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; } // finalize MPI MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>/** * @file ArgumentParserTest.cpp * @brief ArgumentParser class tester. * @author zer0 * @date 2019-10-09 */ #include <gtest/gtest.h> #include <libtbag/string/ArgumentParser.hpp> using namespace libtbag; using namespace libtbag::string; using ap = ArgumentParser; using at = ArgumentParser::ActionType; TEST(ArgumentParserTest, Add) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"}, ArgumentParser::ActionType::AT_STORE, "device"})); ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2, ap::default_value=1, ap::store_const, ap::name="--input-type", ap::name="-t", ap::dest="input_type")); ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type")); } TEST(ArgumentParserTest, Optional_01) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"}, ArgumentParser::ActionType::AT_STORE, "device"})); auto const result1 = parser.parse("program -d 0"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(1, result1.value.optional.size()); ASSERT_STREQ("0", result1.value.optional.at("device").c_str()); ASSERT_EQ(0, result1.value.positional.size()); ASSERT_EQ(0, result1.value.remain.size()); auto const result2 = parser.parse("program --device=1"); ASSERT_EQ(E_SUCCESS, result2.code); ASSERT_EQ(1, result2.value.optional.size()); ASSERT_STREQ("1", result2.value.optional.at("device").c_str()); ASSERT_EQ(0, result2.value.positional.size()); ASSERT_EQ(0, result2.value.remain.size()); auto const result3 = parser.parse("program --device 2"); ASSERT_EQ(E_SUCCESS, result3.code); ASSERT_EQ(1, result3.value.optional.size()); ASSERT_STREQ("2", result3.value.optional.at("device").c_str()); ASSERT_EQ(0, result3.value.positional.size()); ASSERT_EQ(0, result3.value.remain.size()); auto const result4 = parser.parse("program --device"); ASSERT_EQ(E_ILLSTATE, result4.code); auto const result5 = parser.parse("program test"); ASSERT_EQ(E_SUCCESS, result5.code); ASSERT_EQ(0, result5.value.optional.size()); ASSERT_EQ(0, result5.value.positional.size()); ASSERT_EQ(1, result5.value.remain.size()); ASSERT_STREQ("test", result5.value.remain[0].c_str()); } TEST(ArgumentParserTest, Optional_02) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2, ap::default_value=1, ap::store_const, ap::name="--device", ap::name="-d", ap::dest="device")); auto const result1 = parser.parse("program --device 3 test1 test2"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(1, result1.value.optional.size()); ASSERT_STREQ("2", result1.value.optional.at("device").c_str()); ASSERT_EQ(0, result1.value.positional.size()); ASSERT_EQ(3, result1.value.remain.size()); ASSERT_STREQ("3", result1.value.remain[0].c_str()); ASSERT_STREQ("test1", result1.value.remain[1].c_str()); ASSERT_STREQ("test2", result1.value.remain[2].c_str()); auto const result2 = parser.parse("program"); ASSERT_EQ(1, result2.value.optional.size()); ASSERT_STREQ("1", result2.value.optional.at("device").c_str()); ASSERT_EQ(0, result2.value.positional.size()); ASSERT_EQ(0, result2.value.remain.size()); auto const result3 = parser.parse("program -d"); ASSERT_EQ(1, result3.value.optional.size()); ASSERT_STREQ("2", result3.value.optional.at("device").c_str()); ASSERT_EQ(0, result3.value.positional.size()); ASSERT_EQ(0, result3.value.remain.size()); } TEST(ArgumentParserTest, Positional_01) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type")); auto const result1 = parser.parse("program bool test1 test2"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(0, result1.value.optional.size()); ASSERT_EQ(1, result1.value.positional.size()); ASSERT_STREQ("bool", result1.value.positional.at("type").c_str()); ASSERT_EQ(2, result1.value.remain.size()); ASSERT_STREQ("test1", result1.value.remain[0].c_str()); ASSERT_STREQ("test2", result1.value.remain[1].c_str()); auto const result2 = parser.parse("program"); ASSERT_EQ(E_ILLARGS, result2.code); } TEST(ArgumentParserTest, Positional_02) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa1")); ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa2", ap::default_value=100)); auto const result1 = parser.parse("program val1"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(0, result1.value.optional.size()); ASSERT_EQ(2, result1.value.positional.size()); ASSERT_STREQ("val1", result1.value.positional.at("aa1").c_str()); ASSERT_STREQ("100", result1.value.positional.at("aa2").c_str()); ASSERT_EQ(0, result1.value.remain.size()); auto const result2 = parser.parse("program val1 val2"); ASSERT_EQ(E_SUCCESS, result2.code); ASSERT_EQ(0, result2.value.optional.size()); ASSERT_EQ(2, result2.value.positional.size()); ASSERT_STREQ("val1", result2.value.positional.at("aa1").c_str()); ASSERT_STREQ("val2", result2.value.positional.at("aa2").c_str()); ASSERT_EQ(0, result2.value.remain.size()); auto const result3 = parser.parse("program"); ASSERT_EQ(E_ILLARGS, result3.code); } struct ArgumentParserTestFixture : public testing::Test { ArgumentParser parser; void SetUp() override { parser.add(ap::name="--input", ap::name="-i"); parser.add(ap::name="--output", ap::name="-o"); parser.add(ap::name="--threshold", ap::name="-t", ap::default_value=0.5); parser.add(ap::name="--verbose", ap::name="-v", ap::store_const, ap::const_value=true); parser.add(ap::name="cmd1"); parser.add(ap::name="cmd2", ap::default_value="empty"); } void TearDown() override { // EMPTY. } }; TEST_F(ArgumentParserTestFixture, Default) { auto const result1 = parser.parse("program -i test -o result -v -t 0.7 kkk zzz xxx"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(4, result1.value.optional.size()); ASSERT_STREQ("test", result1.value.optional.at("input").c_str()); ASSERT_STREQ("result", result1.value.optional.at("output").c_str()); ASSERT_STREQ("1", result1.value.optional.at("verbose").c_str()); ASSERT_STREQ("0.7", result1.value.optional.at("threshold").c_str()); ASSERT_EQ(2, result1.value.positional.size()); ASSERT_STREQ("kkk", result1.value.positional.at("cmd1").c_str()); ASSERT_STREQ("zzz", result1.value.positional.at("cmd2").c_str()); ASSERT_EQ(1, result1.value.remain.size()); ASSERT_STREQ("xxx", result1.value.remain[0].c_str()); } <commit_msg>Create ArgumentParserTestFixture.StopParsing tester.<commit_after>/** * @file ArgumentParserTest.cpp * @brief ArgumentParser class tester. * @author zer0 * @date 2019-10-09 */ #include <gtest/gtest.h> #include <libtbag/string/ArgumentParser.hpp> using namespace libtbag; using namespace libtbag::string; using ap = ArgumentParser; using at = ArgumentParser::ActionType; TEST(ArgumentParserTest, Add) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"}, ArgumentParser::ActionType::AT_STORE, "device"})); ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2, ap::default_value=1, ap::store_const, ap::name="--input-type", ap::name="-t", ap::dest="input_type")); ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type")); } TEST(ArgumentParserTest, Optional_01) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add({{"-d", "--device"}, ArgumentParser::ActionType::AT_STORE, "device"})); auto const result1 = parser.parse("program -d 0"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(1, result1.value.optional.size()); ASSERT_STREQ("0", result1.value.optional.at("device").c_str()); ASSERT_EQ(0, result1.value.positional.size()); ASSERT_EQ(0, result1.value.remain.size()); auto const result2 = parser.parse("program --device=1"); ASSERT_EQ(E_SUCCESS, result2.code); ASSERT_EQ(1, result2.value.optional.size()); ASSERT_STREQ("1", result2.value.optional.at("device").c_str()); ASSERT_EQ(0, result2.value.positional.size()); ASSERT_EQ(0, result2.value.remain.size()); auto const result3 = parser.parse("program --device 2"); ASSERT_EQ(E_SUCCESS, result3.code); ASSERT_EQ(1, result3.value.optional.size()); ASSERT_STREQ("2", result3.value.optional.at("device").c_str()); ASSERT_EQ(0, result3.value.positional.size()); ASSERT_EQ(0, result3.value.remain.size()); auto const result4 = parser.parse("program --device"); ASSERT_EQ(E_ILLSTATE, result4.code); auto const result5 = parser.parse("program test"); ASSERT_EQ(E_SUCCESS, result5.code); ASSERT_EQ(0, result5.value.optional.size()); ASSERT_EQ(0, result5.value.positional.size()); ASSERT_EQ(1, result5.value.remain.size()); ASSERT_STREQ("test", result5.value.remain[0].c_str()); } TEST(ArgumentParserTest, Optional_02) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add(ap::const_value=2, ap::default_value=1, ap::store_const, ap::name="--device", ap::name="-d", ap::dest="device")); auto const result1 = parser.parse("program --device 3 test1 test2"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(1, result1.value.optional.size()); ASSERT_STREQ("2", result1.value.optional.at("device").c_str()); ASSERT_EQ(0, result1.value.positional.size()); ASSERT_EQ(3, result1.value.remain.size()); ASSERT_STREQ("3", result1.value.remain[0].c_str()); ASSERT_STREQ("test1", result1.value.remain[1].c_str()); ASSERT_STREQ("test2", result1.value.remain[2].c_str()); auto const result2 = parser.parse("program"); ASSERT_EQ(1, result2.value.optional.size()); ASSERT_STREQ("1", result2.value.optional.at("device").c_str()); ASSERT_EQ(0, result2.value.positional.size()); ASSERT_EQ(0, result2.value.remain.size()); auto const result3 = parser.parse("program -d"); ASSERT_EQ(1, result3.value.optional.size()); ASSERT_STREQ("2", result3.value.optional.at("device").c_str()); ASSERT_EQ(0, result3.value.positional.size()); ASSERT_EQ(0, result3.value.remain.size()); } TEST(ArgumentParserTest, Positional_01) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add("type", at::AT_STORE, "type")); auto const result1 = parser.parse("program bool test1 test2"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(0, result1.value.optional.size()); ASSERT_EQ(1, result1.value.positional.size()); ASSERT_STREQ("bool", result1.value.positional.at("type").c_str()); ASSERT_EQ(2, result1.value.remain.size()); ASSERT_STREQ("test1", result1.value.remain[0].c_str()); ASSERT_STREQ("test2", result1.value.remain[1].c_str()); auto const result2 = parser.parse("program"); ASSERT_EQ(E_ILLARGS, result2.code); } TEST(ArgumentParserTest, Positional_02) { ArgumentParser parser; ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa1")); ASSERT_EQ(E_SUCCESS, parser.add(ap::name="aa2", ap::default_value=100)); auto const result1 = parser.parse("program val1"); ASSERT_EQ(E_SUCCESS, result1.code); ASSERT_EQ(0, result1.value.optional.size()); ASSERT_EQ(2, result1.value.positional.size()); ASSERT_STREQ("val1", result1.value.positional.at("aa1").c_str()); ASSERT_STREQ("100", result1.value.positional.at("aa2").c_str()); ASSERT_EQ(0, result1.value.remain.size()); auto const result2 = parser.parse("program val1 val2"); ASSERT_EQ(E_SUCCESS, result2.code); ASSERT_EQ(0, result2.value.optional.size()); ASSERT_EQ(2, result2.value.positional.size()); ASSERT_STREQ("val1", result2.value.positional.at("aa1").c_str()); ASSERT_STREQ("val2", result2.value.positional.at("aa2").c_str()); ASSERT_EQ(0, result2.value.remain.size()); auto const result3 = parser.parse("program"); ASSERT_EQ(E_ILLARGS, result3.code); } struct ArgumentParserTestFixture : public testing::Test { ArgumentParser parser; void SetUp() override { parser.add(ap::name="--input", ap::name="-i"); parser.add(ap::name="--output", ap::name="-o"); parser.add(ap::name="--threshold", ap::name="-t", ap::default_value=0.5); parser.add(ap::name="--verbose", ap::name="-v", ap::store_const, ap::const_value=true); parser.add(ap::name="cmd1"); parser.add(ap::name="cmd2", ap::default_value="empty"); } void TearDown() override { // EMPTY. } }; TEST_F(ArgumentParserTestFixture, Parse_Complex) { auto const result = parser.parse("program -i test kkk -o result zzz -v xxx -t 0.7 vvv"); ASSERT_EQ(E_SUCCESS, result.code); ASSERT_EQ(4, result.value.optional.size()); ASSERT_STREQ("test", result.value.optional.at("input").c_str()); ASSERT_STREQ("result", result.value.optional.at("output").c_str()); ASSERT_STREQ("1", result.value.optional.at("verbose").c_str()); ASSERT_STREQ("0.7", result.value.optional.at("threshold").c_str()); ASSERT_EQ(2, result.value.positional.size()); ASSERT_STREQ("kkk", result.value.positional.at("cmd1").c_str()); ASSERT_STREQ("zzz", result.value.positional.at("cmd2").c_str()); ASSERT_EQ(2, result.value.remain.size()); ASSERT_STREQ("xxx", result.value.remain[0].c_str()); ASSERT_STREQ("vvv", result.value.remain[1].c_str()); } TEST_F(ArgumentParserTestFixture, StopParsing) { auto const result = parser.parse("program kkk -o result -- -v -t 0.7 kkk zzz xxx"); ASSERT_EQ(E_SUCCESS, result.code); ASSERT_EQ(2, result.value.optional.size()); ASSERT_STREQ("result", result.value.optional.at("output").c_str()); ASSERT_STREQ("0.5", result.value.optional.at("threshold").substr(0, 3).c_str()); ASSERT_EQ(2, result.value.positional.size()); ASSERT_STREQ("kkk", result.value.positional.at("cmd1").c_str()); ASSERT_STREQ("empty", result.value.positional.at("cmd2").c_str()); ASSERT_EQ(6, result.value.remain.size()); ASSERT_STREQ("-v", result.value.remain[0].c_str()); ASSERT_STREQ("-t", result.value.remain[1].c_str()); ASSERT_STREQ("0.7", result.value.remain[2].c_str()); ASSERT_STREQ("kkk", result.value.remain[3].c_str()); ASSERT_STREQ("zzz", result.value.remain[4].c_str()); ASSERT_STREQ("xxx", result.value.remain[5].c_str()); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SvXMLAutoCorrectImport.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:24:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_XMLAUTOCORRECTIMPORT_HXX #define _SV_XMLAUTOCORRECTIMPORT_HXX #ifndef _SVSTOR_HXX #include <sot/storage.hxx> #endif #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _MySVXACORR_HXX #include "svxacorr.hxx" #endif class SvXMLAutoCorrectImport : public SvXMLImport { protected: // This method is called after the namespace map has been updated, but // before a context for the current element has been pushed. virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); public: SvxAutocorrWordList *pAutocorr_List; SvxAutoCorrect &rAutoCorrect; com::sun::star::uno::Reference < com::sun::star::embed::XStorage > xStorage; //SvStorageRef &rStorage; // #110680# SvXMLAutoCorrectImport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, SvxAutocorrWordList *pNewAutocorr_List, SvxAutoCorrect &rNewAutoCorrect, const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rNewStorage); ~SvXMLAutoCorrectImport ( void ) throw (); }; class SvXMLWordListContext : public SvXMLImportContext { private: SvXMLAutoCorrectImport & rLocalRef; public: SvXMLWordListContext ( SvXMLAutoCorrectImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLWordListContext ( void ); }; class SvXMLWordContext : public SvXMLImportContext { private: SvXMLAutoCorrectImport & rLocalRef; public: SvXMLWordContext ( SvXMLAutoCorrectImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLWordContext ( void ); }; class SvXMLExceptionListImport : public SvXMLImport { protected: // This method is called after the namespace map has been updated, but // before a context for the current element has been pushed. virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); public: SvStringsISortDtor &rList; // #110680# SvXMLExceptionListImport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, SvStringsISortDtor & rNewList ); ~SvXMLExceptionListImport ( void ) throw (); }; class SvXMLExceptionListContext : public SvXMLImportContext { private: SvXMLExceptionListImport & rLocalRef; public: SvXMLExceptionListContext ( SvXMLExceptionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLExceptionListContext ( void ); }; class SvXMLExceptionContext : public SvXMLImportContext { private: SvXMLExceptionListImport & rLocalRef; public: SvXMLExceptionContext ( SvXMLExceptionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLExceptionContext ( void ); }; #endif <commit_msg>INTEGRATION: CWS vgbugs07 (1.9.876); FILE MERGED 2007/06/04 13:26:47 vg 1.9.876.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SvXMLAutoCorrectImport.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2007-06-27 17:53:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_XMLAUTOCORRECTIMPORT_HXX #define _SV_XMLAUTOCORRECTIMPORT_HXX #ifndef _SVSTOR_HXX #include <sot/storage.hxx> #endif #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _MySVXACORR_HXX #include <svx/svxacorr.hxx> #endif class SvXMLAutoCorrectImport : public SvXMLImport { protected: // This method is called after the namespace map has been updated, but // before a context for the current element has been pushed. virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); public: SvxAutocorrWordList *pAutocorr_List; SvxAutoCorrect &rAutoCorrect; com::sun::star::uno::Reference < com::sun::star::embed::XStorage > xStorage; //SvStorageRef &rStorage; // #110680# SvXMLAutoCorrectImport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, SvxAutocorrWordList *pNewAutocorr_List, SvxAutoCorrect &rNewAutoCorrect, const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rNewStorage); ~SvXMLAutoCorrectImport ( void ) throw (); }; class SvXMLWordListContext : public SvXMLImportContext { private: SvXMLAutoCorrectImport & rLocalRef; public: SvXMLWordListContext ( SvXMLAutoCorrectImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLWordListContext ( void ); }; class SvXMLWordContext : public SvXMLImportContext { private: SvXMLAutoCorrectImport & rLocalRef; public: SvXMLWordContext ( SvXMLAutoCorrectImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLWordContext ( void ); }; class SvXMLExceptionListImport : public SvXMLImport { protected: // This method is called after the namespace map has been updated, but // before a context for the current element has been pushed. virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); public: SvStringsISortDtor &rList; // #110680# SvXMLExceptionListImport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, SvStringsISortDtor & rNewList ); ~SvXMLExceptionListImport ( void ) throw (); }; class SvXMLExceptionListContext : public SvXMLImportContext { private: SvXMLExceptionListImport & rLocalRef; public: SvXMLExceptionListContext ( SvXMLExceptionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLExceptionListContext ( void ); }; class SvXMLExceptionContext : public SvXMLImportContext { private: SvXMLExceptionListImport & rLocalRef; public: SvXMLExceptionContext ( SvXMLExceptionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~SvXMLExceptionContext ( void ); }; #endif <|endoftext|>
<commit_before>/* Copyright 2015 Nervana Systems 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 <assert.h> #include <vector> #include <cstdio> #include <iostream> #include <chrono> #include <utility> #include <algorithm> #include "media.hpp" #include "matrix.hpp" #include "device.hpp" #include "loader.hpp" #include "batch_loader_cpio_cache.hpp" #include "sequential_batch_iterator.hpp" #include "shuffled_batch_iterator.hpp" using namespace std; DecodeThreadPool::DecodeThreadPool(int count, int batchSize, int datumSize, int datumTypeSize, int targetSize, int targetTypeSize, const std::shared_ptr<BufferPool>& in, const std::shared_ptr<BufferPool>& out, const std::shared_ptr<Device>& device, MediaParams* mediaParams) : ThreadPool(count), _itemsPerThread((batchSize - 1) / count + 1), _in(in), _out(out), _endSignaled(0), _manager(0), _stopManager(false), _managerStopped(false), _inputBuf(0), _bufferIndex(0), _batchSize(batchSize), _datumSize(datumSize), _datumTypeSize(datumTypeSize), _targetSize(targetSize), _targetTypeSize(targetTypeSize), _datumLen(datumSize * datumTypeSize), _targetLen(targetSize * targetTypeSize), _device(device) { assert(_itemsPerThread * count >= _batchSize); assert(_itemsPerThread * (count - 1) < _batchSize); for (int i = 0; i < count; i++) { _media.push_back(Media::create(mediaParams, 0, i)); _startSignaled.push_back(0); _startInds.push_back(0); _endInds.push_back(0); _dataOffsets.push_back(0); _targetOffsets.push_back(0); } } DecodeThreadPool::~DecodeThreadPool() { if (_manager != 0) { _manager->join(); delete _manager; } // The other thread objects are freed in the destructor // of the parent class. } void DecodeThreadPool::start() { for (int i = 0; i < _count; i++) { _threads.push_back(new thread(&DecodeThreadPool::run, this, i)); } _manager = new thread(&DecodeThreadPool::manage, this); } void DecodeThreadPool::stop() { ThreadPool::stop(); while (stopped() == false) { std::this_thread::yield(); _in->advanceWritePos(); _in->signalNonEmpty(); } _stopManager = true; while (_managerStopped == false) { std::this_thread::yield(); _in->advanceWritePos(); _in->signalNonEmpty(); _endSignaled++; _ended.notify_one(); } } void DecodeThreadPool::run(int id) { // Initialize worker threads by computing memory offsets for the // data this thread should work on assert(id < _count); _startInds[id] = id * _itemsPerThread; int itemCount = _itemsPerThread; if (id == _count - 1) { itemCount = _batchSize - id * _itemsPerThread; } _endInds[id] = _startInds[id] + itemCount; _dataOffsets[id] = _startInds[id] * _datumLen; _targetOffsets[id] = _startInds[id] * _targetLen; while (_done == false) { work(id); } _stopped[id] = true; } void DecodeThreadPool::work(int id) { // Thread function. { unique_lock<mutex> lock(_mutex); while (_startSignaled[id] == 0) { _started.wait(lock); if (_done == true) { return; } } _startSignaled[id]--; assert(_startSignaled[id] == 0); } int start = _startInds[id]; int end = _endInds[id]; // No locking required because threads // write into non-overlapping regions. BufferPair& outBuf = _out->getForWrite(); char* dataBuf = outBuf.first->_data + _dataOffsets[id]; char* targetBuf = outBuf.second->_data + _targetOffsets[id]; for (int i = start; i < end; i++) { // Handle the data. int itemSize = 0; char* item = _inputBuf->first->getItem(i, itemSize); if (item == 0) { return; } _media[id]->transform(item, itemSize, dataBuf, _datumLen); dataBuf += _datumLen; // Handle the targets. int targetLen = 0; char* target = _inputBuf->second->getItem(i, targetLen); memcpy(targetBuf, target, targetLen); if (_targetLen > targetLen) { // Pad the rest of the buffer with zeros. memset(targetBuf + targetLen, 0, _targetLen - targetLen); } targetBuf += _targetLen; } { lock_guard<mutex> lock(_mutex); _endSignaled++; assert(_endSignaled <= _count); } _ended.notify_one(); } void DecodeThreadPool::produce() { // Produce a minibatch. { unique_lock<mutex> lock(_out->getMutex()); while (_out->full() == true) { _out->waitForNonFull(lock); } { lock_guard<mutex> lock(_mutex); for (unsigned int i = 0; i < _startSignaled.size(); i++) { _startSignaled[i] = 1; } } _started.notify_all(); { unique_lock<mutex> lock(_mutex); while (_endSignaled < _count) { _ended.wait(lock); } _endSignaled = 0; } // At this point, we have decoded data for the whole minibatch. BufferPair& outBuf = _out->getForWrite(); Matrix::transpose(outBuf.first->_data, _batchSize, _datumSize, _datumTypeSize); Matrix::transpose(outBuf.second->_data, _batchSize, _targetSize, _targetTypeSize); // Copy to device. _device->copyData(_bufferIndex, outBuf.first->_data, outBuf.first->_size); _device->copyLabels(_bufferIndex, outBuf.second->_data, outBuf.second->_size); _bufferIndex = (_bufferIndex == 0) ? 1 : 0; _out->advanceWritePos(); } _out->signalNonEmpty(); } void DecodeThreadPool::consume() { // Consume an input buffer. { unique_lock<mutex> lock(_in->getMutex()); while (_in->empty() == true) { _in->waitForNonEmpty(lock); if (_stopManager == true) { return; } } _inputBuf = &_in->getForRead(); produce(); _in->advanceReadPos(); } _in->signalNonFull(); } void DecodeThreadPool::manage() { // Thread function. int result = _device->init(); if (result != 0) { _stopManager = true; } while (_stopManager == false) { consume(); } _managerStopped = true; } ReadThread::ReadThread(const shared_ptr<BufferPool>& out, const shared_ptr<BatchIterator>& batch_iterator) : ThreadPool(1), _out(out), _batch_iterator(batch_iterator) { assert(_count == 1); } void ReadThread::work(int id) { // Fill input buffers. // TODO: make sure this locking still makes sense with new // BatchIterator { unique_lock<mutex> lock(_out->getMutex()); while (_out->full() == true) { _out->waitForNonFull(lock); } _batch_iterator->read(_out->getForWrite()); _out->advanceWritePos(); } _out->signalNonEmpty(); } Loader::Loader(int* itemCount, int batchSize, const char* repoDir, const char* archiveDir, const char* indexFile, const char* archivePrefix, bool shuffle, bool reshuffle, int datumSize, int datumTypeSize, int targetSize, int targetTypeSize, int subsetPercent, MediaParams* mediaParams, DeviceParams* deviceParams, const char* manifestFilename, const char* rootCacheDir) : _first(true), _batchSize(batchSize), _datumSize(datumSize), _datumTypeSize(datumTypeSize), _targetSize(targetSize), _targetTypeSize(targetTypeSize), _readBufs(nullptr), _decodeBufs(nullptr), _readThread(nullptr), _decodeThreads(nullptr), _device(nullptr), _batch_iterator(nullptr), _mediaParams(mediaParams) { // TODO: rename to shuffleManifest and shuffleEveryEpoch // TODO: not a constant uint _macroBatchSize = 1024; // TODO: not a constant uint _seed = 0; _device = Device::create(deviceParams); // the manifest defines which data should be included in the dataset auto manifest = shared_ptr<Manifest>(new Manifest(manifestFilename, shuffle)); *itemCount = manifest->getSize(); // build cacheDir from rootCacheDir and a hash of the manifest stringstream cacheDirStream; cacheDirStream << rootCacheDir << '/' << manifest->hash(); string cacheDir = cacheDirStream.str(); // batch loader provdes random access to blocks of data in the manifest auto batchLoader = shared_ptr<BatchLoaderCPIOCache>(new BatchLoaderCPIOCache( cacheDir.c_str(), shared_ptr<BatchFileLoader>(new BatchFileLoader( manifest, subsetPercent )) )); // _batch_iterator provides an unending iterator (shuffled or not) over // the batchLoader if(reshuffle) { _batch_iterator = shared_ptr<ShuffledBatchIterator>(new ShuffledBatchIterator( batchLoader, _macroBatchSize, _seed )); } else { _batch_iterator = shared_ptr<SequentialBatchIterator>(new SequentialBatchIterator( batchLoader, _macroBatchSize )); } } Loader::~Loader() { } int Loader::start() { _first = true; try { int dataLen = _batchSize * _datumSize * _datumTypeSize; int targetLen = _batchSize * _targetSize * _targetTypeSize; // Start the read buffers off with a reasonable size. They will // get resized as needed. _readBufs = shared_ptr<BufferPool>(new BufferPool(dataLen / 8, targetLen)); _readThread = unique_ptr<ReadThread>(new ReadThread(_readBufs, _batch_iterator)); bool pinned = (_device->_type != CPU); _decodeBufs = shared_ptr<BufferPool>(new BufferPool(dataLen, targetLen, pinned)); int numCores = thread::hardware_concurrency(); int itemsPerThread = (_batchSize - 1) / numCores + 1; int threadCount = (_batchSize - 1) / itemsPerThread + 1; threadCount = std::min(threadCount, _batchSize); _decodeThreads = unique_ptr<DecodeThreadPool>(new DecodeThreadPool(threadCount, _batchSize, _datumSize, _datumTypeSize, _targetSize, _targetTypeSize, _readBufs, _decodeBufs, _device, _mediaParams)); } catch(std::bad_alloc&) { return -1; } _decodeThreads->start(); _readThread->start(); return 0; } void Loader::stop() { _readThread->stop(); while (_readThread->stopped() == false) { std::this_thread::yield(); drain(); } while ((_decodeBufs->empty() == false) || (_readBufs->empty() == false)) { drain(); } _decodeThreads->stop(); _readBufs = nullptr; _readThread = nullptr; _decodeBufs = nullptr; _decodeThreads = nullptr; } int Loader::reset() { stop(); _batch_iterator->reset(); start(); return 0; } void Loader::next(Buffer* dataBuf, Buffer* targetsBuf) { // Copy minibatch data into the buffers passed in. // Only used for testing purposes. { unique_lock<mutex> lock(_decodeBufs->getMutex()); while (_decodeBufs->empty()) { _decodeBufs->waitForNonEmpty(lock); } Buffer* data = _decodeBufs->getForRead().first; memcpy(dataBuf->_data, data->_data, dataBuf->_size); Buffer* targets = _decodeBufs->getForRead().second; memcpy(targetsBuf->_data, targets->_data, targetsBuf->_size); _decodeBufs->advanceReadPos(); } _decodeBufs->signalNonFull(); } void Loader::next() { unique_lock<mutex> lock(_decodeBufs->getMutex()); if (_first == true) { _first = false; } else { // Unlock the buffer used for the previous minibatch. _decodeBufs->advanceReadPos(); _decodeBufs->signalNonFull(); } while (_decodeBufs->empty()) { _decodeBufs->waitForNonEmpty(lock); } } std::shared_ptr<BatchIterator> Loader::getBatchIterator() { return _batch_iterator; } std::shared_ptr<Device> Loader::getDevice() { return _device; } void Loader::drain() { { unique_lock<mutex> lock(_decodeBufs->getMutex()); if (_decodeBufs->empty() == true) { return; } _decodeBufs->advanceReadPos(); } _decodeBufs->signalNonFull(); } <commit_msg>replace shared_ptr with make_shared<commit_after>/* Copyright 2015 Nervana Systems 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 <assert.h> #include <vector> #include <cstdio> #include <iostream> #include <chrono> #include <utility> #include <algorithm> #include "media.hpp" #include "matrix.hpp" #include "device.hpp" #include "loader.hpp" #include "batch_loader_cpio_cache.hpp" #include "sequential_batch_iterator.hpp" #include "shuffled_batch_iterator.hpp" using namespace std; DecodeThreadPool::DecodeThreadPool(int count, int batchSize, int datumSize, int datumTypeSize, int targetSize, int targetTypeSize, const std::shared_ptr<BufferPool>& in, const std::shared_ptr<BufferPool>& out, const std::shared_ptr<Device>& device, MediaParams* mediaParams) : ThreadPool(count), _itemsPerThread((batchSize - 1) / count + 1), _in(in), _out(out), _endSignaled(0), _manager(0), _stopManager(false), _managerStopped(false), _inputBuf(0), _bufferIndex(0), _batchSize(batchSize), _datumSize(datumSize), _datumTypeSize(datumTypeSize), _targetSize(targetSize), _targetTypeSize(targetTypeSize), _datumLen(datumSize * datumTypeSize), _targetLen(targetSize * targetTypeSize), _device(device) { assert(_itemsPerThread * count >= _batchSize); assert(_itemsPerThread * (count - 1) < _batchSize); for (int i = 0; i < count; i++) { _media.push_back(Media::create(mediaParams, 0, i)); _startSignaled.push_back(0); _startInds.push_back(0); _endInds.push_back(0); _dataOffsets.push_back(0); _targetOffsets.push_back(0); } } DecodeThreadPool::~DecodeThreadPool() { if (_manager != 0) { _manager->join(); delete _manager; } // The other thread objects are freed in the destructor // of the parent class. } void DecodeThreadPool::start() { for (int i = 0; i < _count; i++) { _threads.push_back(new thread(&DecodeThreadPool::run, this, i)); } _manager = new thread(&DecodeThreadPool::manage, this); } void DecodeThreadPool::stop() { ThreadPool::stop(); while (stopped() == false) { std::this_thread::yield(); _in->advanceWritePos(); _in->signalNonEmpty(); } _stopManager = true; while (_managerStopped == false) { std::this_thread::yield(); _in->advanceWritePos(); _in->signalNonEmpty(); _endSignaled++; _ended.notify_one(); } } void DecodeThreadPool::run(int id) { // Initialize worker threads by computing memory offsets for the // data this thread should work on assert(id < _count); _startInds[id] = id * _itemsPerThread; int itemCount = _itemsPerThread; if (id == _count - 1) { itemCount = _batchSize - id * _itemsPerThread; } _endInds[id] = _startInds[id] + itemCount; _dataOffsets[id] = _startInds[id] * _datumLen; _targetOffsets[id] = _startInds[id] * _targetLen; while (_done == false) { work(id); } _stopped[id] = true; } void DecodeThreadPool::work(int id) { // Thread function. { unique_lock<mutex> lock(_mutex); while (_startSignaled[id] == 0) { _started.wait(lock); if (_done == true) { return; } } _startSignaled[id]--; assert(_startSignaled[id] == 0); } int start = _startInds[id]; int end = _endInds[id]; // No locking required because threads // write into non-overlapping regions. BufferPair& outBuf = _out->getForWrite(); char* dataBuf = outBuf.first->_data + _dataOffsets[id]; char* targetBuf = outBuf.second->_data + _targetOffsets[id]; for (int i = start; i < end; i++) { // Handle the data. int itemSize = 0; char* item = _inputBuf->first->getItem(i, itemSize); if (item == 0) { return; } _media[id]->transform(item, itemSize, dataBuf, _datumLen); dataBuf += _datumLen; // Handle the targets. int targetLen = 0; char* target = _inputBuf->second->getItem(i, targetLen); memcpy(targetBuf, target, targetLen); if (_targetLen > targetLen) { // Pad the rest of the buffer with zeros. memset(targetBuf + targetLen, 0, _targetLen - targetLen); } targetBuf += _targetLen; } { lock_guard<mutex> lock(_mutex); _endSignaled++; assert(_endSignaled <= _count); } _ended.notify_one(); } void DecodeThreadPool::produce() { // Produce a minibatch. { unique_lock<mutex> lock(_out->getMutex()); while (_out->full() == true) { _out->waitForNonFull(lock); } { lock_guard<mutex> lock(_mutex); for (unsigned int i = 0; i < _startSignaled.size(); i++) { _startSignaled[i] = 1; } } _started.notify_all(); { unique_lock<mutex> lock(_mutex); while (_endSignaled < _count) { _ended.wait(lock); } _endSignaled = 0; } // At this point, we have decoded data for the whole minibatch. BufferPair& outBuf = _out->getForWrite(); Matrix::transpose(outBuf.first->_data, _batchSize, _datumSize, _datumTypeSize); Matrix::transpose(outBuf.second->_data, _batchSize, _targetSize, _targetTypeSize); // Copy to device. _device->copyData(_bufferIndex, outBuf.first->_data, outBuf.first->_size); _device->copyLabels(_bufferIndex, outBuf.second->_data, outBuf.second->_size); _bufferIndex = (_bufferIndex == 0) ? 1 : 0; _out->advanceWritePos(); } _out->signalNonEmpty(); } void DecodeThreadPool::consume() { // Consume an input buffer. { unique_lock<mutex> lock(_in->getMutex()); while (_in->empty() == true) { _in->waitForNonEmpty(lock); if (_stopManager == true) { return; } } _inputBuf = &_in->getForRead(); produce(); _in->advanceReadPos(); } _in->signalNonFull(); } void DecodeThreadPool::manage() { // Thread function. int result = _device->init(); if (result != 0) { _stopManager = true; } while (_stopManager == false) { consume(); } _managerStopped = true; } ReadThread::ReadThread(const shared_ptr<BufferPool>& out, const shared_ptr<BatchIterator>& batch_iterator) : ThreadPool(1), _out(out), _batch_iterator(batch_iterator) { assert(_count == 1); } void ReadThread::work(int id) { // Fill input buffers. // TODO: make sure this locking still makes sense with new // BatchIterator { unique_lock<mutex> lock(_out->getMutex()); while (_out->full() == true) { _out->waitForNonFull(lock); } _batch_iterator->read(_out->getForWrite()); _out->advanceWritePos(); } _out->signalNonEmpty(); } Loader::Loader(int* itemCount, int batchSize, const char* repoDir, const char* archiveDir, const char* indexFile, const char* archivePrefix, bool shuffle, bool reshuffle, int datumSize, int datumTypeSize, int targetSize, int targetTypeSize, int subsetPercent, MediaParams* mediaParams, DeviceParams* deviceParams, const char* manifestFilename, const char* rootCacheDir) : _first(true), _batchSize(batchSize), _datumSize(datumSize), _datumTypeSize(datumTypeSize), _targetSize(targetSize), _targetTypeSize(targetTypeSize), _readBufs(nullptr), _decodeBufs(nullptr), _readThread(nullptr), _decodeThreads(nullptr), _device(nullptr), _batch_iterator(nullptr), _mediaParams(mediaParams) { // TODO: rename to shuffleManifest and shuffleEveryEpoch // TODO: not a constant uint _macroBatchSize = 1024; // TODO: not a constant uint _seed = 0; _device = Device::create(deviceParams); // the manifest defines which data should be included in the dataset auto manifest = make_shared<Manifest>(manifestFilename, shuffle); *itemCount = manifest->getSize(); // build cacheDir from rootCacheDir and a hash of the manifest stringstream cacheDirStream; cacheDirStream << rootCacheDir << '/' << manifest->hash(); string cacheDir = cacheDirStream.str(); // batch loader provdes random access to blocks of data in the manifest auto batchLoader = make_shared<BatchLoaderCPIOCache>( cacheDir.c_str(), make_shared<BatchFileLoader>(manifest, subsetPercent) ); // _batch_iterator provides an unending iterator (shuffled or not) over // the batchLoader if(reshuffle) { _batch_iterator = make_shared<ShuffledBatchIterator>( batchLoader, _macroBatchSize, _seed ); } else { _batch_iterator = make_shared<SequentialBatchIterator>( batchLoader, _macroBatchSize ); } } Loader::~Loader() { } int Loader::start() { _first = true; try { int dataLen = _batchSize * _datumSize * _datumTypeSize; int targetLen = _batchSize * _targetSize * _targetTypeSize; // Start the read buffers off with a reasonable size. They will // get resized as needed. _readBufs = make_shared<BufferPool>(dataLen / 8, targetLen); _readThread = unique_ptr<ReadThread>(new ReadThread(_readBufs, _batch_iterator)); bool pinned = (_device->_type != CPU); _decodeBufs = make_shared<BufferPool>(dataLen, targetLen, pinned); int numCores = thread::hardware_concurrency(); int itemsPerThread = (_batchSize - 1) / numCores + 1; int threadCount = (_batchSize - 1) / itemsPerThread + 1; threadCount = std::min(threadCount, _batchSize); _decodeThreads = unique_ptr<DecodeThreadPool>(new DecodeThreadPool(threadCount, _batchSize, _datumSize, _datumTypeSize, _targetSize, _targetTypeSize, _readBufs, _decodeBufs, _device, _mediaParams)); } catch(std::bad_alloc&) { return -1; } _decodeThreads->start(); _readThread->start(); return 0; } void Loader::stop() { _readThread->stop(); while (_readThread->stopped() == false) { std::this_thread::yield(); drain(); } while ((_decodeBufs->empty() == false) || (_readBufs->empty() == false)) { drain(); } _decodeThreads->stop(); _readBufs = nullptr; _readThread = nullptr; _decodeBufs = nullptr; _decodeThreads = nullptr; } int Loader::reset() { stop(); _batch_iterator->reset(); start(); return 0; } void Loader::next(Buffer* dataBuf, Buffer* targetsBuf) { // Copy minibatch data into the buffers passed in. // Only used for testing purposes. { unique_lock<mutex> lock(_decodeBufs->getMutex()); while (_decodeBufs->empty()) { _decodeBufs->waitForNonEmpty(lock); } Buffer* data = _decodeBufs->getForRead().first; memcpy(dataBuf->_data, data->_data, dataBuf->_size); Buffer* targets = _decodeBufs->getForRead().second; memcpy(targetsBuf->_data, targets->_data, targetsBuf->_size); _decodeBufs->advanceReadPos(); } _decodeBufs->signalNonFull(); } void Loader::next() { unique_lock<mutex> lock(_decodeBufs->getMutex()); if (_first == true) { _first = false; } else { // Unlock the buffer used for the previous minibatch. _decodeBufs->advanceReadPos(); _decodeBufs->signalNonFull(); } while (_decodeBufs->empty()) { _decodeBufs->waitForNonEmpty(lock); } } std::shared_ptr<BatchIterator> Loader::getBatchIterator() { return _batch_iterator; } std::shared_ptr<Device> Loader::getDevice() { return _device; } void Loader::drain() { { unique_lock<mutex> lock(_decodeBufs->getMutex()); if (_decodeBufs->empty() == true) { return; } _decodeBufs->advanceReadPos(); } _decodeBufs->signalNonFull(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_SD_SOURCE_UI_INC_FUTEXT_HXX #define INCLUDED_SD_SOURCE_UI_INC_FUTEXT_HXX #include <editeng/editdata.hxx> #include "fuconstr.hxx" #include <svx/svdotext.hxx> struct StyleRequestData; class SdrTextObj; class FontList; class OutlinerView; namespace sd { /** * Base class for text functions */ class FuText : public FuConstruct { public: TYPEINFO_OVERRIDE(); static rtl::Reference<FuPoor> Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ); virtual void DoExecute( SfxRequest& rReq ) SAL_OVERRIDE; virtual bool KeyInput(const KeyEvent& rKEvt) SAL_OVERRIDE; virtual bool MouseMove(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual bool MouseButtonUp(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual bool MouseButtonDown(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual bool Command(const CommandEvent& rCEvt) SAL_OVERRIDE; virtual bool RequestHelp(const HelpEvent& rHEvt) SAL_OVERRIDE; virtual void ReceiveRequest(SfxRequest& rReq) SAL_OVERRIDE; virtual void DoubleClick(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual void Activate() SAL_OVERRIDE; ///< activates the function virtual void Deactivate() SAL_OVERRIDE; ///< deactivates the function void SetInEditMode(const MouseEvent& rMEvt, bool bQuickDrag); bool DeleteDefaultText(); SdrTextObj* GetTextObj() { return static_cast< SdrTextObj* >( mxTextObj.get() ); } virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle) SAL_OVERRIDE; /** is called when the current function should be aborted. <p> This is used when a function gets a KEY_ESCAPE but can also be called directly. @returns true if a active function was aborted */ virtual bool cancel() SAL_OVERRIDE; static void ChangeFontSize( bool, OutlinerView*, const FontList*, ::sd::View* ); protected: FuText (ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); virtual void disposing() SAL_OVERRIDE; SdrObjectWeakRef mxTextObj; Link<> aOldLink; bool bFirstObjCreated; bool bJustEndedEdit; SfxRequest& rRequest; private: void ImpSetAttributesForNewTextObject(SdrTextObj* pTxtObj); void ImpSetAttributesFitToSize(SdrTextObj* pTxtObj); void ImpSetAttributesFitToSizeVertical(SdrTextObj* pTxtObj); void ImpSetAttributesFitCommon(SdrTextObj* pTxtObj); }; } // end of namespace sd #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Make more FuText members private<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_SD_SOURCE_UI_INC_FUTEXT_HXX #define INCLUDED_SD_SOURCE_UI_INC_FUTEXT_HXX #include <editeng/editdata.hxx> #include "fuconstr.hxx" #include <svx/svdotext.hxx> struct StyleRequestData; class SdrTextObj; class FontList; class OutlinerView; namespace sd { /** * Base class for text functions */ class FuText : public FuConstruct { public: TYPEINFO_OVERRIDE(); static rtl::Reference<FuPoor> Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ); virtual void DoExecute( SfxRequest& rReq ) SAL_OVERRIDE; virtual bool KeyInput(const KeyEvent& rKEvt) SAL_OVERRIDE; virtual bool MouseMove(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual bool MouseButtonUp(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual bool MouseButtonDown(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual bool Command(const CommandEvent& rCEvt) SAL_OVERRIDE; virtual bool RequestHelp(const HelpEvent& rHEvt) SAL_OVERRIDE; virtual void ReceiveRequest(SfxRequest& rReq) SAL_OVERRIDE; virtual void DoubleClick(const MouseEvent& rMEvt) SAL_OVERRIDE; virtual void Activate() SAL_OVERRIDE; ///< activates the function virtual void Deactivate() SAL_OVERRIDE; ///< deactivates the function void SetInEditMode(const MouseEvent& rMEvt, bool bQuickDrag); bool DeleteDefaultText(); SdrTextObj* GetTextObj() { return static_cast< SdrTextObj* >( mxTextObj.get() ); } virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle) SAL_OVERRIDE; /** is called when the current function should be aborted. <p> This is used when a function gets a KEY_ESCAPE but can also be called directly. @returns true if a active function was aborted */ virtual bool cancel() SAL_OVERRIDE; static void ChangeFontSize( bool, OutlinerView*, const FontList*, ::sd::View* ); protected: FuText (ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); private: virtual void disposing() SAL_OVERRIDE; SdrObjectWeakRef mxTextObj; bool bFirstObjCreated; bool bJustEndedEdit; SfxRequest& rRequest; void ImpSetAttributesForNewTextObject(SdrTextObj* pTxtObj); void ImpSetAttributesFitToSize(SdrTextObj* pTxtObj); void ImpSetAttributesFitToSizeVertical(SdrTextObj* pTxtObj); void ImpSetAttributesFitCommon(SdrTextObj* pTxtObj); }; } // end of namespace sd #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optdlg.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:45:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_OPTDLG_HXX #define SD_OPTDLG_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _PRESENTATION_HXX #include "pres.hxx" #endif class SfxItemSet; class SdOptionsDlg : public SfxTabDialog { private: DocumentType meDocType; public: SdOptionsDlg( Window* pParent, const SfxItemSet& rInAttrs, DocumentType eDocType ); ~SdOptionsDlg(); protected: virtual void PageCreated( USHORT nId, SfxTabPage &rPage ); // virtual SfxItemSet* CreateInputItemSet( USHORT nPageId ); }; #endif // SD_OPTDLG_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.298); FILE MERGED 2008/04/01 15:35:28 thb 1.3.298.3: #i85898# Stripping all external header guards 2008/04/01 12:39:08 thb 1.3.298.2: #i85898# Stripping all external header guards 2008/03/31 13:58:16 rt 1.3.298.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optdlg.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SD_OPTDLG_HXX #define SD_OPTDLG_HXX #include <sfx2/tabdlg.hxx> #include "pres.hxx" class SfxItemSet; class SdOptionsDlg : public SfxTabDialog { private: DocumentType meDocType; public: SdOptionsDlg( Window* pParent, const SfxItemSet& rInAttrs, DocumentType eDocType ); ~SdOptionsDlg(); protected: virtual void PageCreated( USHORT nId, SfxTabPage &rPage ); // virtual SfxItemSet* CreateInputItemSet( USHORT nPageId ); }; #endif // SD_OPTDLG_HXX <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "manager/stmgr-server.h" #include <iostream> #include <unordered_set> #include <string> #include <vector> #include "manager/stmgr.h" #include "proto/messages.h" #include "basics/basics.h" #include "errors/errors.h" #include "threads/threads.h" #include "network/network.h" #include "config/helper.h" #include "config/heron-internals-config-reader.h" #include "metrics/metrics.h" namespace heron { namespace stmgr { // The scope the metrics in this file are under const sp_string SERVER_SCOPE = "__server/"; // Num data tuples received from other stream managers const sp_string METRIC_DATA_TUPLES_FROM_STMGRS = "__tuples_from_stmgrs"; // Num ack tuples received from other stream managers const sp_string METRIC_ACK_TUPLES_FROM_STMGRS = "__ack_tuples_from_stmgrs"; // Num fail tuples received from other stream managers const sp_string METRIC_FAIL_TUPLES_FROM_STMGRS = "__fail_tuples_from_stmgrs"; // Bytes received from other stream managers const sp_string METRIC_BYTES_FROM_STMGRS = "__bytes_from_stmgrs"; StMgrServer::StMgrServer(EventLoop* eventLoop, const NetworkOptions& _options, const sp_string& _topology_name, const sp_string& _topology_id, const sp_string& _stmgr_id, StMgr* _stmgr, heron::common::MetricsMgrSt* _metrics_manager_client) : Server(eventLoop, _options), topology_name_(_topology_name), topology_id_(_topology_id), stmgr_id_(_stmgr_id), stmgr_(_stmgr), metrics_manager_client_(_metrics_manager_client) { // stmgr related handlers InstallRequestHandler(&StMgrServer::HandleStMgrHelloRequest); InstallMessageHandler(&StMgrServer::HandleTupleStreamMessage); InstallMessageHandler(&StMgrServer::HandleStartBackPressureMessage); InstallMessageHandler(&StMgrServer::HandleStopBackPressureMessage); InstallMessageHandler(&StMgrServer::HandleDownstreamStatefulCheckpointMessage); // The metrics need to be registered one by one here because the "__server" scope // is already registered in heron::stmgr::InstanceServer. Duplicated registrations // will only have one successfully registered. tuples_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_DATA_TUPLES_FROM_STMGRS, tuples_from_stmgrs_metrics_); ack_tuples_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_ACK_TUPLES_FROM_STMGRS, ack_tuples_from_stmgrs_metrics_); fail_tuples_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_FAIL_TUPLES_FROM_STMGRS, fail_tuples_from_stmgrs_metrics_); bytes_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_BYTES_FROM_STMGRS, bytes_from_stmgrs_metrics_); } StMgrServer::~StMgrServer() { Stop(); metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_DATA_TUPLES_FROM_STMGRS); delete tuples_from_stmgrs_metrics_; metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_ACK_TUPLES_FROM_STMGRS); delete ack_tuples_from_stmgrs_metrics_; metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_FAIL_TUPLES_FROM_STMGRS); delete fail_tuples_from_stmgrs_metrics_; metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_BYTES_FROM_STMGRS); delete bytes_from_stmgrs_metrics_; } void StMgrServer::HandleNewConnection(Connection* _conn) { // There is nothing to be done here. Instead we wait // for the register/hello LOG(INFO) << "StMgrServer Got new connection " << _conn << " from " << _conn->getIPAddress() << ":" << _conn->getPort(); } void StMgrServer::HandleConnectionClose(Connection* _conn, NetworkErrorCode) { LOG(INFO) << "StMgrServer Got connection close of " << _conn << " from " << _conn->getIPAddress() << ":" << _conn->getPort(); // Find the stmgr who hung up auto siter = rstmgrs_.find(_conn); if (siter == rstmgrs_.end()) { LOG(ERROR) << "StMgrServer could not identity connection " << _conn << " from " << _conn->getIPAddress() << ":" << _conn->getPort(); return; } // This is a stmgr connection LOG(INFO) << "Stmgr " << siter->second << " closed connection"; sp_string stmgr_id = rstmgrs_[_conn]; // Did we receive a start back pressure message from this stmgr to // begin with? if (stmgrs_who_announced_back_pressure_.find(stmgr_id) != stmgrs_who_announced_back_pressure_.end()) { stmgrs_who_announced_back_pressure_.erase(stmgr_id); if (stmgrs_who_announced_back_pressure_.empty()) { stmgr_->AttemptStopBackPressureFromSpouts(); } } // Now cleanup the data structures stmgrs_.erase(siter->second); rstmgrs_.erase(_conn); } void StMgrServer::HandleStMgrHelloRequest(REQID _id, Connection* _conn, proto::stmgr::StrMgrHelloRequest* _request) { LOG(INFO) << "Got a hello message from stmgr " << _request->stmgr() << " on connection " << _conn; proto::stmgr::StrMgrHelloResponse response; // Some basic checks if (_request->topology_name() != topology_name_) { LOG(ERROR) << "The hello message was from a different topology " << _request->topology_name() << std::endl; response.mutable_status()->set_status(proto::system::NOTOK); } else if (_request->topology_id() != topology_id_) { LOG(ERROR) << "The hello message was from a different topology id " << _request->topology_id() << std::endl; response.mutable_status()->set_status(proto::system::NOTOK); } else if (stmgrs_.find(_request->stmgr()) != stmgrs_.end()) { LOG(WARNING) << "We already had an active connection from the stmgr " << _request->stmgr() << ". Closing existing connection..."; // This will free up the slot in the various maps in this class // and the next time around we'll be able to add this stmgr. // We shouldn't add the new stmgr connection right now because // the close could be asynchronous (fired through a 0 timer) stmgrs_[_request->stmgr()]->closeConnection(); response.mutable_status()->set_status(proto::system::NOTOK); } else { stmgrs_[_request->stmgr()] = _conn; rstmgrs_[_conn] = _request->stmgr(); response.mutable_status()->set_status(proto::system::OK); } SendResponse(_id, _conn, response); delete _request; } void StMgrServer::HandleTupleStreamMessage(Connection* _conn, proto::stmgr::TupleStreamMessage* _message) { auto iter = rstmgrs_.find(_conn); if (iter == rstmgrs_.end()) { LOG(INFO) << "Recieved Tuple messages from unknown streammanager connection"; __global_protobuf_pool_release__(_message); } else { proto::system::HeronTupleSet2* tuple_set = nullptr; tuple_set = __global_protobuf_pool_acquire__(tuple_set); tuple_set->ParsePartialFromString(_message->set()); bytes_from_stmgrs_metrics_->incr_by(_message->ByteSize()); if (tuple_set->has_data()) { tuples_from_stmgrs_metrics_->incr_by(tuple_set->data().tuples_size()); } else if (tuple_set->has_control()) { ack_tuples_from_stmgrs_metrics_->incr_by(tuple_set->control().acks_size()); fail_tuples_from_stmgrs_metrics_->incr_by(tuple_set->control().fails_size()); } stmgr_->HandleStreamManagerData(iter->second, _message); } } void StMgrServer::StartBackPressureClientCb(const sp_string& _other_stmgr_id) { if (!stmgr_->DidAnnounceBackPressure()) { stmgr_->SendStartBackPressureToOtherStMgrs(); } remote_ends_who_caused_back_pressure_.insert(_other_stmgr_id); LOG(INFO) << "We observe back pressure on sending data to remote stream manager " << _other_stmgr_id; stmgr_->StartBackPressureOnSpouts(); } void StMgrServer::StopBackPressureClientCb(const sp_string& _other_stmgr_id) { CHECK(remote_ends_who_caused_back_pressure_.find(_other_stmgr_id) != remote_ends_who_caused_back_pressure_.end()); remote_ends_who_caused_back_pressure_.erase(_other_stmgr_id); if (!stmgr_->DidAnnounceBackPressure()) { stmgr_->SendStopBackPressureToOtherStMgrs(); } LOG(INFO) << "We don't observe back pressure now on sending data to remote " "stream manager " << _other_stmgr_id; if (!stmgr_->DidAnnounceBackPressure() && !stmgr_->DidOthersAnnounceBackPressure()) { stmgr_->AttemptStopBackPressureFromSpouts(); } } void StMgrServer::HandleStartBackPressureMessage(Connection* _conn, proto::stmgr::StartBackPressureMessage* _message) { // Close spouts LOG(INFO) << "Received start back pressure from str mgr " << _message->stmgr(); if (_message->topology_name() != topology_name_ || _message->topology_id() != topology_id_) { LOG(ERROR) << "Received start back pressure message from unknown stream manager " << _message->topology_name() << " " << _message->topology_id() << " " << _message->stmgr() << " " << _message->message_id(); __global_protobuf_pool_release__(_message); return; } auto iter = rstmgrs_.find(_conn); CHECK(iter != rstmgrs_.end()); sp_string stmgr_id = iter->second; stmgrs_who_announced_back_pressure_.insert(stmgr_id); stmgr_->StartBackPressureOnSpouts(); __global_protobuf_pool_release__(_message); } void StMgrServer::HandleStopBackPressureMessage(Connection* _conn, proto::stmgr::StopBackPressureMessage* _message) { LOG(INFO) << "Received stop back pressure from str mgr " << _message->stmgr(); if (_message->topology_name() != topology_name_ || _message->topology_id() != topology_id_) { LOG(ERROR) << "Received stop back pressure message from unknown stream manager " << _message->topology_name() << " " << _message->topology_id() << " " << _message->stmgr(); __global_protobuf_pool_release__(_message); return; } auto iter = rstmgrs_.find(_conn); CHECK(iter != rstmgrs_.end()); sp_string stmgr_id = iter->second; // Did we receive a start back pressure message from this stmgr to // begin with? We could have been dead at the time of the announcement if (stmgrs_who_announced_back_pressure_.find(stmgr_id) != stmgrs_who_announced_back_pressure_.end()) { stmgrs_who_announced_back_pressure_.erase(stmgr_id); } if (!stmgr_->DidAnnounceBackPressure() && !stmgr_->DidOthersAnnounceBackPressure()) { stmgr_->AttemptStopBackPressureFromSpouts(); } __global_protobuf_pool_release__(_message); } void StMgrServer::HandleDownstreamStatefulCheckpointMessage(Connection* _conn, proto::ckptmgr::DownstreamStatefulCheckpoint* _message) { stmgr_->HandleDownStreamStatefulCheckpoint(*_message); __global_protobuf_pool_release__(_message); } } // namespace stmgr } // namespace heron <commit_msg>Fix memory leak in stmgr when measuring tuple data size (#3175)<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "manager/stmgr-server.h" #include <iostream> #include <unordered_set> #include <string> #include <vector> #include "manager/stmgr.h" #include "proto/messages.h" #include "basics/basics.h" #include "errors/errors.h" #include "threads/threads.h" #include "network/network.h" #include "config/helper.h" #include "config/heron-internals-config-reader.h" #include "metrics/metrics.h" namespace heron { namespace stmgr { // The scope the metrics in this file are under const sp_string SERVER_SCOPE = "__server/"; // Num data tuples received from other stream managers const sp_string METRIC_DATA_TUPLES_FROM_STMGRS = "__tuples_from_stmgrs"; // Num ack tuples received from other stream managers const sp_string METRIC_ACK_TUPLES_FROM_STMGRS = "__ack_tuples_from_stmgrs"; // Num fail tuples received from other stream managers const sp_string METRIC_FAIL_TUPLES_FROM_STMGRS = "__fail_tuples_from_stmgrs"; // Bytes received from other stream managers const sp_string METRIC_BYTES_FROM_STMGRS = "__bytes_from_stmgrs"; StMgrServer::StMgrServer(EventLoop* eventLoop, const NetworkOptions& _options, const sp_string& _topology_name, const sp_string& _topology_id, const sp_string& _stmgr_id, StMgr* _stmgr, heron::common::MetricsMgrSt* _metrics_manager_client) : Server(eventLoop, _options), topology_name_(_topology_name), topology_id_(_topology_id), stmgr_id_(_stmgr_id), stmgr_(_stmgr), metrics_manager_client_(_metrics_manager_client) { // stmgr related handlers InstallRequestHandler(&StMgrServer::HandleStMgrHelloRequest); InstallMessageHandler(&StMgrServer::HandleTupleStreamMessage); InstallMessageHandler(&StMgrServer::HandleStartBackPressureMessage); InstallMessageHandler(&StMgrServer::HandleStopBackPressureMessage); InstallMessageHandler(&StMgrServer::HandleDownstreamStatefulCheckpointMessage); // The metrics need to be registered one by one here because the "__server" scope // is already registered in heron::stmgr::InstanceServer. Duplicated registrations // will only have one successfully registered. tuples_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_DATA_TUPLES_FROM_STMGRS, tuples_from_stmgrs_metrics_); ack_tuples_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_ACK_TUPLES_FROM_STMGRS, ack_tuples_from_stmgrs_metrics_); fail_tuples_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_FAIL_TUPLES_FROM_STMGRS, fail_tuples_from_stmgrs_metrics_); bytes_from_stmgrs_metrics_ = new heron::common::CountMetric(); metrics_manager_client_->register_metric(SERVER_SCOPE + METRIC_BYTES_FROM_STMGRS, bytes_from_stmgrs_metrics_); } StMgrServer::~StMgrServer() { Stop(); metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_DATA_TUPLES_FROM_STMGRS); delete tuples_from_stmgrs_metrics_; metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_ACK_TUPLES_FROM_STMGRS); delete ack_tuples_from_stmgrs_metrics_; metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_FAIL_TUPLES_FROM_STMGRS); delete fail_tuples_from_stmgrs_metrics_; metrics_manager_client_->unregister_metric(SERVER_SCOPE + METRIC_BYTES_FROM_STMGRS); delete bytes_from_stmgrs_metrics_; } void StMgrServer::HandleNewConnection(Connection* _conn) { // There is nothing to be done here. Instead we wait // for the register/hello LOG(INFO) << "StMgrServer Got new connection " << _conn << " from " << _conn->getIPAddress() << ":" << _conn->getPort(); } void StMgrServer::HandleConnectionClose(Connection* _conn, NetworkErrorCode) { LOG(INFO) << "StMgrServer Got connection close of " << _conn << " from " << _conn->getIPAddress() << ":" << _conn->getPort(); // Find the stmgr who hung up auto siter = rstmgrs_.find(_conn); if (siter == rstmgrs_.end()) { LOG(ERROR) << "StMgrServer could not identity connection " << _conn << " from " << _conn->getIPAddress() << ":" << _conn->getPort(); return; } // This is a stmgr connection LOG(INFO) << "Stmgr " << siter->second << " closed connection"; sp_string stmgr_id = rstmgrs_[_conn]; // Did we receive a start back pressure message from this stmgr to // begin with? if (stmgrs_who_announced_back_pressure_.find(stmgr_id) != stmgrs_who_announced_back_pressure_.end()) { stmgrs_who_announced_back_pressure_.erase(stmgr_id); if (stmgrs_who_announced_back_pressure_.empty()) { stmgr_->AttemptStopBackPressureFromSpouts(); } } // Now cleanup the data structures stmgrs_.erase(siter->second); rstmgrs_.erase(_conn); } void StMgrServer::HandleStMgrHelloRequest(REQID _id, Connection* _conn, proto::stmgr::StrMgrHelloRequest* _request) { LOG(INFO) << "Got a hello message from stmgr " << _request->stmgr() << " on connection " << _conn; proto::stmgr::StrMgrHelloResponse response; // Some basic checks if (_request->topology_name() != topology_name_) { LOG(ERROR) << "The hello message was from a different topology " << _request->topology_name() << std::endl; response.mutable_status()->set_status(proto::system::NOTOK); } else if (_request->topology_id() != topology_id_) { LOG(ERROR) << "The hello message was from a different topology id " << _request->topology_id() << std::endl; response.mutable_status()->set_status(proto::system::NOTOK); } else if (stmgrs_.find(_request->stmgr()) != stmgrs_.end()) { LOG(WARNING) << "We already had an active connection from the stmgr " << _request->stmgr() << ". Closing existing connection..."; // This will free up the slot in the various maps in this class // and the next time around we'll be able to add this stmgr. // We shouldn't add the new stmgr connection right now because // the close could be asynchronous (fired through a 0 timer) stmgrs_[_request->stmgr()]->closeConnection(); response.mutable_status()->set_status(proto::system::NOTOK); } else { stmgrs_[_request->stmgr()] = _conn; rstmgrs_[_conn] = _request->stmgr(); response.mutable_status()->set_status(proto::system::OK); } SendResponse(_id, _conn, response); delete _request; } void StMgrServer::HandleTupleStreamMessage(Connection* _conn, proto::stmgr::TupleStreamMessage* _message) { auto iter = rstmgrs_.find(_conn); if (iter == rstmgrs_.end()) { LOG(INFO) << "Recieved Tuple messages from unknown streammanager connection"; __global_protobuf_pool_release__(_message); } else { proto::system::HeronTupleSet2* tuple_set = nullptr; tuple_set = __global_protobuf_pool_acquire__(tuple_set); tuple_set->ParsePartialFromString(_message->set()); bytes_from_stmgrs_metrics_->incr_by(_message->ByteSize()); if (tuple_set->has_data()) { tuples_from_stmgrs_metrics_->incr_by(tuple_set->data().tuples_size()); } else if (tuple_set->has_control()) { ack_tuples_from_stmgrs_metrics_->incr_by(tuple_set->control().acks_size()); fail_tuples_from_stmgrs_metrics_->incr_by(tuple_set->control().fails_size()); } __global_protobuf_pool_release__(tuple_set); stmgr_->HandleStreamManagerData(iter->second, _message); } } void StMgrServer::StartBackPressureClientCb(const sp_string& _other_stmgr_id) { if (!stmgr_->DidAnnounceBackPressure()) { stmgr_->SendStartBackPressureToOtherStMgrs(); } remote_ends_who_caused_back_pressure_.insert(_other_stmgr_id); LOG(INFO) << "We observe back pressure on sending data to remote stream manager " << _other_stmgr_id; stmgr_->StartBackPressureOnSpouts(); } void StMgrServer::StopBackPressureClientCb(const sp_string& _other_stmgr_id) { CHECK(remote_ends_who_caused_back_pressure_.find(_other_stmgr_id) != remote_ends_who_caused_back_pressure_.end()); remote_ends_who_caused_back_pressure_.erase(_other_stmgr_id); if (!stmgr_->DidAnnounceBackPressure()) { stmgr_->SendStopBackPressureToOtherStMgrs(); } LOG(INFO) << "We don't observe back pressure now on sending data to remote " "stream manager " << _other_stmgr_id; if (!stmgr_->DidAnnounceBackPressure() && !stmgr_->DidOthersAnnounceBackPressure()) { stmgr_->AttemptStopBackPressureFromSpouts(); } } void StMgrServer::HandleStartBackPressureMessage(Connection* _conn, proto::stmgr::StartBackPressureMessage* _message) { // Close spouts LOG(INFO) << "Received start back pressure from str mgr " << _message->stmgr(); if (_message->topology_name() != topology_name_ || _message->topology_id() != topology_id_) { LOG(ERROR) << "Received start back pressure message from unknown stream manager " << _message->topology_name() << " " << _message->topology_id() << " " << _message->stmgr() << " " << _message->message_id(); __global_protobuf_pool_release__(_message); return; } auto iter = rstmgrs_.find(_conn); CHECK(iter != rstmgrs_.end()); sp_string stmgr_id = iter->second; stmgrs_who_announced_back_pressure_.insert(stmgr_id); stmgr_->StartBackPressureOnSpouts(); __global_protobuf_pool_release__(_message); } void StMgrServer::HandleStopBackPressureMessage(Connection* _conn, proto::stmgr::StopBackPressureMessage* _message) { LOG(INFO) << "Received stop back pressure from str mgr " << _message->stmgr(); if (_message->topology_name() != topology_name_ || _message->topology_id() != topology_id_) { LOG(ERROR) << "Received stop back pressure message from unknown stream manager " << _message->topology_name() << " " << _message->topology_id() << " " << _message->stmgr(); __global_protobuf_pool_release__(_message); return; } auto iter = rstmgrs_.find(_conn); CHECK(iter != rstmgrs_.end()); sp_string stmgr_id = iter->second; // Did we receive a start back pressure message from this stmgr to // begin with? We could have been dead at the time of the announcement if (stmgrs_who_announced_back_pressure_.find(stmgr_id) != stmgrs_who_announced_back_pressure_.end()) { stmgrs_who_announced_back_pressure_.erase(stmgr_id); } if (!stmgr_->DidAnnounceBackPressure() && !stmgr_->DidOthersAnnounceBackPressure()) { stmgr_->AttemptStopBackPressureFromSpouts(); } __global_protobuf_pool_release__(_message); } void StMgrServer::HandleDownstreamStatefulCheckpointMessage(Connection* _conn, proto::ckptmgr::DownstreamStatefulCheckpoint* _message) { stmgr_->HandleDownStreamStatefulCheckpoint(*_message); __global_protobuf_pool_release__(_message); } } // namespace stmgr } // namespace heron <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010-2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * 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 "cf_configuration.h" #include "sweeper.h" #include "miscutil.h" #include "urlmatch.h" #include "errlog.h" #include <iostream> using sp::sweeper; using sp::miscutil; using sp::urlmatch; using sp::errlog; namespace seeks_plugins { #define hash_domain_name_weight 1333166351ul /* "domain-name-weight" */ #define hash_record_cache_timeout 1954675964ul /* "record-cache-timeout" */ #define hash_cf_peer 1520012134ul /* "cf-peer" */ #define hash_dead_peer_check 1043267473ul /* "dead-peer-check" */ #define hash_dead_peer_retries 681362871ul /* "dead-peer-retries" */ #define hash_post_url_check 3323226172ul /* "post-url-check" */ #define hash_post_radius 2436628877ul /* "post-radius" */ #define hash_post_ua 1442804836ul /* "post-ua" */ #define hash_stop_words_filtering 4002206625ul /* "stop-words-filtering" */ #define hash_remote_post 4059800377ul /* "remote-post" */ #define hash_use_http_url 1825269331ul /* "use-http-urls-only" */ #define hash_cf_estimator 1689657696ul /* "cf-estimator" */ cf_configuration* cf_configuration::_config = NULL; cf_configuration::cf_configuration(const std::string &filename) :configuration_spec(filename) { // external static variables. _pl = new peer_list(); _dpl = new peer_list(); dead_peer::_pl = _pl; dead_peer::_dpl = _dpl; load_config(); } cf_configuration::~cf_configuration() { // XXX: should mutex to avoid crash (this is only called when node is dying, for now). dead_peer::_pl = NULL; dead_peer::_dpl = NULL; delete _pl; // dead peers need to be unregistered from sweeper first. hash_map<const char*,peer*,hash<const char*>,eqstr>::iterator hit = _dpl->_peers.begin(); while(hit!=_dpl->_peers.end()) { dead_peer *dp = dynamic_cast<dead_peer*>((*hit).second); if (dp) sweeper::unregister_sweepable(dp); ++hit; } delete _dpl; } void cf_configuration::set_default_config() { _domain_name_weight = 0.7; _record_cache_timeout = 600; // 10 mins. _dead_peer_check = 300; // 5 mins. _dead_peer_retries = 3; _post_url_check = true; _post_radius = 5; _post_url_ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"; // default. _stop_words_filtering = false; _remote_post = true; _use_http_urls = true; _estimator = "sre"; } void cf_configuration::handle_config_cmd(char *cmd, const uint32_t &cmd_hash, char *arg, char *buf, const unsigned long &linenum) { char tmp[BUFFER_SIZE]; int vec_count; char *vec[4]; int port; std::vector<std::string> elts; std::string host, path, address, port_str; switch (cmd_hash) { case hash_domain_name_weight: _domain_name_weight = atof(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Weight given to the domain names in the simple filter"); break; case hash_record_cache_timeout: _record_cache_timeout = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Timeout on cached remote records, in seconds"); break; case hash_cf_peer: strlcpy(tmp,arg,sizeof(tmp)); vec_count = miscutil::ssplit(tmp," \t",vec,SZ(vec),1,1); div_t divresult; divresult = div(vec_count,2); if (divresult.rem != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Wrong number of parameter when specifying static collaborative filtering peer"); break; } address = vec[0]; urlmatch::parse_url_host_and_path(address,host,path); miscutil::tokenize(host,elts,":"); port = -1; if (elts.size()>1) { host = elts.at(0); port = atoi(elts.at(1).c_str()); } port_str = (port != -1) ? ":" + miscutil::to_string(port) : ""; errlog::log_error(LOG_LEVEL_DEBUG,"adding peer %s%s%s with resource %s", host.c_str(),port_str.c_str(),path.c_str(),vec[1]); _pl->add(host,port,path,std::string(vec[1])); configuration_spec::html_table_row(_config_args,cmd,arg, "Remote peer address for collaborative filtering"); break; case hash_dead_peer_check: _dead_peer_check = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Interval of time between two dead peer checks"); break; case hash_dead_peer_retries: _dead_peer_retries = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Number of retries before marking a peer as dead"); break; case hash_post_url_check: _post_url_check = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to ping and check on posted URLs"); break; case hash_post_radius: _post_radius = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Query similarity impact radius of posted URLs"); break; case hash_post_ua: _post_url_ua = std::string(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "default 'user-agent' header used to retrieve posted URLs"); break; case hash_stop_words_filtering: _stop_words_filtering = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to filter similar queries with stop words"); break; case hash_remote_post: _remote_post = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow remote posting of results"); break; case hash_use_http_url: _use_http_urls = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow only HTTP URLs or to allow generic item UIDs"); break; case hash_cf_estimator: _estimator = arg; configuration_spec::html_table_row(_config_args,cmd,arg, "Estimator used by the collaborative filter"); break; default: break; } } void cf_configuration::finalize_configuration() { } } /* end of namespace. */ <commit_msg>fixed broken parsing of collaborative filters' post-radius<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010-2011 Emmanuel Benazera <ebenazer@seeks-project.info> * * 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 "cf_configuration.h" #include "sweeper.h" #include "miscutil.h" #include "urlmatch.h" #include "errlog.h" #include <iostream> using sp::sweeper; using sp::miscutil; using sp::urlmatch; using sp::errlog; namespace seeks_plugins { #define hash_domain_name_weight 1333166351ul /* "domain-name-weight" */ #define hash_record_cache_timeout 1954675964ul /* "record-cache-timeout" */ #define hash_cf_peer 1520012134ul /* "cf-peer" */ #define hash_dead_peer_check 1043267473ul /* "dead-peer-check" */ #define hash_dead_peer_retries 681362871ul /* "dead-peer-retries" */ #define hash_post_url_check 3323226172ul /* "post-url-check" */ #define hash_post_radius 2436628877ul /* "post-radius" */ #define hash_post_ua 1442804836ul /* "post-ua" */ #define hash_stop_words_filtering 4002206625ul /* "stop-words-filtering" */ #define hash_remote_post 4059800377ul /* "remote-post" */ #define hash_use_http_url 1825269331ul /* "use-http-urls-only" */ #define hash_cf_estimator 1689657696ul /* "cf-estimator" */ cf_configuration* cf_configuration::_config = NULL; cf_configuration::cf_configuration(const std::string &filename) :configuration_spec(filename) { // external static variables. _pl = new peer_list(); _dpl = new peer_list(); dead_peer::_pl = _pl; dead_peer::_dpl = _dpl; load_config(); } cf_configuration::~cf_configuration() { // XXX: should mutex to avoid crash (this is only called when node is dying, for now). dead_peer::_pl = NULL; dead_peer::_dpl = NULL; delete _pl; // dead peers need to be unregistered from sweeper first. hash_map<const char*,peer*,hash<const char*>,eqstr>::iterator hit = _dpl->_peers.begin(); while(hit!=_dpl->_peers.end()) { dead_peer *dp = dynamic_cast<dead_peer*>((*hit).second); if (dp) sweeper::unregister_sweepable(dp); ++hit; } delete _dpl; } void cf_configuration::set_default_config() { _domain_name_weight = 0.7; _record_cache_timeout = 600; // 10 mins. _dead_peer_check = 300; // 5 mins. _dead_peer_retries = 3; _post_url_check = true; _post_radius = 5; _post_url_ua = "Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"; // default. _stop_words_filtering = false; _remote_post = true; _use_http_urls = true; _estimator = "sre"; } void cf_configuration::handle_config_cmd(char *cmd, const uint32_t &cmd_hash, char *arg, char *buf, const unsigned long &linenum) { char tmp[BUFFER_SIZE]; int vec_count; char *vec[4]; int port; std::vector<std::string> elts; std::string host, path, address, port_str; switch (cmd_hash) { case hash_domain_name_weight: _domain_name_weight = atof(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Weight given to the domain names in the simple filter"); break; case hash_record_cache_timeout: _record_cache_timeout = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Timeout on cached remote records, in seconds"); break; case hash_cf_peer: strlcpy(tmp,arg,sizeof(tmp)); vec_count = miscutil::ssplit(tmp," \t",vec,SZ(vec),1,1); div_t divresult; divresult = div(vec_count,2); if (divresult.rem != 0) { errlog::log_error(LOG_LEVEL_ERROR,"Wrong number of parameter when specifying static collaborative filtering peer"); break; } address = vec[0]; urlmatch::parse_url_host_and_path(address,host,path); miscutil::tokenize(host,elts,":"); port = -1; if (elts.size()>1) { host = elts.at(0); port = atoi(elts.at(1).c_str()); } port_str = (port != -1) ? ":" + miscutil::to_string(port) : ""; errlog::log_error(LOG_LEVEL_DEBUG,"adding peer %s%s%s with resource %s", host.c_str(),port_str.c_str(),path.c_str(),vec[1]); _pl->add(host,port,path,std::string(vec[1])); configuration_spec::html_table_row(_config_args,cmd,arg, "Remote peer address for collaborative filtering"); break; case hash_dead_peer_check: _dead_peer_check = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Interval of time between two dead peer checks"); break; case hash_dead_peer_retries: _dead_peer_retries = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Number of retries before marking a peer as dead"); break; case hash_post_url_check: _post_url_check = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to ping and check on posted URLs"); break; case hash_post_radius: _post_radius = atoi(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "Query similarity impact radius of posted URLs"); break; case hash_post_ua: _post_url_ua = std::string(arg); configuration_spec::html_table_row(_config_args,cmd,arg, "default 'user-agent' header used to retrieve posted URLs"); break; case hash_stop_words_filtering: _stop_words_filtering = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to filter similar queries with stop words"); break; case hash_remote_post: _remote_post = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow remote posting of results"); break; case hash_use_http_url: _use_http_urls = static_cast<bool>(atoi(arg)); configuration_spec::html_table_row(_config_args,cmd,arg, "Whether to allow only HTTP URLs or to allow generic item UIDs"); break; case hash_cf_estimator: _estimator = arg; configuration_spec::html_table_row(_config_args,cmd,arg, "Estimator used by the collaborative filter"); break; default: break; } } void cf_configuration::finalize_configuration() { } } /* end of namespace. */ <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "Routing.h" #include "MarbleDeclarativeWidget.h" #include "MarbleModel.h" #include "MarbleDirs.h" #include "routing/AlternativeRoutesModel.h" #include "routing/RoutingManager.h" #include "routing/RoutingModel.h" #include "routing/RouteRequest.h" #include "RouteRequestModel.h" #include "routing/RoutingProfilesModel.h" class RoutingPrivate { public: RoutingPrivate(); MarbleWidget* m_marbleWidget; QAbstractItemModel* m_routeRequestModel; QMap<QString, Marble::RoutingProfile> m_profiles; QString m_routingProfile; }; RoutingPrivate::RoutingPrivate() : m_marbleWidget( 0 ), m_routeRequestModel( 0 ) { // nothing to do } Routing::Routing( QObject* parent) : QObject( parent ), d( new RoutingPrivate ) { // nothing to do } Routing::~Routing() { delete d; } QObject* Routing::routeRequestModel() { if ( !d->m_routeRequestModel && d->m_marbleWidget ) { Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); d->m_routeRequestModel = new RouteRequestModel( request, this ); } return d->m_routeRequestModel; } QObject* Routing::waypointModel() { return d->m_marbleWidget ? d->m_marbleWidget->model()->routingManager()->routingModel() : 0; } void Routing::setMap( MarbleWidget* widget ) { d->m_marbleWidget = widget; if ( d->m_marbleWidget ) { connect( d->m_marbleWidget->model()->routingManager(), SIGNAL(stateChanged(RoutingManager::State)), this, SIGNAL(hasRouteChanged()) ); QList<Marble::RoutingProfile> profiles = d->m_marbleWidget->model()->routingManager()->profilesModel()->profiles(); if ( profiles.size() == 4 ) { /** @todo FIXME: Restrictive assumptions on available plugins and certain profile loading implementation */ d->m_profiles["Motorcar"] = profiles.at( 0 ); d->m_profiles["Bicycle"] = profiles.at( 2 ); d->m_profiles["Pedestrian"] = profiles.at( 3 ); } else { qDebug() << "Unexpected size of default routing profiles: " << profiles.size(); } } emit mapChanged(); } MarbleWidget *Routing::map() { return d->m_marbleWidget; } QString Routing::routingProfile() const { return d->m_routingProfile; } void Routing::setRoutingProfile( const QString & profile ) { if ( d->m_routingProfile != profile ) { d->m_routingProfile = profile; if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->routeRequest()->setRoutingProfile( d->m_profiles[profile] ); } emit routingProfileChanged(); } } bool Routing::hasRoute() const { return d->m_marbleWidget && d->m_marbleWidget->model()->routingManager()->routingModel()->rowCount() > 0; } void Routing::addVia( qreal lon, qreal lat ) { if ( d->m_marbleWidget ) { Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); request->append( Marble::GeoDataCoordinates( lon, lat, 0.0, Marble::GeoDataCoordinates::Degree ) ); updateRoute(); } } void Routing::setVia( int index, qreal lon, qreal lat ) { if ( index < 0 || index > 200 || !d->m_marbleWidget ) { return; } Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); Q_ASSERT( request ); if ( index < request->size() ) { request->setPosition( index, Marble::GeoDataCoordinates( lon, lat, 0.0, Marble::GeoDataCoordinates::Degree ) ); } else { for ( int i=request->size(); i<index; ++i ) { request->append( Marble::GeoDataCoordinates( 0.0, 0.0 ) ); } request->append( Marble::GeoDataCoordinates( lon, lat, 0.0, Marble::GeoDataCoordinates::Degree ) ); } updateRoute(); } void Routing::removeVia( int index ) { if ( index < 0 || !d->m_marbleWidget ) { return; } Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); if ( index < request->size() ) { d->m_marbleWidget->model()->routingManager()->routeRequest()->remove( index ); } } void Routing::reverseRoute() { if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->reverseRoute(); } } void Routing::clearRoute() { if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->clearRoute(); } } void Routing::updateRoute() { if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->retrieveRoute(); } } void Routing::openRoute( const QString &fileName ) { if ( d->m_marbleWidget ) { Marble::RoutingManager * const routingManager = d->m_marbleWidget->model()->routingManager(); /** @todo FIXME: replace the file:// prefix on QML side */ routingManager->clearRoute(); QString target = fileName.startsWith( QLatin1String( "file://" ) ) ? fileName.mid( 7 ) : fileName; routingManager->loadRoute( target ); Marble::GeoDataDocument* route = routingManager->alternativeRoutesModel()->currentRoute(); if ( route ) { Marble::GeoDataLineString* waypoints = routingManager->alternativeRoutesModel()->waypoints( route ); if ( waypoints ) { d->m_marbleWidget->centerOn( waypoints->latLonAltBox() ); } } } } void Routing::saveRoute( const QString &fileName ) { if ( d->m_marbleWidget ) { /** @todo FIXME: replace the file:// prefix on QML side */ QString target = fileName.startsWith( QLatin1String( "file://" ) ) ? fileName.mid( 7 ) : fileName; d->m_marbleWidget->model()->routingManager()->saveRoute( target ); } } #include "Routing.moc" <commit_msg>need to emit a few more signals when assigned MarbleWidget changes<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "Routing.h" #include "MarbleDeclarativeWidget.h" #include "MarbleModel.h" #include "MarbleDirs.h" #include "routing/AlternativeRoutesModel.h" #include "routing/RoutingManager.h" #include "routing/RoutingModel.h" #include "routing/RouteRequest.h" #include "RouteRequestModel.h" #include "routing/RoutingProfilesModel.h" class RoutingPrivate { public: RoutingPrivate(); MarbleWidget* m_marbleWidget; QAbstractItemModel* m_routeRequestModel; QMap<QString, Marble::RoutingProfile> m_profiles; QString m_routingProfile; }; RoutingPrivate::RoutingPrivate() : m_marbleWidget( 0 ), m_routeRequestModel( 0 ) { // nothing to do } Routing::Routing( QObject* parent) : QObject( parent ), d( new RoutingPrivate ) { // nothing to do } Routing::~Routing() { delete d; } QObject* Routing::routeRequestModel() { if ( !d->m_routeRequestModel && d->m_marbleWidget ) { Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); d->m_routeRequestModel = new RouteRequestModel( request, this ); } return d->m_routeRequestModel; } QObject* Routing::waypointModel() { return d->m_marbleWidget ? d->m_marbleWidget->model()->routingManager()->routingModel() : 0; } void Routing::setMap( MarbleWidget* widget ) { d->m_marbleWidget = widget; if ( d->m_marbleWidget ) { connect( d->m_marbleWidget->model()->routingManager(), SIGNAL(stateChanged(RoutingManager::State)), this, SIGNAL(hasRouteChanged()) ); QList<Marble::RoutingProfile> profiles = d->m_marbleWidget->model()->routingManager()->profilesModel()->profiles(); if ( profiles.size() == 4 ) { /** @todo FIXME: Restrictive assumptions on available plugins and certain profile loading implementation */ d->m_profiles["Motorcar"] = profiles.at( 0 ); d->m_profiles["Bicycle"] = profiles.at( 2 ); d->m_profiles["Pedestrian"] = profiles.at( 3 ); } else { qDebug() << "Unexpected size of default routing profiles: " << profiles.size(); } } emit mapChanged(); emit routingProfileChanged(); emit hasRouteChanged(); } MarbleWidget *Routing::map() { return d->m_marbleWidget; } QString Routing::routingProfile() const { return d->m_routingProfile; } void Routing::setRoutingProfile( const QString & profile ) { if ( d->m_routingProfile != profile ) { d->m_routingProfile = profile; if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->routeRequest()->setRoutingProfile( d->m_profiles[profile] ); } emit routingProfileChanged(); } } bool Routing::hasRoute() const { return d->m_marbleWidget && d->m_marbleWidget->model()->routingManager()->routingModel()->rowCount() > 0; } void Routing::addVia( qreal lon, qreal lat ) { if ( d->m_marbleWidget ) { Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); request->append( Marble::GeoDataCoordinates( lon, lat, 0.0, Marble::GeoDataCoordinates::Degree ) ); updateRoute(); } } void Routing::setVia( int index, qreal lon, qreal lat ) { if ( index < 0 || index > 200 || !d->m_marbleWidget ) { return; } Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); Q_ASSERT( request ); if ( index < request->size() ) { request->setPosition( index, Marble::GeoDataCoordinates( lon, lat, 0.0, Marble::GeoDataCoordinates::Degree ) ); } else { for ( int i=request->size(); i<index; ++i ) { request->append( Marble::GeoDataCoordinates( 0.0, 0.0 ) ); } request->append( Marble::GeoDataCoordinates( lon, lat, 0.0, Marble::GeoDataCoordinates::Degree ) ); } updateRoute(); } void Routing::removeVia( int index ) { if ( index < 0 || !d->m_marbleWidget ) { return; } Marble::RouteRequest* request = d->m_marbleWidget->model()->routingManager()->routeRequest(); if ( index < request->size() ) { d->m_marbleWidget->model()->routingManager()->routeRequest()->remove( index ); } } void Routing::reverseRoute() { if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->reverseRoute(); } } void Routing::clearRoute() { if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->clearRoute(); } } void Routing::updateRoute() { if ( d->m_marbleWidget ) { d->m_marbleWidget->model()->routingManager()->retrieveRoute(); } } void Routing::openRoute( const QString &fileName ) { if ( d->m_marbleWidget ) { Marble::RoutingManager * const routingManager = d->m_marbleWidget->model()->routingManager(); /** @todo FIXME: replace the file:// prefix on QML side */ routingManager->clearRoute(); QString target = fileName.startsWith( QLatin1String( "file://" ) ) ? fileName.mid( 7 ) : fileName; routingManager->loadRoute( target ); Marble::GeoDataDocument* route = routingManager->alternativeRoutesModel()->currentRoute(); if ( route ) { Marble::GeoDataLineString* waypoints = routingManager->alternativeRoutesModel()->waypoints( route ); if ( waypoints ) { d->m_marbleWidget->centerOn( waypoints->latLonAltBox() ); } } } } void Routing::saveRoute( const QString &fileName ) { if ( d->m_marbleWidget ) { /** @todo FIXME: replace the file:// prefix on QML side */ QString target = fileName.startsWith( QLatin1String( "file://" ) ) ? fileName.mid( 7 ) : fileName; d->m_marbleWidget->model()->routingManager()->saveRoute( target ); } } #include "Routing.moc" <|endoftext|>
<commit_before>#include "IRremote.h" #include "IRremoteInt.h" //============================================================================== // AAA IIIII W W AAA // A A I W W A A // AAAAA I W W W AAAAA // A A I W W W A A // A A IIIII WWW A A //============================================================================== // Baszed off the RC-T501 RCU // Lirc file http://lirc.sourceforge.net/remotes/aiwa/RC-T501 #define AIWA_RC_T501_HZ 38 #define AIWA_RC_T501_BITS 15 #define AIWA_RC_T501_PRE_BITS 26 #define AIWA_RC_T501_POST_BITS 1 #define AIWA_RC_T501_SUM_BITS (AIWA_RC_T501_PRE_BITS + AIWA_RC_T501_BITS + AIWA_RC_T501_POST_BITS) #define AIWA_RC_T501_HDR_MARK 8800 #define AIWA_RC_T501_HDR_SPACE 4500 #define AIWA_RC_T501_BIT_MARK 500 #define AIWA_RC_T501_ONE_SPACE 600 #define AIWA_RC_T501_ZERO_SPACE 1700 //+============================================================================= #if SEND_AIWA_RC_T501 void IRsend::sendAiwaRCT501 (int code) { unsigned long pre = 0x0227EEC0; // 26-bits // Set IR carrier frequency enableIROut(AIWA_RC_T501_HZ); // Header mark(AIWA_RC_T501_HDR_MARK); space(AIWA_RC_T501_HDR_SPACE); // Send "pre" data for (unsigned long mask = 1UL << (26 - 1); mask; mask >>= 1) { mark(AIWA_RC_T501_BIT_MARK); if (pre & mask) space(AIWA_RC_T501_ONE_SPACE) ; else space(AIWA_RC_T501_ZERO_SPACE) ; } //-v- THIS CODE LOOKS LIKE IT MIGHT BE WRONG - CHECK! // it only send 15bits and ignores the top bit // then uses TOPBIT which is 0x80000000 to check the bit code // I suspect TOPBIT should be changed to 0x00008000 // Skip first code bit code <<= 1; // Send code for (int i = 0; i < 15; i++) { mark(AIWA_RC_T501_BIT_MARK); if (code & 0x80000000) space(AIWA_RC_T501_ONE_SPACE) ; else space(AIWA_RC_T501_ZERO_SPACE) ; code <<= 1; } //-^- THIS CODE LOOKS LIKE IT MIGHT BE WRONG - CHECK! // POST-DATA, 1 bit, 0x0 mark(AIWA_RC_T501_BIT_MARK); space(AIWA_RC_T501_ZERO_SPACE); mark(AIWA_RC_T501_BIT_MARK); space(0); } #endif //+============================================================================= #if DECODE_AIWA_RC_T501 bool IRrecv::decodeAiwaRCT501 (decode_results *results) { int data = 0; int offset = 1; // Check SIZE if (irparams.rawlen < 2 * (AIWA_RC_T501_SUM_BITS) + 4) return false ; // Check HDR Mark/Space if (!MATCH_MARK (results->rawbuf[offset++], AIWA_RC_T501_HDR_MARK )) return false ; if (!MATCH_SPACE(results->rawbuf[offset++], AIWA_RC_T501_HDR_SPACE)) return false ; offset += 26; // skip pre-data - optional while(offset < irparams.rawlen - 4) { if (MATCH_MARK(results->rawbuf[offset], AIWA_RC_T501_BIT_MARK)) offset++ ; else return false ; // ONE & ZERO if (MATCH_SPACE(results->rawbuf[offset], AIWA_RC_T501_ONE_SPACE)) data = (data << 1) | 1 ; else if (MATCH_SPACE(results->rawbuf[offset], AIWA_RC_T501_ZERO_SPACE)) data = (data << 1) | 0 ; else break ; // End of one & zero detected offset++; } results->bits = (offset - 1) / 2; if (results->bits < 42) return false ; results->value = data; results->decode_type = AIWA_RC_T501; return true; } #endif <commit_msg>Update ir_Aiwa.cpp<commit_after>#include "IRremote.h" #include "IRremoteInt.h" //============================================================================== // AAA IIIII W W AAA // A A I W W A A // AAAAA I W W W AAAAA // A A I W W W A A // A A IIIII WWW A A //============================================================================== // Based off the RC-T501 RCU // Lirc file http://lirc.sourceforge.net/remotes/aiwa/RC-T501 #define AIWA_RC_T501_HZ 38 #define AIWA_RC_T501_BITS 15 #define AIWA_RC_T501_PRE_BITS 26 #define AIWA_RC_T501_POST_BITS 1 #define AIWA_RC_T501_SUM_BITS (AIWA_RC_T501_PRE_BITS + AIWA_RC_T501_BITS + AIWA_RC_T501_POST_BITS) #define AIWA_RC_T501_HDR_MARK 8800 #define AIWA_RC_T501_HDR_SPACE 4500 #define AIWA_RC_T501_BIT_MARK 500 #define AIWA_RC_T501_ONE_SPACE 600 #define AIWA_RC_T501_ZERO_SPACE 1700 //+============================================================================= #if SEND_AIWA_RC_T501 void IRsend::sendAiwaRCT501 (int code) { unsigned long pre = 0x0227EEC0; // 26-bits // Set IR carrier frequency enableIROut(AIWA_RC_T501_HZ); // Header mark(AIWA_RC_T501_HDR_MARK); space(AIWA_RC_T501_HDR_SPACE); // Send "pre" data for (unsigned long mask = 1UL << (26 - 1); mask; mask >>= 1) { mark(AIWA_RC_T501_BIT_MARK); if (pre & mask) space(AIWA_RC_T501_ONE_SPACE) ; else space(AIWA_RC_T501_ZERO_SPACE) ; } //-v- THIS CODE LOOKS LIKE IT MIGHT BE WRONG - CHECK! // it only send 15bits and ignores the top bit // then uses TOPBIT which is 0x80000000 to check the bit code // I suspect TOPBIT should be changed to 0x00008000 // Skip first code bit code <<= 1; // Send code for (int i = 0; i < 15; i++) { mark(AIWA_RC_T501_BIT_MARK); if (code & 0x80000000) space(AIWA_RC_T501_ONE_SPACE) ; else space(AIWA_RC_T501_ZERO_SPACE) ; code <<= 1; } //-^- THIS CODE LOOKS LIKE IT MIGHT BE WRONG - CHECK! // POST-DATA, 1 bit, 0x0 mark(AIWA_RC_T501_BIT_MARK); space(AIWA_RC_T501_ZERO_SPACE); mark(AIWA_RC_T501_BIT_MARK); space(0); } #endif //+============================================================================= #if DECODE_AIWA_RC_T501 bool IRrecv::decodeAiwaRCT501 (decode_results *results) { int data = 0; int offset = 1; // Check SIZE if (irparams.rawlen < 2 * (AIWA_RC_T501_SUM_BITS) + 4) return false ; // Check HDR Mark/Space if (!MATCH_MARK (results->rawbuf[offset++], AIWA_RC_T501_HDR_MARK )) return false ; if (!MATCH_SPACE(results->rawbuf[offset++], AIWA_RC_T501_HDR_SPACE)) return false ; offset += 26; // skip pre-data - optional while(offset < irparams.rawlen - 4) { if (MATCH_MARK(results->rawbuf[offset], AIWA_RC_T501_BIT_MARK)) offset++ ; else return false ; // ONE & ZERO if (MATCH_SPACE(results->rawbuf[offset], AIWA_RC_T501_ONE_SPACE)) data = (data << 1) | 1 ; else if (MATCH_SPACE(results->rawbuf[offset], AIWA_RC_T501_ZERO_SPACE)) data = (data << 1) | 0 ; else break ; // End of one & zero detected offset++; } results->bits = (offset - 1) / 2; if (results->bits < 42) return false ; results->value = data; results->decode_type = AIWA_RC_T501; return true; } #endif <|endoftext|>
<commit_before>#include "OpenNIPlugin.h" #include <iostream> #include <StreamTypes.h> #include "../../SenseKit/sensekit_internal.h" #ifndef MIN #define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif using std::cout; using std::endl; EXPORT_PLUGIN(sensekit::openni::OpenNIPlugin); namespace sensekit { namespace openni { void OpenNIPlugin::init_openni() { ::openni::Status rc = ::openni::STATUS_OK; ::openni::OpenNI::addDeviceConnectedListener(this); ::openni::OpenNI::addDeviceDisconnectedListener(this); cout << "Initializing openni" << endl; rc = ::openni::OpenNI::initialize(); } void OpenNIPlugin::onDeviceConnected(const ::openni::DeviceInfo* info) { ::openni::Status rc = ::openni::STATUS_OK; cout << "Opening device" << endl; rc = m_device.open(info->getUri()); if (rc != ::openni::STATUS_OK) { cout << "Failed to open" << endl; ::openni::OpenNI::shutdown(); } m_deviceInfo = m_device.getDeviceInfo(); open_sensor_streams(); } void OpenNIPlugin::onDeviceDisconnected(const ::openni::DeviceInfo* info) { get_pluginService().destroy_stream(m_depthHandle); get_pluginService().destroy_stream(m_colorHandle); get_pluginService().destroy_stream_set(m_streamSetHandle); close_sensor_streams(); } OpenNIPlugin::~OpenNIPlugin() { get_pluginService().destroy_stream(m_depthHandle); get_pluginService().destroy_stream(m_colorHandle); get_pluginService().destroy_stream_set(m_streamSetHandle); close_sensor_streams(); cout << "closing device" << endl; m_device.close(); cout << "shutting down openni" << endl; ::openni::OpenNI::shutdown(); } sensekit_status_t OpenNIPlugin::open_sensor_streams() { ::openni::Status rc = ::openni::STATUS_OK; cout << "opening depth stream" << endl; rc = m_depthStream.create(m_device, ::openni::SENSOR_DEPTH); if (rc == ::openni::STATUS_OK) { cout << "starting depth stream." << endl; rc = m_depthStream.start(); if (rc != ::openni::STATUS_OK) { cout << "failed to start depth stream" << endl; m_depthStream.destroy(); } } else { cout << "Failed to open depth stream" << endl; } if (!m_depthStream.isValid()) { cout << "shutting down openni because of failure" << endl; ::openni::OpenNI::shutdown(); } cout << "opening color stream" << endl; rc = m_colorStream.create(m_device, ::openni::SENSOR_COLOR); if (rc == ::openni::STATUS_OK) { cout << "starting color stream." << endl; rc = m_colorStream.start(); if (rc != ::openni::STATUS_OK) { cout << "failed to start color stream" << endl; m_colorStream.destroy(); } } else { cout << "Failed to open color stream" << endl; } if (!m_colorStream.isValid()) { cout << "shutting down openni because of failure" << endl; ::openni::OpenNI::shutdown(); } sensekit_frame_t* nextBuffer = nullptr; stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this); get_pluginService().create_stream_set(m_streamSetHandle); sensekit_stream_desc_t depthDesc; depthDesc.type = SENSEKIT_STREAM_DEPTH; depthDesc.subType = DEPTH_DEFAULT_SUBTYPE; get_pluginService().create_stream(m_streamSetHandle, depthDesc, pluginCallbacks, &m_depthHandle); sensekit_stream_desc_t colorDesc; colorDesc.type = SENSEKIT_STREAM_COLOR; colorDesc.subType = COLOR_DEFAULT_SUBTYPE; get_pluginService().create_stream(m_streamSetHandle, colorDesc, pluginCallbacks, &m_colorHandle); m_depthMode = m_depthStream.getVideoMode(); m_colorMode = m_colorStream.getVideoMode(); m_depthBufferLength = m_depthMode.getResolutionX() * m_depthMode.getResolutionY() * 2; m_colorBufferLength = m_colorMode.getResolutionX() * m_colorMode.getResolutionY() * 3; get_pluginService() .create_stream_bin(m_depthHandle, sizeof(sensekit_depthframe_wrapper_t) + m_depthBufferLength, &m_depthBinHandle, &nextBuffer); set_new_depth_buffer(nextBuffer); get_pluginService() .create_stream_bin(m_colorHandle, sizeof(sensekit_colorframe_wrapper_t) + m_colorBufferLength, &m_colorBinHandle, &nextBuffer); set_new_color_buffer(nextBuffer); return SENSEKIT_STATUS_SUCCESS; } void OpenNIPlugin::set_parameter(sensekit_streamconnection_t streamConnection, sensekit_parameter_id id, size_t byteLength, sensekit_parameter_data_t* data) {} void OpenNIPlugin::get_parameter_size(sensekit_streamconnection_t streamConnection, sensekit_parameter_id id, size_t& byteLength) {} void OpenNIPlugin::get_parameter_data(sensekit_streamconnection_t streamConnection, sensekit_parameter_id id, size_t byteLength, sensekit_parameter_data_t* data) {} void OpenNIPlugin::connection_added(sensekit_streamconnection_t connection) { sensekit_stream_desc_t desc; sensekit_stream_get_description(connection, &desc); switch (desc.type) { case SENSEKIT_STREAM_DEPTH: get_pluginService().link_connection_to_bin(connection, m_depthBinHandle); cout << "openniplugin: new connection added, linked to global depth" << endl; break; case SENSEKIT_STREAM_COLOR: get_pluginService().link_connection_to_bin(connection, m_colorBinHandle); cout << "openniplugin: new connection added, linked to global color" << endl; break; } } void OpenNIPlugin::connection_removed(sensekit_streamconnection_t connection) { sensekit_stream_desc_t desc; sensekit_stream_get_description(connection, &desc); switch (desc.type) { case SENSEKIT_STREAM_DEPTH: get_pluginService().link_connection_to_bin(connection, nullptr); cout << "openniplugin: connection removed, unlinking from depth" << endl; break; case SENSEKIT_STREAM_COLOR: get_pluginService().link_connection_to_bin(connection, nullptr); cout << "openniplugin: connection removed, unlinking from color" << endl; break; } } sensekit_status_t OpenNIPlugin::close_sensor_streams() { cout << "stopping depth stream" << endl; m_depthStream.stop(); cout << "stopping color stream" << endl; m_colorStream.stop(); cout << "destroying depth stream" << endl; m_depthStream.destroy(); cout << "destroying color stream" << endl; m_colorStream.destroy(); return SENSEKIT_STATUS_SUCCESS; } void OpenNIPlugin::set_new_depth_buffer(sensekit_frame_t* nextBuffer) { m_currentDepthBuffer = nextBuffer; m_currentDepthFrame = nullptr; if (m_currentDepthBuffer != nullptr) { m_currentDepthBuffer->frameIndex = m_frameIndex; m_currentDepthFrame = static_cast<sensekit_depthframe_wrapper_t*>(m_currentDepthBuffer->data); if (m_currentDepthFrame != nullptr) { m_currentDepthFrame->frame.data = reinterpret_cast<int16_t *>(&(m_currentDepthFrame->frame_data)); sensekit_depthframe_metadata_t metadata; metadata.width = m_depthMode.getResolutionX(); metadata.height = m_depthMode.getResolutionY(); metadata.bytesPerPixel = 2; m_currentDepthFrame->frame.metadata = metadata; } } } void OpenNIPlugin::set_new_color_buffer(sensekit_frame_t* nextBuffer) { m_currentColorBuffer = nextBuffer; m_currentColorFrame = nullptr; if (m_currentColorBuffer != nullptr) { m_currentColorBuffer->frameIndex = m_frameIndex; m_currentColorFrame = static_cast<sensekit_colorframe_wrapper_t*>(m_currentColorBuffer->data); if (m_currentColorFrame != nullptr) { m_currentColorFrame->frame.data = reinterpret_cast<uint8_t *>(&(m_currentColorFrame->frame_data)); sensekit_colorframe_metadata_t metadata; metadata.width = m_colorMode.getResolutionX(); metadata.height = m_colorMode.getResolutionY(); metadata.bytesPerPixel = 3; m_currentColorFrame->frame.metadata = metadata; } } } void OpenNIPlugin::temp_update() { if (m_currentColorBuffer != nullptr && m_currentDepthBuffer != nullptr) { read_streams(); } } sensekit_status_t OpenNIPlugin::read_streams() { int streamIndex = -1; int timeout = ::openni::TIMEOUT_NONE; ::openni::VideoStream* pStreams[] = { &m_depthStream, &m_colorStream }; if (::openni::OpenNI::waitForAnyStream(pStreams, 2, &streamIndex, timeout) == ::openni::STATUS_TIME_OUT) { return SENSEKIT_STATUS_TIMEOUT; } if (streamIndex == -1) return SENSEKIT_STATUS_TIMEOUT; sensekit_frame_t* nextBuffer = nullptr; if (streamIndex == 0) { ::openni::VideoFrameRef ref; if (m_depthStream.readFrame(&ref) == ::openni::STATUS_OK) { const int16_t* oniFrameData = static_cast<const int16_t*>(ref.getData()); int16_t* frameData = m_currentDepthFrame->frame.data; int dataSize = MIN(ref.getDataSize(), m_depthBufferLength); memcpy(frameData, oniFrameData, dataSize); ++m_frameIndex; get_pluginService().cycle_bin_buffers(m_depthBinHandle, &nextBuffer); set_new_depth_buffer(nextBuffer); } } else if (streamIndex == 1) { ::openni::VideoFrameRef ref; if (m_colorStream.readFrame(&ref) == ::openni::STATUS_OK) { const uint8_t* oniFrameData = static_cast<const uint8_t*>(ref.getData()); uint8_t* frameData = m_currentColorFrame->frame.data; int dataSize = MIN(ref.getDataSize(), m_colorBufferLength); memcpy(frameData, oniFrameData, dataSize); ++m_frameIndex; get_pluginService().cycle_bin_buffers(m_colorBinHandle, &nextBuffer); set_new_color_buffer(nextBuffer); } } return SENSEKIT_STATUS_SUCCESS; } } } <commit_msg>More description messages for device connect/disconnect<commit_after>#include "OpenNIPlugin.h" #include <iostream> #include <StreamTypes.h> #include "../../SenseKit/sensekit_internal.h" #ifndef MIN #define MIN(a,b) (((a)<(b))?(a):(b)) #endif #ifndef MAX #define MAX(a,b) (((a)>(b))?(a):(b)) #endif using std::cout; using std::endl; EXPORT_PLUGIN(sensekit::openni::OpenNIPlugin); namespace sensekit { namespace openni { void OpenNIPlugin::init_openni() { ::openni::Status rc = ::openni::STATUS_OK; ::openni::OpenNI::addDeviceConnectedListener(this); ::openni::OpenNI::addDeviceDisconnectedListener(this); cout << "Initializing openni" << endl; rc = ::openni::OpenNI::initialize(); } void OpenNIPlugin::onDeviceConnected(const ::openni::DeviceInfo* info) { ::openni::Status rc = ::openni::STATUS_OK; cout << "device connected, opening device" << endl; rc = m_device.open(info->getUri()); if (rc != ::openni::STATUS_OK) { cout << "Failed to open" << endl; ::openni::OpenNI::shutdown(); } m_deviceInfo = m_device.getDeviceInfo(); open_sensor_streams(); } void OpenNIPlugin::onDeviceDisconnected(const ::openni::DeviceInfo* info) { cout << "device disconnected" << endl; get_pluginService().destroy_stream(m_depthHandle); get_pluginService().destroy_stream(m_colorHandle); get_pluginService().destroy_stream_set(m_streamSetHandle); close_sensor_streams(); } OpenNIPlugin::~OpenNIPlugin() { get_pluginService().destroy_stream(m_depthHandle); get_pluginService().destroy_stream(m_colorHandle); get_pluginService().destroy_stream_set(m_streamSetHandle); close_sensor_streams(); cout << "closing device" << endl; m_device.close(); cout << "shutting down openni" << endl; ::openni::OpenNI::shutdown(); } sensekit_status_t OpenNIPlugin::open_sensor_streams() { ::openni::Status rc = ::openni::STATUS_OK; cout << "opening depth stream" << endl; rc = m_depthStream.create(m_device, ::openni::SENSOR_DEPTH); if (rc == ::openni::STATUS_OK) { cout << "starting depth stream." << endl; rc = m_depthStream.start(); if (rc != ::openni::STATUS_OK) { cout << "failed to start depth stream" << endl; m_depthStream.destroy(); } } else { cout << "Failed to open depth stream" << endl; } if (!m_depthStream.isValid()) { cout << "shutting down openni because of failure" << endl; ::openni::OpenNI::shutdown(); } cout << "opening color stream" << endl; rc = m_colorStream.create(m_device, ::openni::SENSOR_COLOR); if (rc == ::openni::STATUS_OK) { cout << "starting color stream." << endl; rc = m_colorStream.start(); if (rc != ::openni::STATUS_OK) { cout << "failed to start color stream" << endl; m_colorStream.destroy(); } } else { cout << "Failed to open color stream" << endl; } if (!m_colorStream.isValid()) { cout << "shutting down openni because of failure" << endl; ::openni::OpenNI::shutdown(); } sensekit_frame_t* nextBuffer = nullptr; stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this); get_pluginService().create_stream_set(m_streamSetHandle); sensekit_stream_desc_t depthDesc; depthDesc.type = SENSEKIT_STREAM_DEPTH; depthDesc.subType = DEPTH_DEFAULT_SUBTYPE; get_pluginService().create_stream(m_streamSetHandle, depthDesc, pluginCallbacks, &m_depthHandle); sensekit_stream_desc_t colorDesc; colorDesc.type = SENSEKIT_STREAM_COLOR; colorDesc.subType = COLOR_DEFAULT_SUBTYPE; get_pluginService().create_stream(m_streamSetHandle, colorDesc, pluginCallbacks, &m_colorHandle); m_depthMode = m_depthStream.getVideoMode(); m_colorMode = m_colorStream.getVideoMode(); m_depthBufferLength = m_depthMode.getResolutionX() * m_depthMode.getResolutionY() * 2; m_colorBufferLength = m_colorMode.getResolutionX() * m_colorMode.getResolutionY() * 3; get_pluginService() .create_stream_bin(m_depthHandle, sizeof(sensekit_depthframe_wrapper_t) + m_depthBufferLength, &m_depthBinHandle, &nextBuffer); set_new_depth_buffer(nextBuffer); get_pluginService() .create_stream_bin(m_colorHandle, sizeof(sensekit_colorframe_wrapper_t) + m_colorBufferLength, &m_colorBinHandle, &nextBuffer); set_new_color_buffer(nextBuffer); return SENSEKIT_STATUS_SUCCESS; } void OpenNIPlugin::set_parameter(sensekit_streamconnection_t streamConnection, sensekit_parameter_id id, size_t byteLength, sensekit_parameter_data_t* data) {} void OpenNIPlugin::get_parameter_size(sensekit_streamconnection_t streamConnection, sensekit_parameter_id id, size_t& byteLength) {} void OpenNIPlugin::get_parameter_data(sensekit_streamconnection_t streamConnection, sensekit_parameter_id id, size_t byteLength, sensekit_parameter_data_t* data) {} void OpenNIPlugin::connection_added(sensekit_streamconnection_t connection) { sensekit_stream_desc_t desc; sensekit_stream_get_description(connection, &desc); switch (desc.type) { case SENSEKIT_STREAM_DEPTH: get_pluginService().link_connection_to_bin(connection, m_depthBinHandle); cout << "openniplugin: new connection added, linked to global depth" << endl; break; case SENSEKIT_STREAM_COLOR: get_pluginService().link_connection_to_bin(connection, m_colorBinHandle); cout << "openniplugin: new connection added, linked to global color" << endl; break; } } void OpenNIPlugin::connection_removed(sensekit_streamconnection_t connection) { sensekit_stream_desc_t desc; sensekit_stream_get_description(connection, &desc); switch (desc.type) { case SENSEKIT_STREAM_DEPTH: get_pluginService().link_connection_to_bin(connection, nullptr); cout << "openniplugin: connection removed, unlinking from depth" << endl; break; case SENSEKIT_STREAM_COLOR: get_pluginService().link_connection_to_bin(connection, nullptr); cout << "openniplugin: connection removed, unlinking from color" << endl; break; } } sensekit_status_t OpenNIPlugin::close_sensor_streams() { cout << "stopping depth stream" << endl; m_depthStream.stop(); cout << "stopping color stream" << endl; m_colorStream.stop(); cout << "destroying depth stream" << endl; m_depthStream.destroy(); cout << "destroying color stream" << endl; m_colorStream.destroy(); return SENSEKIT_STATUS_SUCCESS; } void OpenNIPlugin::set_new_depth_buffer(sensekit_frame_t* nextBuffer) { m_currentDepthBuffer = nextBuffer; m_currentDepthFrame = nullptr; if (m_currentDepthBuffer != nullptr) { m_currentDepthBuffer->frameIndex = m_frameIndex; m_currentDepthFrame = static_cast<sensekit_depthframe_wrapper_t*>(m_currentDepthBuffer->data); if (m_currentDepthFrame != nullptr) { m_currentDepthFrame->frame.data = reinterpret_cast<int16_t *>(&(m_currentDepthFrame->frame_data)); sensekit_depthframe_metadata_t metadata; metadata.width = m_depthMode.getResolutionX(); metadata.height = m_depthMode.getResolutionY(); metadata.bytesPerPixel = 2; m_currentDepthFrame->frame.metadata = metadata; } } } void OpenNIPlugin::set_new_color_buffer(sensekit_frame_t* nextBuffer) { m_currentColorBuffer = nextBuffer; m_currentColorFrame = nullptr; if (m_currentColorBuffer != nullptr) { m_currentColorBuffer->frameIndex = m_frameIndex; m_currentColorFrame = static_cast<sensekit_colorframe_wrapper_t*>(m_currentColorBuffer->data); if (m_currentColorFrame != nullptr) { m_currentColorFrame->frame.data = reinterpret_cast<uint8_t *>(&(m_currentColorFrame->frame_data)); sensekit_colorframe_metadata_t metadata; metadata.width = m_colorMode.getResolutionX(); metadata.height = m_colorMode.getResolutionY(); metadata.bytesPerPixel = 3; m_currentColorFrame->frame.metadata = metadata; } } } void OpenNIPlugin::temp_update() { if (m_currentColorBuffer != nullptr && m_currentDepthBuffer != nullptr) { read_streams(); } } sensekit_status_t OpenNIPlugin::read_streams() { int streamIndex = -1; int timeout = ::openni::TIMEOUT_NONE; ::openni::VideoStream* pStreams[] = { &m_depthStream, &m_colorStream }; if (::openni::OpenNI::waitForAnyStream(pStreams, 2, &streamIndex, timeout) == ::openni::STATUS_TIME_OUT) { return SENSEKIT_STATUS_TIMEOUT; } if (streamIndex == -1) return SENSEKIT_STATUS_TIMEOUT; sensekit_frame_t* nextBuffer = nullptr; if (streamIndex == 0) { ::openni::VideoFrameRef ref; if (m_depthStream.readFrame(&ref) == ::openni::STATUS_OK) { const int16_t* oniFrameData = static_cast<const int16_t*>(ref.getData()); int16_t* frameData = m_currentDepthFrame->frame.data; int dataSize = MIN(ref.getDataSize(), m_depthBufferLength); memcpy(frameData, oniFrameData, dataSize); ++m_frameIndex; get_pluginService().cycle_bin_buffers(m_depthBinHandle, &nextBuffer); set_new_depth_buffer(nextBuffer); } } else if (streamIndex == 1) { ::openni::VideoFrameRef ref; if (m_colorStream.readFrame(&ref) == ::openni::STATUS_OK) { const uint8_t* oniFrameData = static_cast<const uint8_t*>(ref.getData()); uint8_t* frameData = m_currentColorFrame->frame.data; int dataSize = MIN(ref.getDataSize(), m_colorBufferLength); memcpy(frameData, oniFrameData, dataSize); ++m_frameIndex; get_pluginService().cycle_bin_buffers(m_colorBinHandle, &nextBuffer); set_new_color_buffer(nextBuffer); } } return SENSEKIT_STATUS_SUCCESS; } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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 "kit.h" #include "devicesupport/devicemanager.h" #include "kitinformation.h" #include "kitmanager.h" #include "project.h" #include "toolchainmanager.h" #include <utils/qtcassert.h> #include <QApplication> #include <QIcon> #include <QStyle> #include <QTextStream> #include <QUuid> namespace { const char ID_KEY[] = "PE.Profile.Id"; const char DISPLAYNAME_KEY[] = "PE.Profile.Name"; const char AUTODETECTED_KEY[] = "PE.Profile.AutoDetected"; const char DATA_KEY[] = "PE.Profile.Data"; const char ICON_KEY[] = "PE.Profile.Icon"; } // namespace namespace ProjectExplorer { // -------------------------------------------------------------------- // Helper: // -------------------------------------------------------------------- static QString cleanName(const QString &name) { QString result = name; result.replace(QRegExp("\\W"), QLatin1String("_")); result.replace(QRegExp("_+"), "_"); // compact _ result.remove(QRegExp("^_*")); // remove leading _ result.remove(QRegExp("_+$")); // remove trailing _ if (result.isEmpty()) result = QLatin1String("unknown"); return result; } // ------------------------------------------------------------------------- // KitPrivate // ------------------------------------------------------------------------- namespace Internal { class KitPrivate { public: KitPrivate(Core::Id id) : m_id(id), m_autodetected(false), m_isValid(true), m_nestedBlockingLevel(0), m_mustNotify(false) { if (!id.isValid()) m_id = Core::Id(QUuid::createUuid().toString().toLatin1().constData()); } QString m_displayName; Core::Id m_id; bool m_autodetected; bool m_isValid; QIcon m_icon; QString m_iconPath; int m_nestedBlockingLevel; bool m_mustNotify; QHash<Core::Id, QVariant> m_data; }; } // namespace Internal // ------------------------------------------------------------------------- // Kit: // ------------------------------------------------------------------------- Kit::Kit(Core::Id id) : d(new Internal::KitPrivate(id)) { KitManager *stm = KitManager::instance(); KitGuard g(this); foreach (KitInformation *sti, stm->kitInformation()) setValue(sti->dataId(), sti->defaultValue(this)); setDisplayName(QCoreApplication::translate("ProjectExplorer::Kit", "Unnamed")); setIconPath(QLatin1String(":///DESKTOP///")); } Kit::~Kit() { delete d; } void Kit::blockNotification() { ++d->m_nestedBlockingLevel; } void Kit::unblockNotification() { --d->m_nestedBlockingLevel; if (d->m_nestedBlockingLevel > 0) return; if (d->m_mustNotify) kitUpdated(); d->m_mustNotify = false; } Kit *Kit::clone(bool keepName) const { Kit *k = new Kit; if (keepName) k->d->m_displayName = d->m_displayName; else k->d->m_displayName = QCoreApplication::translate("ProjectExplorer::Kit", "Clone of %1") .arg(d->m_displayName); k->d->m_autodetected = false; k->d->m_data = d->m_data; k->d->m_isValid = d->m_isValid; k->d->m_icon = d->m_icon; k->d->m_iconPath = d->m_iconPath; return k; } void Kit::copyFrom(const Kit *k) { KitGuard g(this); d->m_data = k->d->m_data; d->m_iconPath = k->d->m_iconPath; d->m_icon = k->d->m_icon; d->m_autodetected = k->d->m_autodetected; d->m_displayName = k->d->m_displayName; d->m_mustNotify = true; } bool Kit::isValid() const { return d->m_id.isValid() && d->m_isValid; } QList<Task> Kit::validate() const { QList<Task> result; QList<KitInformation *> infoList = KitManager::instance()->kitInformation(); d->m_isValid = true; foreach (KitInformation *i, infoList) { QList<Task> tmp = i->validate(this); foreach (const Task &t, tmp) { if (t.type == Task::Error) d->m_isValid = false; } result.append(tmp); } qSort(result); return result; } void Kit::fix() { KitGuard g(this); foreach (KitInformation *i, KitManager::instance()->kitInformation()) i->fix(this); } QString Kit::displayName() const { return d->m_displayName; } static QString candidateName(const QString &name, const QString &postfix) { if (name.contains(postfix)) return QString(); return name + QLatin1Char('-') + postfix; } void Kit::setDisplayName(const QString &name) { KitManager *km = KitManager::instance(); QList<KitInformation *> kitInfo = km->kitInformation(); QStringList nameList; foreach (Kit *k, km->kits()) { if (k == this) continue; nameList << k->displayName(); foreach (KitInformation *ki, kitInfo) { const QString postfix = ki->displayNamePostfix(k); if (!postfix.isEmpty()) nameList << candidateName(k->displayName(), postfix); } } QStringList candidateNames; candidateNames << name; foreach (KitInformation *ki, kitInfo) { const QString postfix = ki->displayNamePostfix(this); if (!postfix.isEmpty()) candidateNames << candidateName(name, postfix); } QString uniqueName = Project::makeUnique(name, nameList); if (uniqueName != name) { foreach (const QString &candidate, candidateNames) { const QString tmp = Project::makeUnique(candidate, nameList); if (tmp == candidate) { uniqueName = tmp; break; } } } if (d->m_displayName == uniqueName) return; d->m_displayName = uniqueName; kitUpdated(); } QString Kit::fileSystemFriendlyName() const { QString name = cleanName(displayName()); foreach (Kit *i, KitManager::instance()->kits()) { if (i == this) continue; if (name == cleanName(i->displayName())) { // append part of the kit id: That should be unique enough;-) // Leading { will be turned into _ which should be fine. name = cleanName(name + QLatin1Char('_') + (id().toString().left(7))); break; } } return name; } bool Kit::isAutoDetected() const { return d->m_autodetected; } Core::Id Kit::id() const { return d->m_id; } QIcon Kit::icon() const { return d->m_icon; } QString Kit::iconPath() const { return d->m_iconPath; } void Kit::setIconPath(const QString &path) { if (d->m_iconPath == path) return; d->m_iconPath = path; if (path.isNull()) d->m_icon = QIcon(); else if (path == QLatin1String(":///DESKTOP///")) d->m_icon = qApp->style()->standardIcon(QStyle::SP_ComputerIcon); else d->m_icon = QIcon(path); kitUpdated(); } QVariant Kit::value(const Core::Id &key, const QVariant &unset) const { return d->m_data.value(key, unset); } bool Kit::hasValue(const Core::Id &key) const { return d->m_data.contains(key); } void Kit::setValue(const Core::Id &key, const QVariant &value) { if (d->m_data.value(key) == value) return; d->m_data.insert(key, value); kitUpdated(); } void Kit::removeKey(const Core::Id &key) { if (!d->m_data.contains(key)) return; d->m_data.remove(key); kitUpdated(); } bool Kit::isDataEqual(const Kit *other) const { return d->m_data == other->d->m_data; } bool Kit::isEqual(const Kit *other) const { return isDataEqual(other) && d->m_iconPath == other->d->m_iconPath && d->m_displayName == other->d->m_displayName; } QVariantMap Kit::toMap() const { QVariantMap data; data.insert(QLatin1String(ID_KEY), QString::fromLatin1(d->m_id.name())); data.insert(QLatin1String(DISPLAYNAME_KEY), d->m_displayName); data.insert(QLatin1String(AUTODETECTED_KEY), d->m_autodetected); data.insert(QLatin1String(ICON_KEY), d->m_iconPath); QVariantMap extra; foreach (const Core::Id &key, d->m_data.keys()) extra.insert(QString::fromLatin1(key.name().constData()), d->m_data.value(key)); data.insert(QLatin1String(DATA_KEY), extra); return data; } void Kit::addToEnvironment(Utils::Environment &env) const { QList<KitInformation *> infoList = KitManager::instance()->kitInformation(); foreach (KitInformation *ki, infoList) ki->addToEnvironment(this, env); } QString Kit::toHtml() { QString rc; QTextStream str(&rc); str << "<html><body>"; str << "<h3>" << displayName() << "</h3>"; str << "<table>"; if (!isValid()) { QList<Task> issues = validate(); str << "<p>"; foreach (const Task &t, issues) { str << "<b>"; switch (t.type) { case Task::Error: str << QCoreApplication::translate("ProjectExplorer::Kit", "Error:"); break; case Task::Warning: str << QCoreApplication::translate("ProjectExplorer::Kit", "Warning:"); break; case Task::Unknown: default: break; } str << "</b>" << t.description << "<br>"; } str << "</p>"; } QList<KitInformation *> infoList = KitManager::instance()->kitInformation(); foreach (KitInformation *ki, infoList) { KitInformation::ItemList list = ki->toUserOutput(this); foreach (const KitInformation::Item &j, list) str << "<tr><td><b>" << j.first << ":</b></td><td>" << j.second << "</td></tr>"; } str << "</table></body></html>"; return rc; } bool Kit::fromMap(const QVariantMap &data) { KitGuard g(this); const QString id = data.value(QLatin1String(ID_KEY)).toString(); if (id.isEmpty()) return false; d->m_id = Core::Id(id); d->m_autodetected = data.value(QLatin1String(AUTODETECTED_KEY)).toBool(); setDisplayName(data.value(QLatin1String(DISPLAYNAME_KEY)).toString()); setIconPath(data.value(QLatin1String(ICON_KEY)).toString()); QVariantMap extra = data.value(QLatin1String(DATA_KEY)).toMap(); foreach (const QString &key, extra.keys()) setValue(Core::Id(key), extra.value(key)); return true; } void Kit::setAutoDetected(bool detected) { d->m_autodetected = detected; } void Kit::kitUpdated() { if (d->m_nestedBlockingLevel > 0) { d->m_mustNotify = true; return; } validate(); KitManager::instance()->notifyAboutUpdate(this); } } // namespace ProjectExplorer <commit_msg>Kits: Do not construct kits with names starting with -<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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 "kit.h" #include "devicesupport/devicemanager.h" #include "kitinformation.h" #include "kitmanager.h" #include "project.h" #include "toolchainmanager.h" #include <utils/qtcassert.h> #include <QApplication> #include <QIcon> #include <QStyle> #include <QTextStream> #include <QUuid> namespace { const char ID_KEY[] = "PE.Profile.Id"; const char DISPLAYNAME_KEY[] = "PE.Profile.Name"; const char AUTODETECTED_KEY[] = "PE.Profile.AutoDetected"; const char DATA_KEY[] = "PE.Profile.Data"; const char ICON_KEY[] = "PE.Profile.Icon"; } // namespace namespace ProjectExplorer { // -------------------------------------------------------------------- // Helper: // -------------------------------------------------------------------- static QString cleanName(const QString &name) { QString result = name; result.replace(QRegExp("\\W"), QLatin1String("_")); result.replace(QRegExp("_+"), "_"); // compact _ result.remove(QRegExp("^_*")); // remove leading _ result.remove(QRegExp("_+$")); // remove trailing _ if (result.isEmpty()) result = QLatin1String("unknown"); return result; } // ------------------------------------------------------------------------- // KitPrivate // ------------------------------------------------------------------------- namespace Internal { class KitPrivate { public: KitPrivate(Core::Id id) : m_id(id), m_autodetected(false), m_isValid(true), m_nestedBlockingLevel(0), m_mustNotify(false) { if (!id.isValid()) m_id = Core::Id(QUuid::createUuid().toString().toLatin1().constData()); } QString m_displayName; Core::Id m_id; bool m_autodetected; bool m_isValid; QIcon m_icon; QString m_iconPath; int m_nestedBlockingLevel; bool m_mustNotify; QHash<Core::Id, QVariant> m_data; }; } // namespace Internal // ------------------------------------------------------------------------- // Kit: // ------------------------------------------------------------------------- Kit::Kit(Core::Id id) : d(new Internal::KitPrivate(id)) { KitManager *stm = KitManager::instance(); KitGuard g(this); foreach (KitInformation *sti, stm->kitInformation()) setValue(sti->dataId(), sti->defaultValue(this)); setDisplayName(QCoreApplication::translate("ProjectExplorer::Kit", "Unnamed")); setIconPath(QLatin1String(":///DESKTOP///")); } Kit::~Kit() { delete d; } void Kit::blockNotification() { ++d->m_nestedBlockingLevel; } void Kit::unblockNotification() { --d->m_nestedBlockingLevel; if (d->m_nestedBlockingLevel > 0) return; if (d->m_mustNotify) kitUpdated(); d->m_mustNotify = false; } Kit *Kit::clone(bool keepName) const { Kit *k = new Kit; if (keepName) k->d->m_displayName = d->m_displayName; else k->d->m_displayName = QCoreApplication::translate("ProjectExplorer::Kit", "Clone of %1") .arg(d->m_displayName); k->d->m_autodetected = false; k->d->m_data = d->m_data; k->d->m_isValid = d->m_isValid; k->d->m_icon = d->m_icon; k->d->m_iconPath = d->m_iconPath; return k; } void Kit::copyFrom(const Kit *k) { KitGuard g(this); d->m_data = k->d->m_data; d->m_iconPath = k->d->m_iconPath; d->m_icon = k->d->m_icon; d->m_autodetected = k->d->m_autodetected; d->m_displayName = k->d->m_displayName; d->m_mustNotify = true; } bool Kit::isValid() const { return d->m_id.isValid() && d->m_isValid; } QList<Task> Kit::validate() const { QList<Task> result; QList<KitInformation *> infoList = KitManager::instance()->kitInformation(); d->m_isValid = true; foreach (KitInformation *i, infoList) { QList<Task> tmp = i->validate(this); foreach (const Task &t, tmp) { if (t.type == Task::Error) d->m_isValid = false; } result.append(tmp); } qSort(result); return result; } void Kit::fix() { KitGuard g(this); foreach (KitInformation *i, KitManager::instance()->kitInformation()) i->fix(this); } QString Kit::displayName() const { return d->m_displayName; } static QString candidateName(const QString &name, const QString &postfix) { if (name.contains(postfix)) return QString(); QString candidate = name; if (!candidate.isEmpty()) candidate.append(QLatin1Char('-')); candidate.append(postfix); return candidate; } void Kit::setDisplayName(const QString &name) { KitManager *km = KitManager::instance(); QList<KitInformation *> kitInfo = km->kitInformation(); QStringList nameList; foreach (Kit *k, km->kits()) { if (k == this) continue; nameList << k->displayName(); foreach (KitInformation *ki, kitInfo) { const QString postfix = ki->displayNamePostfix(k); if (!postfix.isEmpty()) nameList << candidateName(k->displayName(), postfix); } } QStringList candidateNames; candidateNames << name; foreach (KitInformation *ki, kitInfo) { const QString postfix = ki->displayNamePostfix(this); if (!postfix.isEmpty()) candidateNames << candidateName(name, postfix); } QString uniqueName = Project::makeUnique(name, nameList); if (uniqueName != name) { foreach (const QString &candidate, candidateNames) { const QString tmp = Project::makeUnique(candidate, nameList); if (tmp == candidate) { uniqueName = tmp; break; } } } if (d->m_displayName == uniqueName) return; d->m_displayName = uniqueName; kitUpdated(); } QString Kit::fileSystemFriendlyName() const { QString name = cleanName(displayName()); foreach (Kit *i, KitManager::instance()->kits()) { if (i == this) continue; if (name == cleanName(i->displayName())) { // append part of the kit id: That should be unique enough;-) // Leading { will be turned into _ which should be fine. name = cleanName(name + QLatin1Char('_') + (id().toString().left(7))); break; } } return name; } bool Kit::isAutoDetected() const { return d->m_autodetected; } Core::Id Kit::id() const { return d->m_id; } QIcon Kit::icon() const { return d->m_icon; } QString Kit::iconPath() const { return d->m_iconPath; } void Kit::setIconPath(const QString &path) { if (d->m_iconPath == path) return; d->m_iconPath = path; if (path.isNull()) d->m_icon = QIcon(); else if (path == QLatin1String(":///DESKTOP///")) d->m_icon = qApp->style()->standardIcon(QStyle::SP_ComputerIcon); else d->m_icon = QIcon(path); kitUpdated(); } QVariant Kit::value(const Core::Id &key, const QVariant &unset) const { return d->m_data.value(key, unset); } bool Kit::hasValue(const Core::Id &key) const { return d->m_data.contains(key); } void Kit::setValue(const Core::Id &key, const QVariant &value) { if (d->m_data.value(key) == value) return; d->m_data.insert(key, value); kitUpdated(); } void Kit::removeKey(const Core::Id &key) { if (!d->m_data.contains(key)) return; d->m_data.remove(key); kitUpdated(); } bool Kit::isDataEqual(const Kit *other) const { return d->m_data == other->d->m_data; } bool Kit::isEqual(const Kit *other) const { return isDataEqual(other) && d->m_iconPath == other->d->m_iconPath && d->m_displayName == other->d->m_displayName; } QVariantMap Kit::toMap() const { QVariantMap data; data.insert(QLatin1String(ID_KEY), QString::fromLatin1(d->m_id.name())); data.insert(QLatin1String(DISPLAYNAME_KEY), d->m_displayName); data.insert(QLatin1String(AUTODETECTED_KEY), d->m_autodetected); data.insert(QLatin1String(ICON_KEY), d->m_iconPath); QVariantMap extra; foreach (const Core::Id &key, d->m_data.keys()) extra.insert(QString::fromLatin1(key.name().constData()), d->m_data.value(key)); data.insert(QLatin1String(DATA_KEY), extra); return data; } void Kit::addToEnvironment(Utils::Environment &env) const { QList<KitInformation *> infoList = KitManager::instance()->kitInformation(); foreach (KitInformation *ki, infoList) ki->addToEnvironment(this, env); } QString Kit::toHtml() { QString rc; QTextStream str(&rc); str << "<html><body>"; str << "<h3>" << displayName() << "</h3>"; str << "<table>"; if (!isValid()) { QList<Task> issues = validate(); str << "<p>"; foreach (const Task &t, issues) { str << "<b>"; switch (t.type) { case Task::Error: str << QCoreApplication::translate("ProjectExplorer::Kit", "Error:"); break; case Task::Warning: str << QCoreApplication::translate("ProjectExplorer::Kit", "Warning:"); break; case Task::Unknown: default: break; } str << "</b>" << t.description << "<br>"; } str << "</p>"; } QList<KitInformation *> infoList = KitManager::instance()->kitInformation(); foreach (KitInformation *ki, infoList) { KitInformation::ItemList list = ki->toUserOutput(this); foreach (const KitInformation::Item &j, list) str << "<tr><td><b>" << j.first << ":</b></td><td>" << j.second << "</td></tr>"; } str << "</table></body></html>"; return rc; } bool Kit::fromMap(const QVariantMap &data) { KitGuard g(this); const QString id = data.value(QLatin1String(ID_KEY)).toString(); if (id.isEmpty()) return false; d->m_id = Core::Id(id); d->m_autodetected = data.value(QLatin1String(AUTODETECTED_KEY)).toBool(); setDisplayName(data.value(QLatin1String(DISPLAYNAME_KEY)).toString()); setIconPath(data.value(QLatin1String(ICON_KEY)).toString()); QVariantMap extra = data.value(QLatin1String(DATA_KEY)).toMap(); foreach (const QString &key, extra.keys()) setValue(Core::Id(key), extra.value(key)); return true; } void Kit::setAutoDetected(bool detected) { d->m_autodetected = detected; } void Kit::kitUpdated() { if (d->m_nestedBlockingLevel > 0) { d->m_mustNotify = true; return; } validate(); KitManager::instance()->notifyAboutUpdate(this); } } // namespace ProjectExplorer <|endoftext|>
<commit_before>/* // Copyright (c) 2015-2016-2016 Pierre Guillot. // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #include <iostream> #include "test.hpp" extern "C" { #include "../thread/src/thd.h" } #define XPD_TEST_NLOOP 16 #define XPD_TEST_NTHD 4 static xpd::mutex gmutex; class post_tester : private xpd::instance { public: ~post_tester() { if(m_patch) { xpd::instance::close(m_patch); } } bool load(std::string const& name) { m_patch = xpd::instance::load(name, ""); return bool(m_patch); } bool prepare(const int nins, const int nouts, const int samplerate, const int nsamples) { xpd::instance::prepare(nins, nouts, samplerate, nsamples); m_blksize = nsamples; return xpd::instance::samplerate() == samplerate; } void send(std::vector<xpd::atom> const& vec) { xpd::instance::send(m_tfrom, xpd::symbol("list"), vec); } void receive(xpd::console::post const& post) xpd_final { m_counter++; } size_t counter() const xpd_noexcept { return m_counter; } static void test(post_tester* inst) { gmutex.lock(); for(size_t i = 0; i < XPD_TEST_NLOOP; i++) { inst->perform(inst->m_blksize, 0, NULL, 0, NULL); } gmutex.unlock(); } private: xpd::patch m_patch; xpd::tie m_tfrom; xpd::tie m_tto; size_t m_counter; size_t m_blksize; }; TEST_CASE("instance", "[instance post]") { post_tester inst[XPD_TEST_NTHD]; thd_thread thd[XPD_TEST_NTHD]; SECTION("post") { for(size_t i = 0; i < XPD_TEST_NTHD; ++i) { REQUIRE(inst[i].load("test_post.pd")); REQUIRE(inst[i].prepare(0, 0, 44100, 256)); thd_thread_detach(thd+i, (thd_thread_method)(&post_tester::test), inst+i); } for(size_t i = 0; i < XPD_TEST_NTHD; ++i) { thd_thread_join(thd+i); CHECK(inst[i].counter() == XPD_TEST_NLOOP); } } } #undef XPD_TEST_NLOOP <commit_msg>go to all-in-one instance test<commit_after><|endoftext|>
<commit_before>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2008 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include "video_init.h" #include <projectM.hpp> #include "sdltoprojectM.h" #include "ConfigFile.h" #include "getConfigFilename.h" // FIXME: portable includes? // i just added what works for me -fatray #include <GL/gl.h> #include <assert.h> projectM *globalPM= NULL; // window stuff int wvw, wvh, fvw, fvh; bool fullscreen; void renderLoop(); // texture test bool doTextureTest = false; void textureTest(); // memleak test bool doMemleakTest = false; int memLeakIterations = 100; int main(int argc, char **argv) { // fix `fullscreen quit kills mouse` issue. atexit(SDL_Quit); std::string config_filename = getConfigFilename(); ConfigFile config(config_filename); // window dimensions from configfile wvw = config.read<int>("Window Width", 512); wvh = config.read<int>("Window Height", 512); fullscreen = config.read("Fullscreen", true); init_display(wvw, wvh, &fvw, &fvh, fullscreen); SDL_WM_SetCaption(PROJECTM_TITLE, NULL); // memleak test while (doMemleakTest) { static int k = 0; std::cerr << "[iter " << k++ << "]" << std::endl; globalPM = new projectM(config_filename); assert(globalPM); delete (globalPM); if (k >= memLeakIterations) break; } globalPM = new projectM(config_filename); // if started fullscreen, give PM new viewport dimensions if (fullscreen) globalPM->projectM_resetGL(fvw, fvh); renderLoop(); // not reached return 1; } void renderLoop() { while (1) { projectMEvent evt; projectMKeycode key; projectMModifier mod; /** Process SDL events */ SDL_Event event; while (SDL_PollEvent(&event)) { /** Translate into projectM codes and process */ evt = sdl2pmEvent(event); key = sdl2pmKeycode(event.key.keysym.sym); mod = sdl2pmModifier(event.key.keysym.mod); switch (evt) { case PROJECTM_KEYDOWN: switch (key) { case PROJECTM_K_ESCAPE: delete(globalPM); exit(0); break; case PROJECTM_K_f: { fullscreen = !fullscreen; if (fullscreen) { resize_display(fvw, fvh, fullscreen); globalPM->projectM_resetGL(fvw, fvh); } else { resize_display(wvw, wvh, fullscreen); globalPM->projectM_resetGL(wvw, wvh); } break; } case PROJECTM_K_q: exit(1); break; default: globalPM->key_handler(evt, key, mod); } break; case PROJECTM_VIDEORESIZE: wvw = event.resize.w; wvh = event.resize.h; resize_display(wvw, wvh, 0); globalPM->projectM_resetGL(wvw, wvh); break; default: // not for us, give it to projectM globalPM->key_handler(evt, key, mod); break; } } globalPM->renderFrame(); if (doTextureTest) textureTest(); SDL_GL_SwapBuffers(); } } void textureTest() { static int textureHandle = globalPM->initRenderToTexture(); static int frame = 0; frame++; glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (fullscreen) glViewport(0, 0, fvw, fvh); else glViewport(0, 0, wvw, wvh); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1, 1, -1, 1, 2, 10); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(cos(frame*0.023), cos(frame*0.017), -5+sin(frame*0.022)*2); glRotatef(sin(frame*0.0043)*360, sin(frame*0.0017)*360, sin(frame *0.0032) *360, 1); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glBindTexture(GL_TEXTURE_2D, textureHandle); glColor4d(1.0, 1.0, 1.0, 1.0); glBegin(GL_QUADS); glTexCoord2d(0, 1); glVertex3d(-0.8, 0.8, 0); glTexCoord2d(0, 0); glVertex3d(-0.8, -0.8, 0); glTexCoord2d(1, 0); glVertex3d(0.8, -0.8, 0); glTexCoord2d(1, 1); glVertex3d(0.8, 0.8, 0); glEnd(); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glDisable(GL_DEPTH_TEST); } <commit_msg>projectM-test random sound data<commit_after>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2008 projectM Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include "video_init.h" #include <projectM.hpp> #include "sdltoprojectM.h" #include "ConfigFile.h" #include "getConfigFilename.h" #include <stdlib.h> // FIXME: portable includes? // i just added what works for me -fatray #include <GL/gl.h> #include <assert.h> projectM *globalPM= NULL; // window stuff int wvw, wvh, fvw, fvh; bool fullscreen; void renderLoop(); // texture test bool doTextureTest = false; void textureTest(); // memleak test bool doMemleakTest = false; int memLeakIterations = 100; int main(int argc, char **argv) { // fix `fullscreen quit kills mouse` issue. atexit(SDL_Quit); std::string config_filename = getConfigFilename(); ConfigFile config(config_filename); // window dimensions from configfile wvw = config.read<int>("Window Width", 512); wvh = config.read<int>("Window Height", 512); fullscreen = config.read("Fullscreen", true); init_display(wvw, wvh, &fvw, &fvh, fullscreen); SDL_WM_SetCaption(PROJECTM_TITLE, NULL); // memleak test while (doMemleakTest) { static int k = 0; std::cerr << "[iter " << k++ << "]" << std::endl; globalPM = new projectM(config_filename); assert(globalPM); delete (globalPM); if (k >= memLeakIterations) break; } globalPM = new projectM(config_filename); // if started fullscreen, give PM new viewport dimensions if (fullscreen) globalPM->projectM_resetGL(fvw, fvh); renderLoop(); // not reached return 1; } float fakePCM[512]; void renderLoop() { while (1) { projectMEvent evt; projectMKeycode key; projectMModifier mod; /** Process SDL events */ SDL_Event event; while (SDL_PollEvent(&event)) { /** Translate into projectM codes and process */ evt = sdl2pmEvent(event); key = sdl2pmKeycode(event.key.keysym.sym); mod = sdl2pmModifier(event.key.keysym.mod); switch (evt) { case PROJECTM_KEYDOWN: switch (key) { case PROJECTM_K_ESCAPE: delete(globalPM); exit(0); break; case PROJECTM_K_f: { fullscreen = !fullscreen; if (fullscreen) { resize_display(fvw, fvh, fullscreen); globalPM->projectM_resetGL(fvw, fvh); } else { resize_display(wvw, wvh, fullscreen); globalPM->projectM_resetGL(wvw, wvh); } break; } case PROJECTM_K_q: exit(1); break; default: globalPM->key_handler(evt, key, mod); } break; case PROJECTM_VIDEORESIZE: wvw = event.resize.w; wvh = event.resize.h; resize_display(wvw, wvh, 0); globalPM->projectM_resetGL(wvw, wvh); break; default: // not for us, give it to projectM globalPM->key_handler(evt, key, mod); break; } } fakePCM[0]=0; for (int x = 1; x< 512;x++) { fakePCM[x] = fakePCM[x-1] + (rand()%200 - 100) *.002; } globalPM->pcm()->addPCMfloat(fakePCM, 512); globalPM->renderFrame(); if (doTextureTest) textureTest(); SDL_GL_SwapBuffers(); } } void textureTest() { static int textureHandle = globalPM->initRenderToTexture(); static int frame = 0; frame++; glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (fullscreen) glViewport(0, 0, fvw, fvh); else glViewport(0, 0, wvw, wvh); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1, 1, -1, 1, 2, 10); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(cos(frame*0.023), cos(frame*0.017), -5+sin(frame*0.022)*2); glRotatef(sin(frame*0.0043)*360, sin(frame*0.0017)*360, sin(frame *0.0032) *360, 1); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glBindTexture(GL_TEXTURE_2D, textureHandle); glColor4d(1.0, 1.0, 1.0, 1.0); glBegin(GL_QUADS); glTexCoord2d(0, 1); glVertex3d(-0.8, 0.8, 0); glTexCoord2d(0, 0); glVertex3d(-0.8, -0.8, 0); glTexCoord2d(1, 0); glVertex3d(0.8, -0.8, 0); glTexCoord2d(1, 1); glVertex3d(0.8, 0.8, 0); glEnd(); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glDisable(GL_DEPTH_TEST); } <|endoftext|>
<commit_before>#include "DNSDataParser.hpp" audioObject::audioObject () : distance (0) , angle (0) { } speakerData::speakerData () : speakerid ("") , objects{} { } dataParser::dataParser () : _filereader () , _filewriter () { } speakerData dataParser::parseClientData (std::string jsonstring, std::string client_id, std::map<std::string, std::vector<float>>& objects) { Jzon::Node rootNode = _filereader.parseString (jsonstring); speakerData ret_speaker; for (Jzon::NamedNode node : rootNode) { if (node.first == client_id) { ret_speaker.speakerid = node.first; for (Jzon::NamedNode sub_node : node.second) { audioObject object; std::string key = sub_node.first; object.distance = sub_node.second.get ("distance").toFloat (); object.angle = sub_node.second.get ("angle").toFloat (); ret_speaker.objects[key] = object; } } else { for (Jzon::NamedNode sub_node : node.second) { std::string key = sub_node.first; int distance = sub_node.second.get ("distance").toInt (); if (distance != -1) { objects[key].push_back (distance); } } } } return ret_speaker; } std::map<std::string, std::string> dataParser::parseAudioSourceData (std::string jsonstring) { std::map<std::string, std::string> ret; Jzon::Node root_node = _filereader.parseString (jsonstring); for (Jzon::NamedNode sub_node : root_node) { std::string uri, name; name = sub_node.first; uri = sub_node.second.toString (); if (30 < name.length ()) { // truncate string to MAX 30 name.erase (30, std::string::npos); } for (char& c : name) { // replace any non alphanumerical characters if (!isalnum (c)) { c = '_'; } } ret[name] = uri; } return ret; } std::string dataParser::composeClientData (speakerData speaker) { std::string ret_str; Jzon::Node root_node, speaker_node, object_node; for (auto object : speaker.objects) { object_node.add ("distance", object.second.distance); object_node.add ("angle", object.second.angle); speaker_node.add (object.first, object_node); } root_node.add (speaker.speakerid, speaker_node); _filewriter.writeString (root_node, ret_str); return ret_str; } <commit_msg>add support for '.' dots in the object names<commit_after>#include "DNSDataParser.hpp" audioObject::audioObject () : distance (0) , angle (0) { } speakerData::speakerData () : speakerid ("") , objects{} { } dataParser::dataParser () : _filereader () , _filewriter () { } speakerData dataParser::parseClientData (std::string jsonstring, std::string client_id, std::map<std::string, std::vector<float>>& objects) { Jzon::Node rootNode = _filereader.parseString (jsonstring); speakerData ret_speaker; for (Jzon::NamedNode node : rootNode) { if (node.first == client_id) { ret_speaker.speakerid = node.first; for (Jzon::NamedNode sub_node : node.second) { audioObject object; std::string key = sub_node.first; object.distance = sub_node.second.get ("distance").toFloat (); object.angle = sub_node.second.get ("angle").toFloat (); ret_speaker.objects[key] = object; } } else { for (Jzon::NamedNode sub_node : node.second) { std::string key = sub_node.first; int distance = sub_node.second.get ("distance").toInt (); if (distance != -1) { objects[key].push_back (distance); } } } } return ret_speaker; } std::map<std::string, std::string> dataParser::parseAudioSourceData (std::string jsonstring) { std::map<std::string, std::string> ret; Jzon::Node root_node = _filereader.parseString (jsonstring); for (Jzon::NamedNode sub_node : root_node) { std::string uri, name; name = sub_node.first; uri = sub_node.second.toString (); if (30 < name.length ()) { // truncate string to MAX 30 name.erase (30, std::string::npos); } char last_c = '.'; // set '.' to dissalow the name "." for (char& c : name) { // dissalow any special characters if (!isalnum (c)) { // disallow multiple consecutive dots if (!(c == '.' && last_c != '.')) { c = '_'; } last_c = c; } } ret[name] = uri; } return ret; } std::string dataParser::composeClientData (speakerData speaker) { std::string ret_str; Jzon::Node root_node, speaker_node, object_node; for (auto object : speaker.objects) { object_node.add ("distance", object.second.distance); object_node.add ("angle", object.second.angle); speaker_node.add (object.first, object_node); } root_node.add (speaker.speakerid, speaker_node); _filewriter.writeString (root_node, ret_str); return ret_str; } <|endoftext|>
<commit_before>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::Row(const MYSQL_ROW& d, const ResUse* r, unsigned long* jj, bool te) : OptionalExceptions(te), res_(r), initialized_(false) { if (!d || !r) { if (throw_exceptions()) { throw BadQuery("ROW or RES is NULL"); } else { return; } } data_.clear(); is_nulls_.clear(); initialized_ = true; for (unsigned int i = 0; i < size(); i++) { data_.insert(data_.end(), (d[i] ? std::string(d[i], jj[i]) : std::string("NULL"))); is_nulls_.insert(is_nulls_.end(), d[i] ? false : true); } } Row::~Row() { data_.clear(); is_nulls_.clear(); initialized_ = false; } Row::size_type Row::size() const { return res_->num_fields(); } const ColData Row::at(size_type i) const { if (initialized_) { const std::string& s = data_.at(i); return ColData(s.c_str(), s.length(), res_->types(i), is_nulls_[i]); } else { if (throw_exceptions()) throw std::out_of_range("Row not initialized"); else return ColData(); } } const ColData Row::operator [](const char* field) const { size_type si = res_->field_num(std::string(field)); if (si < size()) { return at(si); } else { throw BadFieldName(field); } } value_list_ba<FieldNames, do_nothing_type0> Row::field_list(const char* d) const { return value_list_ba<FieldNames, do_nothing_type0> (parent().names(), d, do_nothing); } template <class Manip> value_list_ba<FieldNames, Manip> Row::field_list(const char *d, Manip m) const { return value_list_ba<FieldNames, Manip>(parent().names(), d, m); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char *d, Manip m, const std::vector<bool>& vb) const { return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char* d, const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char* d, Manip m, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char *d, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } equal_list_ba<FieldNames, Row, quote_type0> Row::equal_list(const char* d, const char* e) const { return equal_list_ba<FieldNames, Row, quote_type0>( parent().names(), *this, d, e, quote); } template <class Manip> equal_list_ba<FieldNames, Row, Manip> Row::equal_list(const char* d, const char* e, Manip m) const { return equal_list_ba<FieldNames, Row, Manip>( parent().names(), *this, d, e, m); } } // end namespace mysqlpp <commit_msg>Minor speed optimizations in the Row() ctor that copies data from a MYSQL_ROW structure, and in Row::size(). Patch by Korolyov Ilya <breeze@begun.ru>.<commit_after>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::Row(const MYSQL_ROW& d, const ResUse* r, unsigned long* jj, bool te) : OptionalExceptions(te), res_(r), initialized_(false) { if (!d || !r) { if (throw_exceptions()) { throw BadQuery("ROW or RES is NULL"); } else { return; } } data_.clear(); is_nulls_.clear(); initialized_ = true; size_type num_fields = size(); for (size_type i = 0; i < num_fields; ++i) { data_.insert(data_.end(), (d[i] ? std::string(d[i], jj[i]) : std::string("NULL"))); is_nulls_.insert(is_nulls_.end(), d[i] ? false : true); } } Row::~Row() { data_.clear(); is_nulls_.clear(); initialized_ = false; } Row::size_type Row::size() const { return data_.size(); } const ColData Row::at(size_type i) const { if (initialized_) { const std::string& s = data_.at(i); return ColData(s.c_str(), s.length(), res_->types(i), is_nulls_[i]); } else { if (throw_exceptions()) throw std::out_of_range("Row not initialized"); else return ColData(); } } const ColData Row::operator [](const char* field) const { size_type si = res_->field_num(std::string(field)); if (si < size()) { return at(si); } else { throw BadFieldName(field); } } value_list_ba<FieldNames, do_nothing_type0> Row::field_list(const char* d) const { return value_list_ba<FieldNames, do_nothing_type0> (parent().names(), d, do_nothing); } template <class Manip> value_list_ba<FieldNames, Manip> Row::field_list(const char *d, Manip m) const { return value_list_ba<FieldNames, Manip>(parent().names(), d, m); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char *d, Manip m, const std::vector<bool>& vb) const { return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char* d, const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char* d, Manip m, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char *d, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } equal_list_ba<FieldNames, Row, quote_type0> Row::equal_list(const char* d, const char* e) const { return equal_list_ba<FieldNames, Row, quote_type0>( parent().names(), *this, d, e, quote); } template <class Manip> equal_list_ba<FieldNames, Row, Manip> Row::equal_list(const char* d, const char* e, Manip m) const { return equal_list_ba<FieldNames, Row, Manip>( parent().names(), *this, d, e, m); } } // end namespace mysqlpp <|endoftext|>
<commit_before>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::size_type Row::size() const { return res->num_fields(); } const ColData Row::operator[] (size_type i) const { if (!initialized) { if (throw_exceptions) throw BadQuery("Row not initialized"); else return ColData(); } return ColData(data.at(i).c_str(), res->types(i), is_nulls[i]); } const ColData Row::lookup_by_name(const char* i) const { int si = res->field_num(std::string(i)); if (si < res->num_fields()) { return (*this)[si]; } else { throw BadFieldName(i); } } } // end namespace mysqlpp <commit_msg>Whitespace change<commit_after>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::size_type Row::size() const { return res->num_fields(); } const ColData Row::operator [](size_type i) const { if (!initialized) { if (throw_exceptions) throw BadQuery("Row not initialized"); else return ColData(); } return ColData(data.at(i).c_str(), res->types(i), is_nulls[i]); } const ColData Row::lookup_by_name(const char* i) const { int si = res->field_num(std::string(i)); if (si < res->num_fields()) { return (*this)[si]; } else { throw BadFieldName(i); } } } // end namespace mysqlpp <|endoftext|>
<commit_before>// FIXME: The first two includes should probably be swapped! #include "HalideRuntime.h" #include "runtime_internal.h" #include "printer.h" namespace Halide { namespace Runtime { namespace Internal { WEAK void default_error_handler(void *user_context, const char *msg) { char buf[4096]; char *dst = halide_string_to_string(buf, buf + 4095, "Error: "); dst = halide_string_to_string(dst, buf + 4095, msg); // We still have one character free. Add a newline if there // isn't one already. if (dst[-1] != '\n') { dst[0] = '\n'; dst[1] = 0; } halide_print(user_context, buf); abort(); } WEAK void (*halide_error_handler)(void *, const char *) = default_error_handler; }}} // namespace Halide::Runtime::Internal extern "C" { WEAK void halide_error(void *user_context, const char *msg) { (*halide_error_handler)(user_context, msg); } WEAK void (*halide_set_error_handler(void (*handler)(void *, const char *)))(void *, const char *) { void (*result)(void *, const char *) = halide_error_handler; halide_error_handler = handler; return result; } WEAK int halide_error_bounds_inference_call_failed(void *user_context, const char *extern_stage_name, int result) { error(user_context) << "Bounds inference call to external stage " << extern_stage_name << " returned non-zero value: " << result; return result; } WEAK int halide_error_extern_stage_failed(void *user_context, const char *extern_stage_name, int result) { error(user_context) << "Call to external stage " << extern_stage_name << " returned non-zero value: " << result; return result; } WEAK int halide_error_explicit_bounds_too_small(void *user_context, const char *func_name, const char *var_name, int min_bound, int max_bound, int min_required, int max_required) { error(user_context) << "Bounds given for " << var_name << " in " << func_name << " (from " << min_bound << " to " << max_bound << ") do not cover required region (from " << min_required << " to " << max_required << ")"; return halide_error_code_explicit_bounds_too_small; } WEAK int halide_error_bad_elem_size(void *user_context, const char *func_name, const char *type_name, int elem_size_given, int correct_elem_size) { error(user_context) << func_name << " has type " << type_name << " but elem_size of the buffer passed in is " << elem_size_given << " instead of " << correct_elem_size; return halide_error_code_bad_elem_size; } WEAK int halide_error_access_out_of_bounds(void *user_context, const char *func_name, int dimension, int min_touched, int max_touched, int min_valid, int max_valid) { if (min_touched < min_valid) { error(user_context) << func_name << " is accessed at " << min_touched << ", which is before the min (" << min_valid << ") in dimension " << dimension; } else if (max_touched > max_valid) { error(user_context) << func_name << " is accessed at " << max_touched << ", which is beyond the max (" << max_valid << ") in dimension " << dimension; } return halide_error_code_access_out_of_bounds; } WEAK int halide_error_buffer_allocation_too_large(void *user_context, const char *buffer_name, int64_t allocation_size, int64_t max_size) { error(user_context) << "Total allocation for buffer " << buffer_name << " is " << allocation_size << ", which exceeds the maximum size of " << max_size; return halide_error_code_buffer_allocation_too_large; } WEAK int halide_error_buffer_extents_too_large(void *user_context, const char *buffer_name, int64_t actual_size, int64_t max_size) { error(user_context) << "Product of extents for buffer " << buffer_name << " is " << actual_size << ", which exceeds the maximum size of " << max_size; return halide_error_code_buffer_extents_too_large; } WEAK int halide_error_constraints_make_required_region_smaller(void *user_context, const char *buffer_name, int dimension, int constrained_min, int constrained_extent, int required_min, int required_extent) { int required_max = required_min + required_extent - 1; int constrained_max = constrained_min + required_extent - 1; error(user_context) << "Applying the constraints on " << buffer_name << " to the required region made it smaller. " << "Required size: " << required_min << " to " << required_max << ". " << "Constrained size: " << constrained_min << " to " << constrained_max << "."; return halide_error_code_constraints_make_required_region_smaller; } WEAK int halide_error_constraint_violated(void *user_context, const char *var, int val, const char *constrained_var, int constrained_val) { error(user_context) << "Constraint violated: " << var << " (" << val << ") == " << constrained_var << " (" << constrained_var << ")"; return halide_error_code_constraint_violated; } WEAK int halide_error_param_too_small_i64(void *user_context, const char *param_name, int64_t val, int64_t min_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at least " << min_val; return halide_error_code_param_too_small; } WEAK int halide_error_param_too_small_u64(void *user_context, const char *param_name, uint64_t val, uint64_t min_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at least " << min_val; return halide_error_code_param_too_small; } WEAK int halide_error_param_too_small_f64(void *user_context, const char *param_name, double val, double min_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at least " << min_val; return halide_error_code_param_too_small; } WEAK int halide_error_param_too_large_i64(void *user_context, const char *param_name, int64_t val, int64_t max_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at most " << max_val; return halide_error_code_param_too_large; } WEAK int halide_error_param_too_large_u64(void *user_context, const char *param_name, uint64_t val, uint64_t max_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at most " << max_val; return halide_error_code_param_too_large; } WEAK int halide_error_param_too_large_f64(void *user_context, const char *param_name, double val, double max_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at most " << max_val; return halide_error_code_param_too_large; } WEAK int halide_error_out_of_memory(void *user_context) { // The error message builder uses malloc, so we can't use it here. halide_error(user_context, "Out of memory (halide_malloc returned NULL)"); return halide_error_code_out_of_memory; } WEAK int halide_error_buffer_argument_is_null(void *user_context, const char *buffer_name) { error(user_context) << "Buffer argument " << buffer_name << " is NULL"; return halide_error_code_buffer_argument_is_null; } WEAK int halide_error_debug_to_file_failed(void *user_context, const char *func, const char *filename, int error_code) { error(user_context) << "Failed to dump function " << func << " to file " << filename << " with error " << error_code; return halide_error_code_debug_to_file_failed; } } <commit_msg>For uniformity with other runtime source files swap the ``runtime_internal.h`` and ``HalideRuntime.h`` includes in ``posix_error_handler.cpp``. This should be a non functional change because if ``HalideRuntime.h`` is included while compiling the runtime ``runtime_internal.h`` should automatically get included first.<commit_after>#include "runtime_internal.h" #include "HalideRuntime.h" #include "printer.h" namespace Halide { namespace Runtime { namespace Internal { WEAK void default_error_handler(void *user_context, const char *msg) { char buf[4096]; char *dst = halide_string_to_string(buf, buf + 4095, "Error: "); dst = halide_string_to_string(dst, buf + 4095, msg); // We still have one character free. Add a newline if there // isn't one already. if (dst[-1] != '\n') { dst[0] = '\n'; dst[1] = 0; } halide_print(user_context, buf); abort(); } WEAK void (*halide_error_handler)(void *, const char *) = default_error_handler; }}} // namespace Halide::Runtime::Internal extern "C" { WEAK void halide_error(void *user_context, const char *msg) { (*halide_error_handler)(user_context, msg); } WEAK void (*halide_set_error_handler(void (*handler)(void *, const char *)))(void *, const char *) { void (*result)(void *, const char *) = halide_error_handler; halide_error_handler = handler; return result; } WEAK int halide_error_bounds_inference_call_failed(void *user_context, const char *extern_stage_name, int result) { error(user_context) << "Bounds inference call to external stage " << extern_stage_name << " returned non-zero value: " << result; return result; } WEAK int halide_error_extern_stage_failed(void *user_context, const char *extern_stage_name, int result) { error(user_context) << "Call to external stage " << extern_stage_name << " returned non-zero value: " << result; return result; } WEAK int halide_error_explicit_bounds_too_small(void *user_context, const char *func_name, const char *var_name, int min_bound, int max_bound, int min_required, int max_required) { error(user_context) << "Bounds given for " << var_name << " in " << func_name << " (from " << min_bound << " to " << max_bound << ") do not cover required region (from " << min_required << " to " << max_required << ")"; return halide_error_code_explicit_bounds_too_small; } WEAK int halide_error_bad_elem_size(void *user_context, const char *func_name, const char *type_name, int elem_size_given, int correct_elem_size) { error(user_context) << func_name << " has type " << type_name << " but elem_size of the buffer passed in is " << elem_size_given << " instead of " << correct_elem_size; return halide_error_code_bad_elem_size; } WEAK int halide_error_access_out_of_bounds(void *user_context, const char *func_name, int dimension, int min_touched, int max_touched, int min_valid, int max_valid) { if (min_touched < min_valid) { error(user_context) << func_name << " is accessed at " << min_touched << ", which is before the min (" << min_valid << ") in dimension " << dimension; } else if (max_touched > max_valid) { error(user_context) << func_name << " is accessed at " << max_touched << ", which is beyond the max (" << max_valid << ") in dimension " << dimension; } return halide_error_code_access_out_of_bounds; } WEAK int halide_error_buffer_allocation_too_large(void *user_context, const char *buffer_name, int64_t allocation_size, int64_t max_size) { error(user_context) << "Total allocation for buffer " << buffer_name << " is " << allocation_size << ", which exceeds the maximum size of " << max_size; return halide_error_code_buffer_allocation_too_large; } WEAK int halide_error_buffer_extents_too_large(void *user_context, const char *buffer_name, int64_t actual_size, int64_t max_size) { error(user_context) << "Product of extents for buffer " << buffer_name << " is " << actual_size << ", which exceeds the maximum size of " << max_size; return halide_error_code_buffer_extents_too_large; } WEAK int halide_error_constraints_make_required_region_smaller(void *user_context, const char *buffer_name, int dimension, int constrained_min, int constrained_extent, int required_min, int required_extent) { int required_max = required_min + required_extent - 1; int constrained_max = constrained_min + required_extent - 1; error(user_context) << "Applying the constraints on " << buffer_name << " to the required region made it smaller. " << "Required size: " << required_min << " to " << required_max << ". " << "Constrained size: " << constrained_min << " to " << constrained_max << "."; return halide_error_code_constraints_make_required_region_smaller; } WEAK int halide_error_constraint_violated(void *user_context, const char *var, int val, const char *constrained_var, int constrained_val) { error(user_context) << "Constraint violated: " << var << " (" << val << ") == " << constrained_var << " (" << constrained_var << ")"; return halide_error_code_constraint_violated; } WEAK int halide_error_param_too_small_i64(void *user_context, const char *param_name, int64_t val, int64_t min_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at least " << min_val; return halide_error_code_param_too_small; } WEAK int halide_error_param_too_small_u64(void *user_context, const char *param_name, uint64_t val, uint64_t min_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at least " << min_val; return halide_error_code_param_too_small; } WEAK int halide_error_param_too_small_f64(void *user_context, const char *param_name, double val, double min_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at least " << min_val; return halide_error_code_param_too_small; } WEAK int halide_error_param_too_large_i64(void *user_context, const char *param_name, int64_t val, int64_t max_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at most " << max_val; return halide_error_code_param_too_large; } WEAK int halide_error_param_too_large_u64(void *user_context, const char *param_name, uint64_t val, uint64_t max_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at most " << max_val; return halide_error_code_param_too_large; } WEAK int halide_error_param_too_large_f64(void *user_context, const char *param_name, double val, double max_val) { error(user_context) << "Parameter " << param_name << " is " << val << " but must be at most " << max_val; return halide_error_code_param_too_large; } WEAK int halide_error_out_of_memory(void *user_context) { // The error message builder uses malloc, so we can't use it here. halide_error(user_context, "Out of memory (halide_malloc returned NULL)"); return halide_error_code_out_of_memory; } WEAK int halide_error_buffer_argument_is_null(void *user_context, const char *buffer_name) { error(user_context) << "Buffer argument " << buffer_name << " is NULL"; return halide_error_code_buffer_argument_is_null; } WEAK int halide_error_debug_to_file_failed(void *user_context, const char *func, const char *filename, int error_code) { error(user_context) << "Failed to dump function " << func << " to file " << filename << " with error " << error_code; return halide_error_code_debug_to_file_failed; } } <|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 1999-2016 Vaclav Slavik * Copyright (C) 2005 Olivier Sannier * * 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 "cat_sorting.h" #include <unicode/unistr.h> #include "str_helpers.h" #include <wx/config.h> #include <wx/log.h> /*static*/ SortOrder SortOrder::Default() { SortOrder order; wxString by = wxConfig::Get()->Read("/sort_by", "file-order"); long ctxt = wxConfig::Get()->Read("/sort_group_by_context", 0L); long untrans = wxConfig::Get()->Read("/sort_untrans_first", 0L); long errors = wxConfig::Get()->Read("/sort_errors_first", 1L); if ( by == "source" ) order.by = By_Source; else if ( by == "translation" ) order.by = By_Translation; else order.by = By_FileOrder; order.groupByContext = (ctxt != 0); order.untransFirst = (untrans != 0); order.errorsFirst = (errors != 0); return order; } void SortOrder::Save() { wxString bystr; switch ( by ) { case By_FileOrder: bystr = "file-order"; break; case By_Source: bystr = "source"; break; case By_Translation: bystr = "translation"; break; } wxConfig::Get()->Write("/sort_by", bystr); wxConfig::Get()->Write("/sort_group_by_context", groupByContext); wxConfig::Get()->Write("/sort_untrans_first", untransFirst); wxConfig::Get()->Write("/sort_errors_first", errorsFirst); } CatalogItemsComparator::CatalogItemsComparator(const Catalog& catalog, const SortOrder& order) : m_catalog(catalog), m_order(order) { UErrorCode err = U_ZERO_ERROR; switch (m_order.by) { case SortOrder::By_Source: // TODO: allow non-English source languages too m_collator.reset(icu::Collator::createInstance(catalog.GetSourceLanguage().ToIcu(), err)); break; case SortOrder::By_Translation: m_collator.reset(icu::Collator::createInstance(catalog.GetLanguage().ToIcu(), err)); break; case SortOrder::By_FileOrder: break; } if (!U_SUCCESS(err) || err == U_USING_FALLBACK_WARNING) { wxLogTrace("poedit", "warning: not using collation for %s (%s)", catalog.GetLanguage().Code(), u_errorName(err)); } if (m_collator) { // Case-insensitive comparison: m_collator->setStrength(icu::Collator::SECONDARY); } } bool CatalogItemsComparator::operator()(int i, int j) const { const CatalogItem& a = Item(i); const CatalogItem& b = Item(j); if ( m_order.errorsFirst ) { if ( a.GetValidity() == CatalogItem::Val_Invalid && b.GetValidity() != CatalogItem::Val_Invalid ) return true; else if ( a.GetValidity() != CatalogItem::Val_Invalid && b.GetValidity() == CatalogItem::Val_Invalid ) return false; } if ( m_order.untransFirst ) { if ( !a.IsTranslated() && b.IsTranslated() ) return true; else if ( a.IsTranslated() && !b.IsTranslated() ) return false; if ( a.IsFuzzy() && !b.IsFuzzy() ) return true; else if ( !a.IsFuzzy() && b.IsFuzzy() ) return false; } if ( m_order.groupByContext ) { if ( a.HasContext() && !b.HasContext() ) return true; else if ( !a.HasContext() && b.HasContext() ) return false; else if ( a.HasContext() && b.HasContext() ) { int r = CompareStrings(a.GetContext(), b.GetContext()); if ( r != 0 ) return r < 0; } } switch ( m_order.by ) { case SortOrder::By_FileOrder: { return i < j; } case SortOrder::By_Source: { int r = CompareStrings(a.GetString(), b.GetString()); if ( r != 0 ) return r < 0; break; } case SortOrder::By_Translation: { int r = CompareStrings(a.GetTranslation(), b.GetTranslation()); if ( r != 0 ) return r < 0; break; } } // As last resort, sort by position in file. Note that this means that // no two items are considered equal w.r.t. sort order; this ensures stable // ordering. return i < j; } int CatalogItemsComparator::CompareStrings(wxString a, wxString b) const { a.Replace("&", ""); a.Replace("_", ""); b.Replace("&", ""); b.Replace("_", ""); if (m_collator) { UErrorCode err = U_ZERO_ERROR; #if wxUSE_UNICODE_UTF8 return m_collator->compareUTF8(a.wx_str(), b.wx_str(), err); #elif SIZEOF_WCHAR_T == 2 return m_collator->compare(a.wx_str(), a.length(), b.wx_str(), b.length(), err); #else return m_collator->compare(str::to_icu(a), str::to_icu(b), err); #endif } else { return a.CmpNoCase(b); } } <commit_msg>Remove outdated TODO comment<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 1999-2016 Vaclav Slavik * Copyright (C) 2005 Olivier Sannier * * 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 "cat_sorting.h" #include <unicode/unistr.h> #include "str_helpers.h" #include <wx/config.h> #include <wx/log.h> /*static*/ SortOrder SortOrder::Default() { SortOrder order; wxString by = wxConfig::Get()->Read("/sort_by", "file-order"); long ctxt = wxConfig::Get()->Read("/sort_group_by_context", 0L); long untrans = wxConfig::Get()->Read("/sort_untrans_first", 0L); long errors = wxConfig::Get()->Read("/sort_errors_first", 1L); if ( by == "source" ) order.by = By_Source; else if ( by == "translation" ) order.by = By_Translation; else order.by = By_FileOrder; order.groupByContext = (ctxt != 0); order.untransFirst = (untrans != 0); order.errorsFirst = (errors != 0); return order; } void SortOrder::Save() { wxString bystr; switch ( by ) { case By_FileOrder: bystr = "file-order"; break; case By_Source: bystr = "source"; break; case By_Translation: bystr = "translation"; break; } wxConfig::Get()->Write("/sort_by", bystr); wxConfig::Get()->Write("/sort_group_by_context", groupByContext); wxConfig::Get()->Write("/sort_untrans_first", untransFirst); wxConfig::Get()->Write("/sort_errors_first", errorsFirst); } CatalogItemsComparator::CatalogItemsComparator(const Catalog& catalog, const SortOrder& order) : m_catalog(catalog), m_order(order) { UErrorCode err = U_ZERO_ERROR; switch (m_order.by) { case SortOrder::By_Source: m_collator.reset(icu::Collator::createInstance(catalog.GetSourceLanguage().ToIcu(), err)); break; case SortOrder::By_Translation: m_collator.reset(icu::Collator::createInstance(catalog.GetLanguage().ToIcu(), err)); break; case SortOrder::By_FileOrder: break; } if (!U_SUCCESS(err) || err == U_USING_FALLBACK_WARNING) { wxLogTrace("poedit", "warning: not using collation for %s (%s)", catalog.GetLanguage().Code(), u_errorName(err)); } if (m_collator) { // Case-insensitive comparison: m_collator->setStrength(icu::Collator::SECONDARY); } } bool CatalogItemsComparator::operator()(int i, int j) const { const CatalogItem& a = Item(i); const CatalogItem& b = Item(j); if ( m_order.errorsFirst ) { if ( a.GetValidity() == CatalogItem::Val_Invalid && b.GetValidity() != CatalogItem::Val_Invalid ) return true; else if ( a.GetValidity() != CatalogItem::Val_Invalid && b.GetValidity() == CatalogItem::Val_Invalid ) return false; } if ( m_order.untransFirst ) { if ( !a.IsTranslated() && b.IsTranslated() ) return true; else if ( a.IsTranslated() && !b.IsTranslated() ) return false; if ( a.IsFuzzy() && !b.IsFuzzy() ) return true; else if ( !a.IsFuzzy() && b.IsFuzzy() ) return false; } if ( m_order.groupByContext ) { if ( a.HasContext() && !b.HasContext() ) return true; else if ( !a.HasContext() && b.HasContext() ) return false; else if ( a.HasContext() && b.HasContext() ) { int r = CompareStrings(a.GetContext(), b.GetContext()); if ( r != 0 ) return r < 0; } } switch ( m_order.by ) { case SortOrder::By_FileOrder: { return i < j; } case SortOrder::By_Source: { int r = CompareStrings(a.GetString(), b.GetString()); if ( r != 0 ) return r < 0; break; } case SortOrder::By_Translation: { int r = CompareStrings(a.GetTranslation(), b.GetTranslation()); if ( r != 0 ) return r < 0; break; } } // As last resort, sort by position in file. Note that this means that // no two items are considered equal w.r.t. sort order; this ensures stable // ordering. return i < j; } int CatalogItemsComparator::CompareStrings(wxString a, wxString b) const { a.Replace("&", ""); a.Replace("_", ""); b.Replace("&", ""); b.Replace("_", ""); if (m_collator) { UErrorCode err = U_ZERO_ERROR; #if wxUSE_UNICODE_UTF8 return m_collator->compareUTF8(a.wx_str(), b.wx_str(), err); #elif SIZEOF_WCHAR_T == 2 return m_collator->compare(a.wx_str(), a.length(), b.wx_str(), b.length(), err); #else return m_collator->compare(str::to_icu(a), str::to_icu(b), err); #endif } else { return a.CmpNoCase(b); } } <|endoftext|>
<commit_before>#include <nan.h> #include <iostream> #include <unordered_map> #include <string> #include "FractalGenerator.h" #define JS_LENGTH_CHECK(info, length) if (info.Length() < length) { \ Nan::ThrowTypeError("Wrong number of arguments, must be at least " #length); \ return; \ } #define JS_TYPE_CHECK(info, index, typeCheck) if (!info[index]->typeCheck()) { \ Nan::ThrowTypeError("Wrong argument type, failed test " #typeCheck); \ return; \ } std::unordered_map<std::string, FractalGenerator *> generators; typedef struct { v8::Global<v8::Function> jsCallback; std::string id; } FractalData; void fractalDoneCallback(v8::Isolate *isolate, v8::Local<v8::Object> buffer, bool halted, void *customData) { FractalData *fd = (FractalData *) customData; v8::Local<v8::Function> func = fd->jsCallback.Get(isolate); v8::Local<v8::Value> args[] = { Nan::New(halted), buffer }; func->Call(isolate->GetCurrentContext(), func, 2, args); generators.erase(fd->id); fd->jsCallback.Reset(); delete fd; } void createFractalGenerator(const Nan::FunctionCallbackInfo<v8::Value> &info) { /* * Args: * String uuid : frctal id * Function doneCallback : callback for when the fractal is done * Buffer buffer : the buffer the fractal should write to * Int width : the image width of the fractal * Int height : the image height of the fractal * Double fractalWidth : the complex width (real) of the fractal * Double fractalHeight : the complex height (imaginary) of the fractal * Double fractalX : the complex x (real) start of the fractal (x+ is right) * Double fractalY : the complex y (imaginary) start of the fractal (y+ is down) * Int iterations : the number of iterations before a pixel turns black */ // type checks JS_LENGTH_CHECK(info, 10) JS_TYPE_CHECK(info, 0, IsString) JS_TYPE_CHECK(info, 1, IsFunction) JS_TYPE_CHECK(info, 2, IsObject) JS_TYPE_CHECK(info, 3, IsNumber) JS_TYPE_CHECK(info, 4, IsNumber) JS_TYPE_CHECK(info, 5, IsNumber) JS_TYPE_CHECK(info, 6, IsNumber) JS_TYPE_CHECK(info, 7, IsNumber) JS_TYPE_CHECK(info, 8, IsNumber) JS_TYPE_CHECK(info, 9, IsNumber) // get args std::string uuid(*v8::String::Utf8Value(info[0])); v8::Local<v8::Function> doneCallback = info[1].As<v8::Function>(); v8::Local<v8::Object> buffer = info[2]->ToObject(); int width = info[3]->Int32Value(); int height = info[4]->Int32Value(); double fractalWidth = info[5]->NumberValue(); double fractalHeight = info[6]->NumberValue(); double fractalX = info[7]->NumberValue(); double fractalY = info[8]->NumberValue(); int iterations = info[9]->Int32Value(); FractalData *fd = new FractalData; fd->id = uuid; fd->jsCallback = v8::Global<v8::Function>(); fd->jsCallback.Reset(info.GetIsolate(), doneCallback); FractalGenerator *gen = new FractalGenerator(uuid, info.GetIsolate(), fractalDoneCallback, buffer, fd, width, height, fractalWidth, fractalHeight, fractalX, fractalY, iterations); generators.insert(std::pair<std::string, FractalGenerator *>(uuid, gen)); } void startGenerator(const Nan::FunctionCallbackInfo<v8::Value> &info) { /* * Args: * String uuid : uuid of the fractal */ JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); if (generators.find(uuid) != generators.end()) { generators[uuid]->start(); } else { Nan::ThrowRangeError( (std::string("No fractal with uuid ") + uuid).c_str()); } } void getProgress(const Nan::FunctionCallbackInfo<v8::Value> &info) { // uuid is argument JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); if (generators.find(uuid) != generators.end()) { info.GetReturnValue().Set(generators[uuid]->getProgress()); } else { Nan::ThrowRangeError( (std::string("No fractal with uuid ") + uuid).c_str()); } } void containsFractal(const Nan::FunctionCallbackInfo<v8::Value> &info) { // uuid is argument JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); info.GetReturnValue().Set(generators.find(uuid) != generators.end()); } void listFractals(const Nan::FunctionCallbackInfo<v8::Value> &info) { // no arguments v8::Local<v8::Array> fractals = Nan::New<v8::Array>(generators.size()); auto it = generators.begin(); for (int i = 0; i < generators.size(); i++) { fractals->Set(i, Nan::New(it->first).ToLocalChecked()); it++; } info.GetReturnValue().Set(fractals); } void haltFractal(const Nan::FunctionCallbackInfo<v8::Value> &info) { // uuid is argument JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); if (generators.find(uuid) != generators.end()) { generators[uuid]->halt(); } else { Nan::ThrowRangeError( (std::string("No fractal with uuid ") + uuid).c_str()); } } void haltAllFractals(const Nan::FunctionCallbackInfo<v8::Value> &info) { // no arguments for (const auto &elem : generators) { elem.second->halt(); } } void init(v8::Local<v8::Object> exports) { exports->Set(Nan::New("createFractalGenerator").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(createFractalGenerator)->GetFunction()); exports->Set(Nan::New("startGenerator").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(startGenerator)->GetFunction()); exports->Set(Nan::New("getProgress").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(getProgress)->GetFunction()); exports->Set(Nan::New("containsFractal").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(containsFractal)->GetFunction()); } NODE_MODULE(fractal_service_native, init) <commit_msg>Add api pointers to new functions<commit_after>#include <nan.h> #include <iostream> #include <unordered_map> #include <string> #include "FractalGenerator.h" #define JS_LENGTH_CHECK(info, length) if (info.Length() < length) { \ Nan::ThrowTypeError("Wrong number of arguments, must be at least " #length); \ return; \ } #define JS_TYPE_CHECK(info, index, typeCheck) if (!info[index]->typeCheck()) { \ Nan::ThrowTypeError("Wrong argument type, failed test " #typeCheck); \ return; \ } std::unordered_map<std::string, FractalGenerator *> generators; typedef struct { v8::Global<v8::Function> jsCallback; std::string id; } FractalData; void fractalDoneCallback(v8::Isolate *isolate, v8::Local<v8::Object> buffer, bool halted, void *customData) { FractalData *fd = (FractalData *) customData; v8::Local<v8::Function> func = fd->jsCallback.Get(isolate); v8::Local<v8::Value> args[] = { Nan::New(halted), buffer }; func->Call(isolate->GetCurrentContext(), func, 2, args); generators.erase(fd->id); fd->jsCallback.Reset(); delete fd; } void createFractalGenerator(const Nan::FunctionCallbackInfo<v8::Value> &info) { /* * Args: * String uuid : frctal id * Function doneCallback : callback for when the fractal is done * Buffer buffer : the buffer the fractal should write to * Int width : the image width of the fractal * Int height : the image height of the fractal * Double fractalWidth : the complex width (real) of the fractal * Double fractalHeight : the complex height (imaginary) of the fractal * Double fractalX : the complex x (real) start of the fractal (x+ is right) * Double fractalY : the complex y (imaginary) start of the fractal (y+ is down) * Int iterations : the number of iterations before a pixel turns black */ // type checks JS_LENGTH_CHECK(info, 10) JS_TYPE_CHECK(info, 0, IsString) JS_TYPE_CHECK(info, 1, IsFunction) JS_TYPE_CHECK(info, 2, IsObject) JS_TYPE_CHECK(info, 3, IsNumber) JS_TYPE_CHECK(info, 4, IsNumber) JS_TYPE_CHECK(info, 5, IsNumber) JS_TYPE_CHECK(info, 6, IsNumber) JS_TYPE_CHECK(info, 7, IsNumber) JS_TYPE_CHECK(info, 8, IsNumber) JS_TYPE_CHECK(info, 9, IsNumber) // get args std::string uuid(*v8::String::Utf8Value(info[0])); v8::Local<v8::Function> doneCallback = info[1].As<v8::Function>(); v8::Local<v8::Object> buffer = info[2]->ToObject(); int width = info[3]->Int32Value(); int height = info[4]->Int32Value(); double fractalWidth = info[5]->NumberValue(); double fractalHeight = info[6]->NumberValue(); double fractalX = info[7]->NumberValue(); double fractalY = info[8]->NumberValue(); int iterations = info[9]->Int32Value(); FractalData *fd = new FractalData; fd->id = uuid; fd->jsCallback = v8::Global<v8::Function>(); fd->jsCallback.Reset(info.GetIsolate(), doneCallback); FractalGenerator *gen = new FractalGenerator(uuid, info.GetIsolate(), fractalDoneCallback, buffer, fd, width, height, fractalWidth, fractalHeight, fractalX, fractalY, iterations); generators.insert(std::pair<std::string, FractalGenerator *>(uuid, gen)); } void startGenerator(const Nan::FunctionCallbackInfo<v8::Value> &info) { /* * Args: * String uuid : uuid of the fractal */ JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); if (generators.find(uuid) != generators.end()) { generators[uuid]->start(); } else { Nan::ThrowRangeError( (std::string("No fractal with uuid ") + uuid).c_str()); } } void getProgress(const Nan::FunctionCallbackInfo<v8::Value> &info) { // uuid is argument JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); if (generators.find(uuid) != generators.end()) { info.GetReturnValue().Set(generators[uuid]->getProgress()); } else { Nan::ThrowRangeError( (std::string("No fractal with uuid ") + uuid).c_str()); } } void containsFractal(const Nan::FunctionCallbackInfo<v8::Value> &info) { // uuid is argument JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); info.GetReturnValue().Set(generators.find(uuid) != generators.end()); } void listFractals(const Nan::FunctionCallbackInfo<v8::Value> &info) { // no arguments v8::Local<v8::Array> fractals = Nan::New<v8::Array>(generators.size()); auto it = generators.begin(); for (int i = 0; i < generators.size(); i++) { fractals->Set(i, Nan::New(it->first).ToLocalChecked()); it++; } info.GetReturnValue().Set(fractals); } void haltFractal(const Nan::FunctionCallbackInfo<v8::Value> &info) { // uuid is argument JS_LENGTH_CHECK(info, 1) JS_TYPE_CHECK(info, 0, IsString) std::string uuid(*v8::String::Utf8Value(info[0])); if (generators.find(uuid) != generators.end()) { generators[uuid]->halt(); } else { Nan::ThrowRangeError( (std::string("No fractal with uuid ") + uuid).c_str()); } } void haltAllFractals(const Nan::FunctionCallbackInfo<v8::Value> &info) { // no arguments for (const auto &elem : generators) { elem.second->halt(); } } void init(v8::Local<v8::Object> exports) { exports->Set(Nan::New("createFractalGenerator").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(createFractalGenerator)->GetFunction()); exports->Set(Nan::New("startGenerator").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(startGenerator)->GetFunction()); exports->Set(Nan::New("getProgress").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(getProgress)->GetFunction()); exports->Set(Nan::New("containsFractal").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(containsFractal)->GetFunction()); exports->Set(Nan::New("listFractals").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(listFractals)->GetFunction()); exports->Set(Nan::New("haltFractal").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(haltFractal)->GetFunction()); exports->Set(Nan::New("haltAllFractals").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(haltAllFractals)->GetFunction()); } NODE_MODULE(fractal_service_native, init) <|endoftext|>
<commit_before>#include "heart_cell_sim.h" #include <QApplication> #include <QSettings> #include <QMessageBox> int main(int argc, char *argv[]) { QApplication a(argc, argv); QCoreApplication::setOrganizationName("Hund lab BME OSU"); QCoreApplication::setOrganizationDomain("http://hundlab.org"); QCoreApplication::setApplicationName("LongQt"); Simulation window; window.show(); QSettings settings; if(settings.value("showHelp",true).toBool() &&QMessageBox::Discard == QMessageBox::information(0,"Welcome!", "LongQt is a program for modeling cardiac potentials. As you go through this program keep a few things in mind. First, if you would like more information about something hover your mouse above its name and information will pop up. Second, default values have been provided for all options so if you don't know what an option does it's ok to simply skip it. And finally have fun!\n If you would like to re-enable this text after discarding it use the Restore Defaults button in the About dialog." ,QMessageBox::Ok|QMessageBox::Discard,QMessageBox::Ok)) { settings.setValue("showHelp",false); } return a.exec(); } <commit_msg>changed from discard to ignore<commit_after>#include "heart_cell_sim.h" #include <QApplication> #include <QSettings> #include <QMessageBox> int main(int argc, char *argv[]) { QApplication a(argc, argv); QCoreApplication::setOrganizationName("Hund lab BME OSU"); QCoreApplication::setOrganizationDomain("http://hundlab.org"); QCoreApplication::setApplicationName("LongQt"); Simulation window; window.show(); QSettings settings; if(settings.value("showHelp",true).toBool() &&QMessageBox::Ignore == QMessageBox::information(0,"Welcome!", "LongQt is a program for modeling cardiac potentials. As you go through this program keep a few things in mind. First, if you would like more information about something hover your mouse above its name and information will pop up. Second, default values have been provided for all options so if you don't know what an option does it's ok to simply skip it. And finally have fun!\n If you would like to re-enable this text after discarding it use the Restore Defaults button in the About dialog." ,QMessageBox::Ok|QMessageBox::Ignore,QMessageBox::Ok)) { settings.setValue("showHelp",false); } return a.exec(); } <|endoftext|>
<commit_before>#pragma once #include <Word.hxx> #define _E(rest) E##rest##_ = E##rest namespace linux { template <typename Success, typename Failure> struct Result { explicit operator bool() const { return this->__word > 0xFFFFFFFFFFFFF000UL; } Failure failure() const { return static_cast<Failure>(-this->__word); } Success success() const { return static_cast<Success>(this->__word); } //---------------------------------------------------------------------------------------------- Word __word; }; } <commit_msg>if (auto _ = …) → switch (auto _ = …)<commit_after>#pragma once #include <Word.hxx> #define _E(rest) E##rest##_ = E##rest namespace linux { template <typename Success, typename Failure> struct Result { enum Kind { SUCCESS, FAILURE }; operator Kind() const { return __builtin_expect(this->__word <= 0xFFFFFFFFFFFFF000UL, 1) ? SUCCESS : FAILURE; } Failure failure() const { return static_cast<Failure>(-this->__word); } Success success() const { return static_cast<Success>(this->__word); } //---------------------------------------------------------------------------------------------- Word __word; }; } <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * 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 "lhttp_stock.hxx" #include "lhttp_address.hxx" #include "stock/Stock.hxx" #include "stock/MapStock.hxx" #include "stock/MultiStock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "pool/tpool.hxx" #include "AllocatorPtr.hxx" #include "lease.hxx" #include "child_stock.hxx" #include "spawn/JailParams.hxx" #include "spawn/Prepared.hxx" #include "event/SocketEvent.hxx" #include "event/TimerEvent.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "io/Logger.hxx" #include "util/RuntimeError.hxx" #include "util/Exception.hxx" #include <assert.h> #include <sys/socket.h> #include <unistd.h> #include <string.h> class LhttpStock final : StockClass, ChildStockClass { ChildStock child_stock; MultiStock mchild_stock; StockMap hstock; public: LhttpStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket, const ChildErrorLogOptions &log_options) noexcept; void FadeAll() noexcept { hstock.FadeAll(); child_stock.GetStockMap().FadeAll(); mchild_stock.FadeAll(); } void FadeTag(const char *tag) noexcept; StockMap &GetConnectionStock() noexcept { return hstock; } private: /* virtual methods from class StockClass */ void Create(CreateStockItem c, StockRequest request, CancellablePointer &cancel_ptr) override; /* virtual methods from class ChildStockClass */ int GetChildSocketType(void *info) const noexcept override; const char *GetChildTag(void *info) const noexcept override; void PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) override; }; class LhttpConnection final : LoggerDomainFactory, StockItem { LazyDomainLogger logger; StockItem *child = nullptr; struct lease_ref lease_ref; UniqueSocketDescriptor fd; SocketEvent event; TimerEvent idle_timeout_event; public: explicit LhttpConnection(CreateStockItem c) noexcept :StockItem(c), logger(*this), event(c.stock.GetEventLoop(), BIND_THIS_METHOD(EventCallback)), idle_timeout_event(c.stock.GetEventLoop(), BIND_THIS_METHOD(OnIdleTimeout)) {} ~LhttpConnection() noexcept override; void Connect(MultiStock &child_stock, const char *key, StockRequest &&request, unsigned concurrency); SocketDescriptor GetSocket() const noexcept { assert(fd.IsDefined()); return fd; } gcc_pure const char *GetTag() const noexcept { assert(child != nullptr); return child_stock_item_get_tag(*child); } void SetSite(const char *site) noexcept { child_stock_item_set_site(*child, site); } void SetUri(const char *uri) noexcept { child_stock_item_set_uri(*child, uri); } private: void EventCallback(unsigned events) noexcept; void OnIdleTimeout() noexcept; /* virtual methods from LoggerDomainFactory */ std::string MakeLoggerDomain() const noexcept override { return GetStockName(); } /* virtual methods from class StockItem */ bool Borrow() noexcept override { event.Cancel(); idle_timeout_event.Cancel(); return true; } bool Release() noexcept override { event.ScheduleRead(); idle_timeout_event.Schedule(std::chrono::minutes(5)); return true; } }; inline void LhttpConnection::Connect(MultiStock &child_stock, const char *key, StockRequest &&request, unsigned concurrency) { try { child = child_stock.GetNow(key, std::move(request), concurrency, lease_ref); } catch (...) { delete this; std::throw_with_nested(FormatRuntimeError("Failed to launch LHTTP server '%s'", key)); } try { fd = child_stock_item_connect(*child); } catch (...) { delete this; std::throw_with_nested(FormatRuntimeError("Failed to connect to LHTTP server '%s'", key)); } event.Open(fd); InvokeCreateSuccess(); } static const char * lhttp_stock_key(struct pool *pool, const LhttpAddress *address) noexcept { return address->GetServerId(AllocatorPtr(*pool)); } /* * libevent callback * */ inline void LhttpConnection::EventCallback(unsigned) noexcept { char buffer; ssize_t nbytes = fd.Read(&buffer, sizeof(buffer)); if (nbytes < 0) logger(2, "error on idle LHTTP connection: ", strerror(errno)); else if (nbytes > 0) logger(2, "unexpected data from idle LHTTP connection"); InvokeIdleDisconnect(); } inline void LhttpConnection::OnIdleTimeout() noexcept { InvokeIdleDisconnect(); } /* * child_stock class * */ int LhttpStock::GetChildSocketType(void *info) const noexcept { const auto &address = *(const LhttpAddress *)info; int type = SOCK_STREAM; if (!address.blocking) type |= SOCK_NONBLOCK; return type; } const char * LhttpStock::GetChildTag(void *info) const noexcept { const auto &address = *(const LhttpAddress *)info; return address.options.tag; } void LhttpStock::PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) { const auto &address = *(const LhttpAddress *)info; p.SetStdin(std::move(fd)); address.CopyTo(p); } /* * stock class * */ void LhttpStock::Create(CreateStockItem c, StockRequest request, gcc_unused CancellablePointer &cancel_ptr) { const auto *address = (const LhttpAddress *)request.get(); assert(address != nullptr); assert(address->path != nullptr); auto *connection = new LhttpConnection(c); connection->Connect(mchild_stock, c.GetStockName(), std::move(request), address->concurrency); } LhttpConnection::~LhttpConnection() noexcept { if (fd.IsDefined()) { event.Cancel(); fd.Close(); } if (child != nullptr) lease_ref.Release(true); } /* * interface * */ inline LhttpStock::LhttpStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket, const ChildErrorLogOptions &log_options) noexcept :child_stock(event_loop, spawn_service, *this, 64, log_socket, log_options, limit, max_idle), mchild_stock(child_stock.GetStockMap()), hstock(event_loop, *this, limit, max_idle) {} void LhttpStock::FadeTag(const char *tag) noexcept { assert(tag != nullptr); hstock.FadeIf([tag](const StockItem &item){ const auto &connection = (const LhttpConnection &)item; const char *tag2 = connection.GetTag(); return tag2 != nullptr && strcmp(tag, tag2) == 0; }); mchild_stock.FadeIf([tag](const StockItem &item){ const char *tag2 = child_stock_item_get_tag(item); return tag2 != nullptr && strcmp(tag, tag2) == 0; }); child_stock.FadeTag(tag); } LhttpStock * lhttp_stock_new(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket, const ChildErrorLogOptions &log_options) noexcept { return new LhttpStock(limit, max_idle, event_loop, spawn_service, log_socket, log_options); } void lhttp_stock_free(LhttpStock *ls) noexcept { delete ls; } void lhttp_stock_fade_all(LhttpStock &ls) noexcept { ls.FadeAll(); } void lhttp_stock_fade_tag(LhttpStock &ls, const char *tag) noexcept { ls.FadeTag(tag); } StockItem * lhttp_stock_get(LhttpStock *lhttp_stock, const LhttpAddress *address) { const auto *const jail = address->options.jail; if (jail != nullptr) jail->Check(); union { const LhttpAddress *in; void *out; } deconst = { .in = address }; const TempPoolLease tpool; return lhttp_stock->GetConnectionStock().GetNow(lhttp_stock_key(tpool, address), ToNopPointer(deconst.out)); } SocketDescriptor lhttp_stock_item_get_socket(const StockItem &item) noexcept { const auto *connection = (const LhttpConnection *)&item; return connection->GetSocket(); } FdType lhttp_stock_item_get_type(gcc_unused const StockItem &item) noexcept { return FdType::FD_SOCKET; } void lhttp_stock_item_set_site(StockItem &item, const char *site) noexcept { auto &connection = (LhttpConnection &)item; connection.SetSite(site); } void lhttp_stock_item_set_uri(StockItem &item, const char *uri) noexcept { auto &connection = (LhttpConnection &)item; connection.SetUri(uri); } <commit_msg>lhttp_stock: use `const_cast`<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * 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 "lhttp_stock.hxx" #include "lhttp_address.hxx" #include "stock/Stock.hxx" #include "stock/MapStock.hxx" #include "stock/MultiStock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "pool/tpool.hxx" #include "AllocatorPtr.hxx" #include "lease.hxx" #include "child_stock.hxx" #include "spawn/JailParams.hxx" #include "spawn/Prepared.hxx" #include "event/SocketEvent.hxx" #include "event/TimerEvent.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "io/Logger.hxx" #include "util/RuntimeError.hxx" #include "util/Exception.hxx" #include <assert.h> #include <sys/socket.h> #include <unistd.h> #include <string.h> class LhttpStock final : StockClass, ChildStockClass { ChildStock child_stock; MultiStock mchild_stock; StockMap hstock; public: LhttpStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket, const ChildErrorLogOptions &log_options) noexcept; void FadeAll() noexcept { hstock.FadeAll(); child_stock.GetStockMap().FadeAll(); mchild_stock.FadeAll(); } void FadeTag(const char *tag) noexcept; StockMap &GetConnectionStock() noexcept { return hstock; } private: /* virtual methods from class StockClass */ void Create(CreateStockItem c, StockRequest request, CancellablePointer &cancel_ptr) override; /* virtual methods from class ChildStockClass */ int GetChildSocketType(void *info) const noexcept override; const char *GetChildTag(void *info) const noexcept override; void PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) override; }; class LhttpConnection final : LoggerDomainFactory, StockItem { LazyDomainLogger logger; StockItem *child = nullptr; struct lease_ref lease_ref; UniqueSocketDescriptor fd; SocketEvent event; TimerEvent idle_timeout_event; public: explicit LhttpConnection(CreateStockItem c) noexcept :StockItem(c), logger(*this), event(c.stock.GetEventLoop(), BIND_THIS_METHOD(EventCallback)), idle_timeout_event(c.stock.GetEventLoop(), BIND_THIS_METHOD(OnIdleTimeout)) {} ~LhttpConnection() noexcept override; void Connect(MultiStock &child_stock, const char *key, StockRequest &&request, unsigned concurrency); SocketDescriptor GetSocket() const noexcept { assert(fd.IsDefined()); return fd; } gcc_pure const char *GetTag() const noexcept { assert(child != nullptr); return child_stock_item_get_tag(*child); } void SetSite(const char *site) noexcept { child_stock_item_set_site(*child, site); } void SetUri(const char *uri) noexcept { child_stock_item_set_uri(*child, uri); } private: void EventCallback(unsigned events) noexcept; void OnIdleTimeout() noexcept; /* virtual methods from LoggerDomainFactory */ std::string MakeLoggerDomain() const noexcept override { return GetStockName(); } /* virtual methods from class StockItem */ bool Borrow() noexcept override { event.Cancel(); idle_timeout_event.Cancel(); return true; } bool Release() noexcept override { event.ScheduleRead(); idle_timeout_event.Schedule(std::chrono::minutes(5)); return true; } }; inline void LhttpConnection::Connect(MultiStock &child_stock, const char *key, StockRequest &&request, unsigned concurrency) { try { child = child_stock.GetNow(key, std::move(request), concurrency, lease_ref); } catch (...) { delete this; std::throw_with_nested(FormatRuntimeError("Failed to launch LHTTP server '%s'", key)); } try { fd = child_stock_item_connect(*child); } catch (...) { delete this; std::throw_with_nested(FormatRuntimeError("Failed to connect to LHTTP server '%s'", key)); } event.Open(fd); InvokeCreateSuccess(); } static const char * lhttp_stock_key(struct pool *pool, const LhttpAddress *address) noexcept { return address->GetServerId(AllocatorPtr(*pool)); } /* * libevent callback * */ inline void LhttpConnection::EventCallback(unsigned) noexcept { char buffer; ssize_t nbytes = fd.Read(&buffer, sizeof(buffer)); if (nbytes < 0) logger(2, "error on idle LHTTP connection: ", strerror(errno)); else if (nbytes > 0) logger(2, "unexpected data from idle LHTTP connection"); InvokeIdleDisconnect(); } inline void LhttpConnection::OnIdleTimeout() noexcept { InvokeIdleDisconnect(); } /* * child_stock class * */ int LhttpStock::GetChildSocketType(void *info) const noexcept { const auto &address = *(const LhttpAddress *)info; int type = SOCK_STREAM; if (!address.blocking) type |= SOCK_NONBLOCK; return type; } const char * LhttpStock::GetChildTag(void *info) const noexcept { const auto &address = *(const LhttpAddress *)info; return address.options.tag; } void LhttpStock::PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) { const auto &address = *(const LhttpAddress *)info; p.SetStdin(std::move(fd)); address.CopyTo(p); } /* * stock class * */ void LhttpStock::Create(CreateStockItem c, StockRequest request, gcc_unused CancellablePointer &cancel_ptr) { const auto *address = (const LhttpAddress *)request.get(); assert(address != nullptr); assert(address->path != nullptr); auto *connection = new LhttpConnection(c); connection->Connect(mchild_stock, c.GetStockName(), std::move(request), address->concurrency); } LhttpConnection::~LhttpConnection() noexcept { if (fd.IsDefined()) { event.Cancel(); fd.Close(); } if (child != nullptr) lease_ref.Release(true); } /* * interface * */ inline LhttpStock::LhttpStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket, const ChildErrorLogOptions &log_options) noexcept :child_stock(event_loop, spawn_service, *this, 64, log_socket, log_options, limit, max_idle), mchild_stock(child_stock.GetStockMap()), hstock(event_loop, *this, limit, max_idle) {} void LhttpStock::FadeTag(const char *tag) noexcept { assert(tag != nullptr); hstock.FadeIf([tag](const StockItem &item){ const auto &connection = (const LhttpConnection &)item; const char *tag2 = connection.GetTag(); return tag2 != nullptr && strcmp(tag, tag2) == 0; }); mchild_stock.FadeIf([tag](const StockItem &item){ const char *tag2 = child_stock_item_get_tag(item); return tag2 != nullptr && strcmp(tag, tag2) == 0; }); child_stock.FadeTag(tag); } LhttpStock * lhttp_stock_new(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket, const ChildErrorLogOptions &log_options) noexcept { return new LhttpStock(limit, max_idle, event_loop, spawn_service, log_socket, log_options); } void lhttp_stock_free(LhttpStock *ls) noexcept { delete ls; } void lhttp_stock_fade_all(LhttpStock &ls) noexcept { ls.FadeAll(); } void lhttp_stock_fade_tag(LhttpStock &ls, const char *tag) noexcept { ls.FadeTag(tag); } StockItem * lhttp_stock_get(LhttpStock *lhttp_stock, const LhttpAddress *address) { const auto *const jail = address->options.jail; if (jail != nullptr) jail->Check(); const TempPoolLease tpool; return lhttp_stock->GetConnectionStock().GetNow(lhttp_stock_key(tpool, address), ToNopPointer(const_cast<LhttpAddress *>(address))); } SocketDescriptor lhttp_stock_item_get_socket(const StockItem &item) noexcept { const auto *connection = (const LhttpConnection *)&item; return connection->GetSocket(); } FdType lhttp_stock_item_get_type(gcc_unused const StockItem &item) noexcept { return FdType::FD_SOCKET; } void lhttp_stock_item_set_site(StockItem &item, const char *site) noexcept { auto &connection = (LhttpConnection &)item; connection.SetSite(site); } void lhttp_stock_item_set_uri(StockItem &item, const char *uri) noexcept { auto &connection = (LhttpConnection &)item; connection.SetUri(uri); } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/cl/cl_device.h" #include <algorithm> #include <string> #include <vector> #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "tensorflow/lite/delegates/gpu/cl/util.h" #include "tensorflow/lite/delegates/gpu/common/status.h" namespace tflite { namespace gpu { namespace cl { template <> std::string GetDeviceInfo<std::string>(cl_device_id id, cl_device_info info) { size_t size; cl_int error = clGetDeviceInfo(id, info, 0, nullptr, &size); if (error != CL_SUCCESS) { return ""; } std::string result(size - 1, 0); error = clGetDeviceInfo(id, info, size, &result[0], nullptr); if (error != CL_SUCCESS) { return ""; } return result; } namespace { template <typename T> T GetPlatformInfo(cl_platform_id id, cl_platform_info info) { T result; cl_int error = clGetPlatformInfo(id, info, sizeof(T), &result, nullptr); if (error != CL_SUCCESS) { return -1; } return result; } std::string GetPlatformInfo(cl_platform_id id, cl_platform_info info) { size_t size; cl_int error = clGetPlatformInfo(id, info, 0, nullptr, &size); if (error != CL_SUCCESS) { return ""; } std::string result(size - 1, 0); error = clGetPlatformInfo(id, info, size, &result[0], nullptr); if (error != CL_SUCCESS) { return ""; } return result; } void GetDeviceWorkDimsSizes(cl_device_id id, int3* result) { int dims_count = GetDeviceInfo<cl_uint>(id, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS); if (dims_count < 3) { return; } std::vector<size_t> limits(dims_count); cl_int error = clGetDeviceInfo(id, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t) * dims_count, limits.data(), nullptr); if (error != CL_SUCCESS) { return; } // dims_count must be at least 3 according to spec result->x = limits[0]; result->y = limits[1]; result->z = limits[2]; } OpenClVersion ParseCLVersion(const std::string& version) { const auto first_dot_pos = version.find_first_of('.'); if (first_dot_pos == std::string::npos) { return OpenClVersion::kCl1_0; } const int major = version[first_dot_pos - 1] - '0'; const int minor = version[first_dot_pos + 1] - '0'; if (major == 1) { if (minor == 2) { return OpenClVersion::kCl1_2; } else if (minor == 1) { return OpenClVersion::kCl1_1; } else { return OpenClVersion::kCl1_0; } } else if (major == 2) { if (minor == 2) { return OpenClVersion::kCl2_2; } else if (minor == 1) { return OpenClVersion::kCl2_1; } else { return OpenClVersion::kCl2_0; } } else if (major == 3) { return OpenClVersion::kCl3_0; } else { return OpenClVersion::kCl1_0; } } GpuVendor ParseVendor(const std::string& device_name, const std::string& vendor_name) { std::string d_name = device_name; std::string v_name = vendor_name; std::transform(d_name.begin(), d_name.end(), d_name.begin(), ::tolower); std::transform(v_name.begin(), v_name.end(), v_name.begin(), ::tolower); if (d_name.find("qualcomm") != std::string::npos || v_name.find("qualcomm") != std::string::npos) { return GpuVendor::kQualcomm; } else if (d_name.find("mali") != std::string::npos || v_name.find("mali") != std::string::npos) { return GpuVendor::kMali; } else if (d_name.find("power") != std::string::npos || v_name.find("power") != std::string::npos) { return GpuVendor::kPowerVR; } else if (d_name.find("nvidia") != std::string::npos || v_name.find("nvidia") != std::string::npos) { return GpuVendor::kNvidia; } else if (d_name.find("advanced micro devices") != std::string::npos || v_name.find("advanced micro devices") != std::string::npos) { return GpuVendor::kAMD; } else if (d_name.find("intel") != std::string::npos || v_name.find("intel") != std::string::npos) { return GpuVendor::kIntel; } else { return GpuVendor::kUnknown; } } // check that gpu_version belong to range min_version-max_version // min_version is included and max_version is excluded. bool IsGPUVersionInRange(int gpu_version, int min_version, int max_version) { return gpu_version >= min_version && gpu_version < max_version; } } // namespace GpuInfo GpuInfoFromDeviceID(cl_device_id id) { GpuInfo info; const auto device_name = GetDeviceInfo<std::string>(id, CL_DEVICE_NAME); const auto vendor_name = GetDeviceInfo<std::string>(id, CL_DEVICE_VENDOR); const auto opencl_c_version = GetDeviceInfo<std::string>(id, CL_DEVICE_OPENCL_C_VERSION); info.gpu_api = GpuApi::kOpenCl; info.vendor = ParseVendor(device_name, vendor_name); if (info.IsAdreno()) { info.adreno_info = AdrenoInfo(opencl_c_version); } else if (info.IsMali()) { info.mali_info = MaliInfo(device_name); } info.opencl_info.cl_version = ParseCLVersion(opencl_c_version); info.opencl_info.extensions = absl::StrSplit(GetDeviceInfo<std::string>(id, CL_DEVICE_EXTENSIONS), ' '); info.opencl_info.supports_fp16 = false; info.opencl_info.supports_image3d_writes = false; for (const auto& ext : info.opencl_info.extensions) { if (ext == "cl_khr_fp16") { info.opencl_info.supports_fp16 = true; } if (ext == "cl_khr_3d_image_writes") { info.opencl_info.supports_image3d_writes = true; } } cl_device_fp_config f32_config = GetDeviceInfo<cl_device_fp_config>(id, CL_DEVICE_SINGLE_FP_CONFIG); info.opencl_info.supports_fp32_rtn = f32_config & CL_FP_ROUND_TO_NEAREST; if (info.opencl_info.supports_fp16) { cl_device_fp_config f16_config; auto status = GetDeviceInfo<cl_device_fp_config>( id, CL_DEVICE_HALF_FP_CONFIG, &f16_config); // AMD supports cl_khr_fp16 but CL_DEVICE_HALF_FP_CONFIG is empty. if (status.ok() && !info.IsAMD()) { info.opencl_info.supports_fp16_rtn = f16_config & CL_FP_ROUND_TO_NEAREST; } else { // happens on PowerVR f16_config = f32_config; info.opencl_info.supports_fp16_rtn = info.opencl_info.supports_fp32_rtn; } } else { info.opencl_info.supports_fp16_rtn = false; } if (info.IsPowerVR() && !info.opencl_info.supports_fp16) { // PowerVR doesn't have full support of fp16 and so doesn't list this // extension. But it can support fp16 in MADs and as buffers/textures types, // so we will use it. info.opencl_info.supports_fp16 = true; info.opencl_info.supports_fp16_rtn = info.opencl_info.supports_fp32_rtn; } if (!info.opencl_info.supports_image3d_writes && ((info.IsAdreno() && info.adreno_info.IsAdreno4xx()) || info.IsNvidia())) { // in local tests Adreno 430 can write in image 3d, at least on small sizes, // but it doesn't have cl_khr_3d_image_writes in list of available // extensions // The same for NVidia info.opencl_info.supports_image3d_writes = true; } info.opencl_info.compute_units_count = GetDeviceInfo<cl_uint>(id, CL_DEVICE_MAX_COMPUTE_UNITS); info.opencl_info.image2d_max_width = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE2D_MAX_WIDTH); info.opencl_info.image2d_max_height = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE2D_MAX_HEIGHT); info.opencl_info.buffer_max_size = GetDeviceInfo<cl_ulong>(id, CL_DEVICE_MAX_MEM_ALLOC_SIZE); if (info.opencl_info.cl_version >= OpenClVersion::kCl1_2) { info.opencl_info.image_buffer_max_size = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE_MAX_BUFFER_SIZE); info.opencl_info.image_array_max_layers = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE_MAX_ARRAY_SIZE); } info.opencl_info.image3d_max_width = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE3D_MAX_WIDTH); info.opencl_info.image3d_max_height = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE2D_MAX_HEIGHT); info.opencl_info.image3d_max_depth = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE3D_MAX_DEPTH); int3 max_work_group_sizes; GetDeviceWorkDimsSizes(id, &max_work_group_sizes); info.opencl_info.max_work_group_size_x = max_work_group_sizes.x; info.opencl_info.max_work_group_size_y = max_work_group_sizes.y; info.opencl_info.max_work_group_size_z = max_work_group_sizes.z; info.opencl_info.max_work_group_total_size = GetDeviceInfo<size_t>(id, CL_DEVICE_MAX_WORK_GROUP_SIZE); if (info.IsIntel()) { if (info.SupportsExtension("cl_intel_required_subgroup_size")) { size_t sub_groups_count; cl_int status = clGetDeviceInfo(id, 0x4108 /*CL_DEVICE_SUB_GROUP_SIZES_INTEL*/, 0, nullptr, &sub_groups_count); if (status == CL_SUCCESS) { std::vector<size_t> sub_group_sizes(sub_groups_count); status = clGetDeviceInfo(id, 0x4108 /*CL_DEVICE_SUB_GROUP_SIZES_INTEL*/, sizeof(size_t) * sub_groups_count, sub_group_sizes.data(), nullptr); if (status == CL_SUCCESS) { for (int i = 0; i < sub_groups_count; ++i) { info.supported_subgroup_sizes.push_back(sub_group_sizes[i]); } } } } } return info; } CLDevice::CLDevice(cl_device_id id, cl_platform_id platform_id) : info_(GpuInfoFromDeviceID(id)), id_(id), platform_id_(platform_id) {} CLDevice::CLDevice(const CLDevice& device) : info_(device.info_), id_(device.id_), platform_id_(device.platform_id_) {} CLDevice& CLDevice::operator=(const CLDevice& device) { if (this != &device) { info_ = device.info_; id_ = device.id_; platform_id_ = device.platform_id_; } return *this; } CLDevice::CLDevice(CLDevice&& device) : info_(std::move(device.info_)), id_(device.id_), platform_id_(device.platform_id_) { device.id_ = nullptr; device.platform_id_ = nullptr; } CLDevice& CLDevice::operator=(CLDevice&& device) { if (this != &device) { id_ = nullptr; platform_id_ = nullptr; info_ = std::move(device.info_); std::swap(id_, device.id_); std::swap(platform_id_, device.platform_id_); } return *this; } std::string CLDevice::GetPlatformVersion() const { return GetPlatformInfo(platform_id_, CL_PLATFORM_VERSION); } void CLDevice::DisableOneLayerTextureArray() { info_.adreno_info.support_one_layer_texture_array = false; } absl::Status CreateDefaultGPUDevice(CLDevice* result) { cl_uint num_platforms; clGetPlatformIDs(0, nullptr, &num_platforms); if (num_platforms == 0) { return absl::UnknownError("No supported OpenCL platform."); } std::vector<cl_platform_id> platforms(num_platforms); clGetPlatformIDs(num_platforms, platforms.data(), nullptr); cl_platform_id platform_id = platforms[0]; cl_uint num_devices; clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, nullptr, &num_devices); if (num_devices == 0) { return absl::UnknownError("No GPU on current platform."); } std::vector<cl_device_id> devices(num_devices); clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, num_devices, devices.data(), nullptr); *result = CLDevice(devices[0], platform_id); return absl::OkStatus(); } } // namespace cl } // namespace gpu } // namespace tflite <commit_msg>Using common function for initialization of gpu_info in OpenCL backend.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/cl/cl_device.h" #include <algorithm> #include <string> #include <vector> #include "absl/strings/numbers.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "tensorflow/lite/delegates/gpu/cl/util.h" #include "tensorflow/lite/delegates/gpu/common/status.h" namespace tflite { namespace gpu { namespace cl { template <> std::string GetDeviceInfo<std::string>(cl_device_id id, cl_device_info info) { size_t size; cl_int error = clGetDeviceInfo(id, info, 0, nullptr, &size); if (error != CL_SUCCESS) { return ""; } std::string result(size - 1, 0); error = clGetDeviceInfo(id, info, size, &result[0], nullptr); if (error != CL_SUCCESS) { return ""; } return result; } namespace { template <typename T> T GetPlatformInfo(cl_platform_id id, cl_platform_info info) { T result; cl_int error = clGetPlatformInfo(id, info, sizeof(T), &result, nullptr); if (error != CL_SUCCESS) { return -1; } return result; } std::string GetPlatformInfo(cl_platform_id id, cl_platform_info info) { size_t size; cl_int error = clGetPlatformInfo(id, info, 0, nullptr, &size); if (error != CL_SUCCESS) { return ""; } std::string result(size - 1, 0); error = clGetPlatformInfo(id, info, size, &result[0], nullptr); if (error != CL_SUCCESS) { return ""; } return result; } void GetDeviceWorkDimsSizes(cl_device_id id, int3* result) { int dims_count = GetDeviceInfo<cl_uint>(id, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS); if (dims_count < 3) { return; } std::vector<size_t> limits(dims_count); cl_int error = clGetDeviceInfo(id, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(size_t) * dims_count, limits.data(), nullptr); if (error != CL_SUCCESS) { return; } // dims_count must be at least 3 according to spec result->x = limits[0]; result->y = limits[1]; result->z = limits[2]; } OpenClVersion ParseCLVersion(const std::string& version) { const auto first_dot_pos = version.find_first_of('.'); if (first_dot_pos == std::string::npos) { return OpenClVersion::kCl1_0; } const int major = version[first_dot_pos - 1] - '0'; const int minor = version[first_dot_pos + 1] - '0'; if (major == 1) { if (minor == 2) { return OpenClVersion::kCl1_2; } else if (minor == 1) { return OpenClVersion::kCl1_1; } else { return OpenClVersion::kCl1_0; } } else if (major == 2) { if (minor == 2) { return OpenClVersion::kCl2_2; } else if (minor == 1) { return OpenClVersion::kCl2_1; } else { return OpenClVersion::kCl2_0; } } else if (major == 3) { return OpenClVersion::kCl3_0; } else { return OpenClVersion::kCl1_0; } } // check that gpu_version belong to range min_version-max_version // min_version is included and max_version is excluded. bool IsGPUVersionInRange(int gpu_version, int min_version, int max_version) { return gpu_version >= min_version && gpu_version < max_version; } } // namespace GpuInfo GpuInfoFromDeviceID(cl_device_id id) { GpuInfo info; const auto device_name = GetDeviceInfo<std::string>(id, CL_DEVICE_NAME); const auto vendor_name = GetDeviceInfo<std::string>(id, CL_DEVICE_VENDOR); const auto opencl_c_version = GetDeviceInfo<std::string>(id, CL_DEVICE_OPENCL_C_VERSION); const std::string gpu_description = absl::StrCat(device_name, " ", vendor_name, " ", opencl_c_version); GetGpuInfoFromDeviceDescription(gpu_description, GpuApi::kOpenCl, &info); info.opencl_info.cl_version = ParseCLVersion(opencl_c_version); info.opencl_info.extensions = absl::StrSplit(GetDeviceInfo<std::string>(id, CL_DEVICE_EXTENSIONS), ' '); info.opencl_info.supports_fp16 = false; info.opencl_info.supports_image3d_writes = false; for (const auto& ext : info.opencl_info.extensions) { if (ext == "cl_khr_fp16") { info.opencl_info.supports_fp16 = true; } if (ext == "cl_khr_3d_image_writes") { info.opencl_info.supports_image3d_writes = true; } } cl_device_fp_config f32_config = GetDeviceInfo<cl_device_fp_config>(id, CL_DEVICE_SINGLE_FP_CONFIG); info.opencl_info.supports_fp32_rtn = f32_config & CL_FP_ROUND_TO_NEAREST; if (info.opencl_info.supports_fp16) { cl_device_fp_config f16_config; auto status = GetDeviceInfo<cl_device_fp_config>( id, CL_DEVICE_HALF_FP_CONFIG, &f16_config); // AMD supports cl_khr_fp16 but CL_DEVICE_HALF_FP_CONFIG is empty. if (status.ok() && !info.IsAMD()) { info.opencl_info.supports_fp16_rtn = f16_config & CL_FP_ROUND_TO_NEAREST; } else { // happens on PowerVR f16_config = f32_config; info.opencl_info.supports_fp16_rtn = info.opencl_info.supports_fp32_rtn; } } else { info.opencl_info.supports_fp16_rtn = false; } if (info.IsPowerVR() && !info.opencl_info.supports_fp16) { // PowerVR doesn't have full support of fp16 and so doesn't list this // extension. But it can support fp16 in MADs and as buffers/textures types, // so we will use it. info.opencl_info.supports_fp16 = true; info.opencl_info.supports_fp16_rtn = info.opencl_info.supports_fp32_rtn; } if (!info.opencl_info.supports_image3d_writes && ((info.IsAdreno() && info.adreno_info.IsAdreno4xx()) || info.IsNvidia())) { // in local tests Adreno 430 can write in image 3d, at least on small sizes, // but it doesn't have cl_khr_3d_image_writes in list of available // extensions // The same for NVidia info.opencl_info.supports_image3d_writes = true; } info.opencl_info.compute_units_count = GetDeviceInfo<cl_uint>(id, CL_DEVICE_MAX_COMPUTE_UNITS); info.opencl_info.image2d_max_width = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE2D_MAX_WIDTH); info.opencl_info.image2d_max_height = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE2D_MAX_HEIGHT); info.opencl_info.buffer_max_size = GetDeviceInfo<cl_ulong>(id, CL_DEVICE_MAX_MEM_ALLOC_SIZE); if (info.opencl_info.cl_version >= OpenClVersion::kCl1_2) { info.opencl_info.image_buffer_max_size = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE_MAX_BUFFER_SIZE); info.opencl_info.image_array_max_layers = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE_MAX_ARRAY_SIZE); } info.opencl_info.image3d_max_width = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE3D_MAX_WIDTH); info.opencl_info.image3d_max_height = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE2D_MAX_HEIGHT); info.opencl_info.image3d_max_depth = GetDeviceInfo<size_t>(id, CL_DEVICE_IMAGE3D_MAX_DEPTH); int3 max_work_group_sizes; GetDeviceWorkDimsSizes(id, &max_work_group_sizes); info.opencl_info.max_work_group_size_x = max_work_group_sizes.x; info.opencl_info.max_work_group_size_y = max_work_group_sizes.y; info.opencl_info.max_work_group_size_z = max_work_group_sizes.z; info.opencl_info.max_work_group_total_size = GetDeviceInfo<size_t>(id, CL_DEVICE_MAX_WORK_GROUP_SIZE); if (info.IsIntel()) { if (info.SupportsExtension("cl_intel_required_subgroup_size")) { size_t sub_groups_count; cl_int status = clGetDeviceInfo(id, 0x4108 /*CL_DEVICE_SUB_GROUP_SIZES_INTEL*/, 0, nullptr, &sub_groups_count); if (status == CL_SUCCESS) { std::vector<size_t> sub_group_sizes(sub_groups_count); status = clGetDeviceInfo(id, 0x4108 /*CL_DEVICE_SUB_GROUP_SIZES_INTEL*/, sizeof(size_t) * sub_groups_count, sub_group_sizes.data(), nullptr); if (status == CL_SUCCESS) { for (int i = 0; i < sub_groups_count; ++i) { info.supported_subgroup_sizes.push_back(sub_group_sizes[i]); } } } } } return info; } CLDevice::CLDevice(cl_device_id id, cl_platform_id platform_id) : info_(GpuInfoFromDeviceID(id)), id_(id), platform_id_(platform_id) {} CLDevice::CLDevice(const CLDevice& device) : info_(device.info_), id_(device.id_), platform_id_(device.platform_id_) {} CLDevice& CLDevice::operator=(const CLDevice& device) { if (this != &device) { info_ = device.info_; id_ = device.id_; platform_id_ = device.platform_id_; } return *this; } CLDevice::CLDevice(CLDevice&& device) : info_(std::move(device.info_)), id_(device.id_), platform_id_(device.platform_id_) { device.id_ = nullptr; device.platform_id_ = nullptr; } CLDevice& CLDevice::operator=(CLDevice&& device) { if (this != &device) { id_ = nullptr; platform_id_ = nullptr; info_ = std::move(device.info_); std::swap(id_, device.id_); std::swap(platform_id_, device.platform_id_); } return *this; } std::string CLDevice::GetPlatformVersion() const { return GetPlatformInfo(platform_id_, CL_PLATFORM_VERSION); } void CLDevice::DisableOneLayerTextureArray() { info_.adreno_info.support_one_layer_texture_array = false; } absl::Status CreateDefaultGPUDevice(CLDevice* result) { cl_uint num_platforms; clGetPlatformIDs(0, nullptr, &num_platforms); if (num_platforms == 0) { return absl::UnknownError("No supported OpenCL platform."); } std::vector<cl_platform_id> platforms(num_platforms); clGetPlatformIDs(num_platforms, platforms.data(), nullptr); cl_platform_id platform_id = platforms[0]; cl_uint num_devices; clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, nullptr, &num_devices); if (num_devices == 0) { return absl::UnknownError("No GPU on current platform."); } std::vector<cl_device_id> devices(num_devices); clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, num_devices, devices.data(), nullptr); *result = CLDevice(devices[0], platform_id); return absl::OkStatus(); } } // namespace cl } // namespace gpu } // namespace tflite <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xaa; pchMessageStart[1] = 0xa3; pchMessageStart[2] = 0xb2; pchMessageStart[3] = 0xc4; vAlertPubKey = ParseHex(""); nDefaultPort = 57155; nRPCPort = 57154; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 const char* pszTimestamp = "New genesis for Coinswap of RENOS June/17"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1497040584, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1497040584; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 213861; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000e590857f6bf83e3ae07b56528e47565115465f9d4e8ead2c5bffb1a9edc")); assert(genesis.hashMerkleRoot == uint256("0xb43b9c01703081ea07d54e271471e7100364535cf55e38763761e384d27970af")); vSeeds.push_back(CDNSSeedData("seed1", "137.74.193.204")); vSeeds.push_back(CDNSSeedData("seed2", "137.74.193.204")); vSeeds.push_back(CDNSSeedData("seed3", "198.50.180.192")); vSeeds.push_back(CDNSSeedData("seed4", "137.74.193.204")); vSeeds.push_back(CDNSSeedData("seed5", "137.74.193.204")); vSeeds.push_back(CDNSSeedData("seed6", "45.32.196.193")); vSeeds.push_back(CDNSSeedData("seed7", "45.32.164.109")); vSeeds.push_back(CDNSSeedData("seed8", "45.77.5.93")); vSeeds.push_back(CDNSSeedData("seed9", "149.56.128.2")); vSeeds.push_back(CDNSSeedData("seed10", "2a01:7e01::f03c:91ff:fe7b:8e41")); vSeeds.push_back(CDNSSeedData("seed11", "45.77.58.26")); vSeeds.push_back(CDNSSeedData("seed12", "45.77.37.208")); vSeeds.push_back(CDNSSeedData("seed13", "174.67.252.25")); vSeeds.push_back(CDNSSeedData("seed14", "79.137.34.194")); vSeeds.push_back(CDNSSeedData("seed15", "144.217.166.140")); vSeeds.push_back(CDNSSeedData("seed16", "2001:bc8:4700:2000::3e39")); vSeeds.push_back(CDNSSeedData("seed17", "104.238.184.213")); vSeeds.push_back(CDNSSeedData("seed18", "93.186.193.158")); vSeeds.push_back(CDNSSeedData("seed19", "51.15.52.23")); vSeeds.push_back(CDNSSeedData("seed20", "198.50.171.20")); vSeeds.push_back(CDNSSeedData("seed21", "147.135.233.42")); vSeeds.push_back(CDNSSeedData("seed22", "45.79.216.189")); vSeeds.push_back(CDNSSeedData("seed23", "2600:3c02::f03c:91ff:fe3e:dbbb")); vSeeds.push_back(CDNSSeedData("seed24", "45.63.68.182")); vSeeds.push_back(CDNSSeedData("seed25", "90.215.122.71")); vSeeds.push_back(CDNSSeedData("seed26", "82.43.204.158")); vSeeds.push_back(CDNSSeedData("seed27", "5.189.142.181")); vSeeds.push_back(CDNSSeedData("seed28", "2001:4ca0:0:fe00:0:5efe:a96:caa4")); vSeeds.push_back(CDNSSeedData("seed29", "193.90.142.13")); vSeeds.push_back(CDNSSeedData("seed30", "35.165.42.90")); vSeeds.push_back(CDNSSeedData("seed31", "2.62.187.203")); vSeeds.push_back(CDNSSeedData("seed32", "192.210.128.100")); vSeeds.push_back(CDNSSeedData("seed33", "2a02:f680:1:1100::60d2")); vSeeds.push_back(CDNSSeedData("seed34", "80.89.233.124")); vSeeds.push_back(CDNSSeedData("seed35", "203.59.230.190")); vSeeds.push_back(CDNSSeedData("seed36", "222.5.183.201")); vSeeds.push_back(CDNSSeedData("seed37", "104.237.153.253")); vSeeds.push_back(CDNSSeedData("seed38", "147.135.233.45")); vSeeds.push_back(CDNSSeedData("seed39", "2a01:7e01::f03c:91ff:fe92:d170")); vSeeds.push_back(CDNSSeedData("seed40", "172.104.86.169")); vSeeds.push_back(CDNSSeedData("seed41", "45.63.89.184")); vSeeds.push_back(CDNSSeedData("seed42", "2600:3c01::f03c:91ff:fed4:f07")); vSeeds.push_back(CDNSSeedData("seed43", "108.61.197.30")); vSeeds.push_back(CDNSSeedData("seed44", "45.77.80.196")); vSeeds.push_back(CDNSSeedData("seed45", "147.135.233.33")); vSeeds.push_back(CDNSSeedData("seed46", "2400:8902::f03c:91ff:fe3e:dbbf")); vSeeds.push_back(CDNSSeedData("seed47", "147.135.233.35")); vSeeds.push_back(CDNSSeedData("seed48", "2607:fea8:131f:f75a::7")); vSeeds.push_back(CDNSSeedData("seed49", "2001:0:9d38:6ab8:20a5:1a6c:fdc1:4434")); vSeeds.push_back(CDNSSeedData("seed50", "45.32.130.36")); vSeeds.push_back(CDNSSeedData("seed51", "45.77.82.231")); vSeeds.push_back(CDNSSeedData("seed52", "2001:0:9d38:6abd:34db:f25:899b:5608")); vSeeds.push_back(CDNSSeedData("seed53", "2001:0:9d38:90d7:3ce3:11d9:b08f:2a28")); vSeeds.push_back(CDNSSeedData("seed54", "2001:0:9d38:953c:10df:211c:41b4:9198")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,60); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,28); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,150); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 6000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xa1; pchMessageStart[1] = 0x79; pchMessageStart[2] = 0xa4; pchMessageStart[3] = 0xa2; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex(""); nDefaultPort = 57255; nRPCPort = 57254; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = 1497040584; genesis.nNonce = 213861; assert(hashGenesisBlock == uint256("0x00000e590857f6bf83e3ae07b56528e47565115465f9d4e8ead2c5bffb1a9edc")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,229); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>Revert "Updated dns seed list. Will now sync on first runs"<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xaa; pchMessageStart[1] = 0xa3; pchMessageStart[2] = 0xb2; pchMessageStart[3] = 0xc4; vAlertPubKey = ParseHex(""); nDefaultPort = 57155; nRPCPort = 57154; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 const char* pszTimestamp = "New genesis for Coinswap of RENOS June/17"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1497040584, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1497040584; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 213861; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000e590857f6bf83e3ae07b56528e47565115465f9d4e8ead2c5bffb1a9edc")); assert(genesis.hashMerkleRoot == uint256("0xb43b9c01703081ea07d54e271471e7100364535cf55e38763761e384d27970af")); vSeeds.push_back(CDNSSeedData("seed1", "45.32.164.109")); vSeeds.push_back(CDNSSeedData("seed2", "45.32.163.3")); vSeeds.push_back(CDNSSeedData("seed3", "45.32.173.218")); vSeeds.push_back(CDNSSeedData("seed4", "45.32.196.193")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,60); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,28); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,150); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 6000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xa1; pchMessageStart[1] = 0x79; pchMessageStart[2] = 0xa4; pchMessageStart[3] = 0xa2; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex(""); nDefaultPort = 57255; nRPCPort = 57254; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = 1497040584; genesis.nNonce = 213861; assert(hashGenesisBlock == uint256("0x00000e590857f6bf83e3ae07b56528e47565115465f9d4e8ead2c5bffb1a9edc")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,229); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Copyright (c) 2017 Empinel/The Ion Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include "amount.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } void MineGenesis(CBlock genesis, uint256 nProofOfWorkLimit){ // This will figure out a valid hash and Nonce if you're creating a differe$ uint256 hashTarget = nProofOfWorkLimit; printf("Target: %s\n", hashTarget.GetHex().c_str()); uint256 newhash = genesis.GetHash(); uint256 besthash; memset(&besthash,0xFF,32); while (newhash > hashTarget) { ++genesis.nNonce; if (genesis.nNonce == 0){ printf("NONCE WRAPPED, incrementing time"); ++genesis.nTime; } newhash = genesis.GetHash(); if(newhash < besthash){ besthash=newhash; printf("New best: %s\n", newhash.GetHex().c_str()); } } printf("Gensis Hash: %s\n", genesis.GetHash().ToString().c_str()); printf("Gensis Hash Merkle: %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("Gensis nTime: %u\n", genesis.nTime); printf("Gensis nBits: %08x\n", genesis.nBits); printf("Gensis Nonce: %u\n\n\n", genesis.nNonce); } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x7e; pchMessageStart[1] = 0x3f; pchMessageStart[2] = 0x95; pchMessageStart[3] = 0xbb; vAlertPubKey = ParseHex("040627d06214ba58f42eb74d475d32bc359c822902fb91766be30bfff2b878d2b5d4efa9e38c2a3438b15ff85e734ce3ce0382f8ebb79b6cdb3bc779af69e0b9b8"); nDefaultPort = 15200; nRPCPort = 15201; nProofOfWorkLimit = ~uint256(0) >> 24; // 000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff nProofOfStakeLimit = ~uint256(0) >> 20; const char* pszTimestamp = "Reuters: Merkel expected to speak with Trump about Russia"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].scriptPubKey = CScript() << ParseHex("04964ae39ac7421145f93a031791749772f671fa1153e4d6df87b1dce87ed2d68a74b46df6cd023ceffbbae4feed084915372d2b8ca866d24dd979af6f09800b3d") << OP_CHECKSIG; vout[0].nValue = (1 * COIN); CTransaction txNew(1, 1485517600, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1485517600; genesis.nBits = 0x1e00ffff; genesis.nNonce = 56961757; hashGenesisBlock = genesis.GetHash(); if (false) { MineGenesis(genesis, nProofOfWorkLimit); } /** Gensis Hash: 000000c4f068822742fe2576d9da3ebc057e227be478d4dd419ac58ca23ab5a7 Gensis Hash Merkle: 7ca71c0b618948ceba95805287d1e48e3f3f6cc4fb3b761d05c405b7e8640370 Gensis nTime: 1485517600 Gensis nBits: 1e00ffff Gensis Nonce: 56961757 */ assert(hashGenesisBlock == uint256("0x000000c4f068822742fe2576d9da3ebc057e227be478d4dd419ac58ca23ab5a7")); assert(genesis.hashMerkleRoot == uint256("0x7ca71c0b618948ceba95805287d1e48e3f3f6cc4fb3b761d05c405b7e8640370")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("seeder.baseserv.com", "main.seeder.baseserv.com")); vSeeds.push_back(CDNSSeedData("seeder.uksafedns.net", "main.seeder.uksafedns.net")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; strDarksendPoolDummyAddress = "iUUCtBZUVR98Cufh9BbSSqUPJFEtPKSLSe"; nLastPOWBlock = 500; // Preliminary Proof of Work } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4d; pchMessageStart[3] = 0x3e; nProofOfWorkLimit = ~uint256(0) >> 16; nProofOfStakeLimit = ~uint256(0) >> 16; vAlertPubKey = ParseHex("04cc24ab003c828cdd9cf4db2ebbde8e1cecb3bbfa8b3127fcb9dd9b84d44112080827ed7c49a648af9fe788ff42e316aee665879c553f099e55299d6b54edd7e0"); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; genesis.nVersion = 1; genesis.nTime = 1484332000; genesis.nBits = 0x1f00ffff; genesis.nNonce = 1172; if (false) { MineGenesis(genesis, nProofOfWorkLimit); } // Modify the testnet genesis block so the timestamp is valid for a later start. // assert(hashGenesisBlock == uint256("0x00008ca69320cdd1932a5d19f6602b383d6683e4185b552acb05a32dd94995f2")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,97); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>[Genesis] A New One<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin developers // Copyright (c) 2017 Empinel/The Ion Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include "amount.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } void MineGenesis(CBlock genesis, uint256 nProofOfWorkLimit){ // This will figure out a valid hash and Nonce if you're creating a differe$ uint256 hashTarget = nProofOfWorkLimit; printf("Target: %s\n", hashTarget.GetHex().c_str()); uint256 newhash = genesis.GetHash(); uint256 besthash; memset(&besthash,0xFF,32); while (newhash > hashTarget) { ++genesis.nNonce; if (genesis.nNonce == 0){ printf("NONCE WRAPPED, incrementing time"); ++genesis.nTime; } newhash = genesis.GetHash(); if(newhash < besthash){ besthash=newhash; printf("New best: %s\n", newhash.GetHex().c_str()); } } printf("Gensis Hash: %s\n", genesis.GetHash().ToString().c_str()); printf("Gensis Hash Merkle: %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("Gensis nTime: %u\n", genesis.nTime); printf("Gensis nBits: %08x\n", genesis.nBits); printf("Gensis Nonce: %u\n\n\n", genesis.nNonce); } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x7e; pchMessageStart[1] = 0x3f; pchMessageStart[2] = 0x95; pchMessageStart[3] = 0xbb; vAlertPubKey = ParseHex("040627d06214ba58f42eb74d475d32bc359c822902fb91766be30bfff2b878d2b5d4efa9e38c2a3438b15ff85e734ce3ce0382f8ebb79b6cdb3bc779af69e0b9b8"); nDefaultPort = 15200; nRPCPort = 15201; nProofOfWorkLimit = ~uint256(0) >> 24; // 000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff nProofOfStakeLimit = ~uint256(0) >> 20; const char* pszTimestamp = "Reuters: Merkel expected to speak with Trump about Russia"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].scriptPubKey = CScript() << ParseHex("04964ae39ac7421145f93a031791749772f671fa1153e4d6df87b1dce87ed2d68a74b46df6cd023ceffbbae4feed084915372d2b8ca866d24dd979af6f09800b3d") << OP_CHECKSIG; vout[0].nValue = (1 * COIN); CTransaction txNew(1, 1485544000, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1485544000; genesis.nBits = 0x1e00ffff; genesis.nNonce = 15789410; hashGenesisBlock = genesis.GetHash(); if (false) { MineGenesis(genesis, nProofOfWorkLimit); } /** Gensis Hash: 0000007d36f5940db0ec8bd99e75cceb3bfa7fd3d11bf2f2898815a6a6630d7e Gensis Hash Merkle: 15f1ba05923859ecb9bf820bed78954c16057396ef4aa4bd57a4a5ee0d695cef Gensis nTime: 1485544000 Gensis nBits: 1e00ffff Gensis Nonce: 15789410 */ assert(hashGenesisBlock == uint256("0x0000007d36f5940db0ec8bd99e75cceb3bfa7fd3d11bf2f2898815a6a6630d7e")); assert(genesis.hashMerkleRoot == uint256("0x15f1ba05923859ecb9bf820bed78954c16057396ef4aa4bd57a4a5ee0d695cef")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vSeeds.push_back(CDNSSeedData("seeder.baseserv.com", "main.seeder.baseserv.com")); vSeeds.push_back(CDNSSeedData("seeder.uksafedns.net", "main.seeder.uksafedns.net")); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nPoolMaxTransactions = 3; strDarksendPoolDummyAddress = "iUUCtBZUVR98Cufh9BbSSqUPJFEtPKSLSe"; nLastPOWBlock = 500; // Preliminary Proof of Work } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x2f; pchMessageStart[1] = 0xca; pchMessageStart[2] = 0x4d; pchMessageStart[3] = 0x3e; nProofOfWorkLimit = ~uint256(0) >> 16; nProofOfStakeLimit = ~uint256(0) >> 16; vAlertPubKey = ParseHex("04cc24ab003c828cdd9cf4db2ebbde8e1cecb3bbfa8b3127fcb9dd9b84d44112080827ed7c49a648af9fe788ff42e316aee665879c553f099e55299d6b54edd7e0"); nDefaultPort = 27170; nRPCPort = 27171; strDataDir = "testnet"; genesis.nVersion = 1; genesis.nTime = 1484332000; genesis.nBits = 0x1f00ffff; genesis.nNonce = 1172; if (false) { MineGenesis(genesis, nProofOfWorkLimit); } // Modify the testnet genesis block so the timestamp is valid for a later start. // assert(hashGenesisBlock == uint256("0x00008ca69320cdd1932a5d19f6602b383d6683e4185b552acb05a32dd94995f2")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,97); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[STEALTH_ADDRESS] = std::vector<unsigned char>(1,40); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include "main.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd9; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 5433; nRPCPort = 5432; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); nSubsidyHalvingInterval = 210000; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) // vMerkleTree: 4a5e1e const char* pszTimestamp = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1231006505; genesis.nBits = 0x1d00ffff; genesis.nNonce = 2083236893; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == MAINNET_GENESIS); assert(genesis.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b")); vSeeds.push_back(CDNSSeedData("earlz.net", "earlz.net")); base58Prefixes[PUBKEY_ADDRESS] = list_of(10); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(128); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 15433; nRPCPort = 15432; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1296688602; genesis.nNonce = 414098458; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == TESTNET_GENESIS); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("earlz.net", "earlz.net")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 2; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; assert(hashGenesisBlock == REGNET_GENESIS); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } void CChainParams::MineNewGenesisBlock() { //This will output (to stdout) the code for a new genesis block when it is found genesis.nTime=time(NULL); genesis.nNonce=0; printf("Searching for genesis block...\n"); uint256 thash; while(1) { thash=genesis.GetHash(); if (CheckProofOfWork(thash, genesis.nBits)) break; if ((genesis.nNonce & 0xFFFF) == 0) { printf("nonce %08X: hash = %s\n",genesis.nNonce, thash.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } printf("genesis.nTime = %u;\n",genesis.nTime); printf("genesis.nNonce = %u;\n",genesis.nNonce); printf("assert(genesis.hashMerkleRoot == uint256(\"0x%s\"));\n",genesis.hashMerkleRoot.ToString().c_str()); printf("assert(genesis.GetHash() == uint256(\"0x%s\"));\n",genesis.GetHash().ToString().c_str()); exit(1); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit()) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } <commit_msg>prepare to mine genesis<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include "main.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd9; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 5433; nRPCPort = 5432; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); nSubsidyHalvingInterval = 210000; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // const char* pszTimestamp = "earlz testing"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("0") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nVersion = 1; MineNewGenesisBlock(); hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == MAINNET_GENESIS); assert(genesis.hashMerkleRoot == uint256("0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b")); vSeeds.push_back(CDNSSeedData("earlz.net", "earlz.net")); base58Prefixes[PUBKEY_ADDRESS] = list_of(10); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(128); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 15433; nRPCPort = 15432; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1296688602; genesis.nNonce = 414098458; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == TESTNET_GENESIS); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("earlz.net", "earlz.net")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 2; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; assert(hashGenesisBlock == REGNET_GENESIS); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } void CChainParams::MineNewGenesisBlock() { //This will output (to stdout) the code for a new genesis block when it is found genesis.nTime=time(NULL); genesis.nNonce=0; printf("Searching for genesis block...\n"); uint256 thash; while(1) { thash=genesis.GetHash(); if (CheckProofOfWork(thash, genesis.nBits)) break; if ((genesis.nNonce & 0xFFFF) == 0) { printf("nonce %08X: hash = %s\n",genesis.nNonce, thash.ToString().c_str()); } ++genesis.nNonce; if (genesis.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++genesis.nTime; } } printf("genesis.nTime = %u;\n",genesis.nTime); printf("genesis.nNonce = %u;\n",genesis.nNonce); printf("assert(genesis.hashMerkleRoot == uint256(\"0x%s\"));\n",genesis.hashMerkleRoot.ToString().c_str()); printf("assert(genesis.GetHash() == uint256(\"0x%s\"));\n",genesis.GetHash().ToString().c_str()); exit(1); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > Params().ProofOfWorkLimit()) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Original Code: Copyright (c) 2009-2014 The Bitcoin Core Developers // Modified Code: Copyright (c) 2014 Project Bitmark // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x46A83599, 0x48DC48A9, 0x5CDE19F5 // networks fixed seed nodes }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd9; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 21); nSubsidyHalvingInterval = 788000; // Build the genesis block. const char* pszTimestamp = "Insight for the benefit of all."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 20 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04f88a76429dad346a10ecb5d36fcbf50bc2e009870e20c1a6df8db743e0b994afc1f91e079be8acc380b0ee7765519906e3d781519e9db48259f64160104939d8") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; // OLD LINE: genesis.nTime = 1405274442; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nTime = 1405274410; genesis.nNonce = 624724; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x6be0214f333f8e533c5723ec780cf370718d30326db67ff690a78bbfeba510ea")); // todo add more dns seeders vSeeds.push_back(CDNSSeedData("zmark.org", "seed.zmark.org")); base58Prefixes[PUBKEY_ADDRESS] = list_of(143); // z base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(271); // Z base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. // Testnet Genesis has a lower difficulty pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); strDataDir = "testnet3"; genesis.nTime = 1405274409; genesis.nNonce = 675600; genesis.nBits = bnProofOfWorkLimit.GetCompact(); hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x23e5abab7d3ce67fbb64f467b3b02f25a35b563d428c75086c38eb72b76e3896")); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("zmark.co", "test.zmark.co")); base58Prefixes[PUBKEY_ADDRESS] = list_of(130); // u base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(185); // U base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1405274400; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>new branch<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Original Code: Copyright (c) 2009-2014 The Bitcoin Core Developers // Modified Code: Copyright (c) 2014 Project Bitmark -> and now zmark // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x46A83599, 0x48DC48A9, 0x5CDE19F5 // networks fixed seed nodes }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd9; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 21); nSubsidyHalvingInterval = 788000; // Build the genesis block. const char* pszTimestamp = "Insight for the benefit of all."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 20 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04f88a76429dad346a10ecb5d36fcbf50bc2e009870e20c1a6df8db743e0b994afc1f91e079be8acc380b0ee7765519906e3d781519e9db48259f64160104939d8") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; // OLD LINE: genesis.nTime = 1405274442; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nTime = 1405274410; genesis.nNonce = 624724; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x6be0214f333f8e533c5723ec780cf370718d30326db67ff690a78bbfeba510ea")); // todo add more dns seeders vSeeds.push_back(CDNSSeedData("zmark.org", "seed.zmark.org")); base58Prefixes[PUBKEY_ADDRESS] = list_of(143); // z base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(271); // Z base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. // Testnet Genesis has a lower difficulty pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 8388; nRPCPort = 8387; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); strDataDir = "testnet3"; genesis.nTime = 1405274409; genesis.nNonce = 675600; genesis.nBits = bnProofOfWorkLimit.GetCompact(); hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x23e5abab7d3ce67fbb64f467b3b02f25a35b563d428c75086c38eb72b76e3896")); vFixedSeeds.clear(); vSeeds.clear(); vSeeds.push_back(CDNSSeedData("zmark.co", "test.zmark.co")); base58Prefixes[PUBKEY_ADDRESS] = list_of(130); // u base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(185); // U base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1405274400; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 18444; strDataDir = "regtest"; //assert(hashGenesisBlock == uint256("0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Moneta developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0xb32b80ef, 0x807f6aeb, 0x259dfa0a, 0xa2d16323, 0x6c3dd236, 0xacf50584, 0x2ea2420a, 0x4e6db2c3, 0x8a80a95e, 0x340b8de5, 0x253b153a, 0x2e69760f, 0xb2217edd, 0x68ec1783, 0x6c3dd125, }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. MAINNET pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0x0c; pchMessageStart[2] = 0x6b; pchMessageStart[3] = 0xbd; vAlertPubKey = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); nDefaultPort = 9999; nRPCPort = 9998; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Moneta starting difficulty is 1 / 2^12 nSubsidyHalvingInterval = 210000; // Genesis block const char* pszTimestamp = "MONETA 10/Jan/2015 Moneta project was born. We Accepting Bitcoins"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 50 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04ffff001d0104414d4f4e4554412031302f4a616e2f32303135204d6f6e6574612070726f6a6563742077617320626f726e2e20576520416363657074696e6720426974636f696e73") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1430669734; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 438078; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000bd555bc569df3c8eb14479f8fd5b281bf0f11122416c82c0ecadf5408cf")); assert(genesis.hashMerkleRoot == uint256("0xe995228562caf76d8283ae06310e70f993bd3b35f00c2f4eeb6414343ecffe08")); vSeeds.push_back(CDNSSeedData("moneta.io", "dnsseed.moneta.io")); vSeeds.push_back(CDNSSeedData("darkcoin.qa", "dnsseed.darkcoin.qa")); vSeeds.push_back(CDNSSeedData("masternode.io", "dnsseed.masternode.io")); vSeeds.push_back(CDNSSeedData("moneta.io", "dnsseed.moneta.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of( 76); // Moneta addresses start with 'X' base58Prefixes[SCRIPT_ADDRESS] = list_of( 16); // Moneta script addresses start with '7' base58Prefixes[SECRET_KEY] = list_of(204); // Moneta private keys start with '7' or 'X' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0xF8); // Moneta BIP32 pubkeys start with 'drkv' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0xCC); // Moneta BIP32 prvkeys start with 'drkp' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000005); // Moneta BIP44 coin type is '5' // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // TESTNET (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. TESTNET pchMessageStart[0] = 0xce; pchMessageStart[1] = 0xe2; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0xff; vAlertPubKey = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); nDefaultPort = 19999; nRPCPort = 19998; strDataDir = "testnet3"; // Modify the TESTNET genesis block so the timestamp is valid for a later start. genesis.nTime = 1430670314; genesis.nNonce = 239363; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000068319b18033754d6824c918ea318441fde2ba1c58b6b926b03825da4996")); vFixedSeeds.clear(); vSeeds.clear(); /*vSeeds.push_back(CDNSSeedData("moneta.io", "testnet-seed.moneta.io")); vSeeds.push_back(CDNSSeedData("moneta.qa", "testnet-seed.moneta.qa")); *///legacy seeders vSeeds.push_back(CDNSSeedData("moneta.io", "testnet-seed.moneta.io")); vSeeds.push_back(CDNSSeedData("seed.moneta.io", "testnet.seed.moneta.io")); vSeeds.push_back(CDNSSeedData("moneta.poolcoin.pw", "seed.moneta.poolcoin.pw")); base58Prefixes[PUBKEY_ADDRESS] = list_of(139); // Testnet moneta addresses start with 'x' or 'y' base58Prefixes[SCRIPT_ADDRESS] = list_of( 19); // Testnet moneta script addresses start with '8' or '9' base58Prefixes[SECRET_KEY] = list_of(239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x3a)(0x80)(0x61)(0xa0); // Testnet moneta BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_SECRET_KEY] = list_of(0x3a)(0x80)(0x58)(0x37); // Testnet moneta BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000001); // Testnet moneta BIP44 coin type is '5' (All coin's testnet default) } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1430670314; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 239363; nDefaultPort = 19994; strDataDir = "regtest"; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000068319b18033754d6824c918ea318441fde2ba1c58b6b926b03825da4996")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>Update chainparams.cpp<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Moneta developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0xBCA65599, 0xBCA64EA4, 0xBCA64EDD }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. MAINNET pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0x0c; pchMessageStart[2] = 0x6b; pchMessageStart[3] = 0xbd; vAlertPubKey = ParseHex("04ffff001d01042357697265642031352f4d61792f3230313520426974636f696e206d757374206c697665"); nDefaultPort = 9999; nRPCPort = 9998; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // Moneta starting difficulty is 1 / 2^12 nSubsidyHalvingInterval = 210000; // Genesis block const char* pszTimestamp = "Wired 15/May/2015 Bitcoin must live"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 500 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1431650687; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 70294; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000003ab930a6d828497a846575e78e5049d51916ce60856339dc6c5ec139662")); assert(genesis.hashMerkleRoot == uint256("0xa82b008ef45b53ec2b546a8c66c9781456d7a1ac5311f0b4c9edc7cdd324b453")); vSeeds.push_back(CDNSSeedData("seed.moneta.io", "seed.moneta.io")); vSeeds.push_back(CDNSSeedData("moneta.poolcoin.pw", "moneta.poolcoin.pw")); vSeeds.push_back(CDNSSeedData("seed2.moneta.io", "seed2.moneta.io")); base58Prefixes[PUBKEY_ADDRESS] = list_of( 76); // Moneta addresses start with 'X' base58Prefixes[SCRIPT_ADDRESS] = list_of( 16); // Moneta script addresses start with '7' base58Prefixes[SECRET_KEY] = list_of(204); // Moneta private keys start with '7' or 'X' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0xF8); // Moneta BIP32 pubkeys start with 'drkv' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0xCC); // Moneta BIP32 prvkeys start with 'drkp' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000005); // Moneta BIP44 coin type is '5' // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // TESTNET (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. TESTNET pchMessageStart[0] = 0xce; pchMessageStart[1] = 0xe2; pchMessageStart[2] = 0xca; pchMessageStart[3] = 0xff; vAlertPubKey = ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"); nDefaultPort = 19999; nRPCPort = 19998; strDataDir = "testnet3"; // Modify the TESTNET genesis block so the timestamp is valid for a later start. genesis.nTime = 1431650687; genesis.nNonce = 70294; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000003ab930a6d828497a846575e78e5049d51916ce60856339dc6c5ec139662")); vFixedSeeds.clear(); vSeeds.clear(); /*vSeeds.push_back(CDNSSeedData("moneta.io", "testnet-seed.moneta.io")); vSeeds.push_back(CDNSSeedData("moneta.qa", "testnet-seed.moneta.qa")); *///legacy seeders vSeeds.push_back(CDNSSeedData("moneta.io", "testnet-seed.moneta.io")); vSeeds.push_back(CDNSSeedData("seed.moneta.io", "testnet.seed.moneta.io")); vSeeds.push_back(CDNSSeedData("moneta.poolcoin.pw", "seed.moneta.poolcoin.pw")); base58Prefixes[PUBKEY_ADDRESS] = list_of(139); // Testnet moneta addresses start with 'x' or 'y' base58Prefixes[SCRIPT_ADDRESS] = list_of( 19); // Testnet moneta script addresses start with '8' or '9' base58Prefixes[SECRET_KEY] = list_of(239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x3a)(0x80)(0x61)(0xa0); // Testnet moneta BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_SECRET_KEY] = list_of(0x3a)(0x80)(0x58)(0x37); // Testnet moneta BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_COIN_TYPE] = list_of(0x80000001); // Testnet moneta BIP44 coin type is '5' (All coin's testnet default) } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfc; pchMessageStart[1] = 0xc1; pchMessageStart[2] = 0xb7; pchMessageStart[3] = 0xdc; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1430670314; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 239363; nDefaultPort = 19994; strDataDir = "regtest"; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000068319b18033754d6824c918ea318441fde2ba1c58b6b926b03825da4996")); vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x00000000 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xb8; pchMessageStart[1] = 0xeb; pchMessageStart[2] = 0xb3; pchMessageStart[3] = 0xdf; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 9340; nRPCPort = 9341; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 32); nSubsidyHalvingInterval = 2100000; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1408638282, nBits=1d00ffff, nNonce=1408638282, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01042654686520696e63657074696f6e206f662043726f776e636f696e2032302f4175672f32303134) // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) // vMerkleTree: 4a5e1e const char* pszTimestamp = "Crowncoin - Tradition merged with technology 10/Oct/2014"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 10 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1412760826; genesis.nBits = 0x1d00ffff; genesis.nNonce = 1612467894; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000000085370d5e122f64f4ab19c68614ff3df78c8d13cb814fd7e69a1dc6da")); //assert(genesis.hashMerkleRoot == uint256("0xf2ce47889874027a63af9cc324eb43b57bf1cfe68234089d5d68d88d9aef704f")); vSeeds.push_back(CDNSSeedData("crowncoin.org", "nodelist.crowncoin.org")); base58Prefixes[PUBKEY_ADDRESS] = list_of(0); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(128); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x0c; pchMessageStart[1] = 0x17; pchMessageStart[2] = 0x0f; pchMessageStart[3] = 0x05; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 19340; nRPCPort = 19341; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1405338325; genesis.nNonce = 1678912305; hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x000000005f94b67f20bf3cad62cf7cf74fd7f2878574d3e81015d38ffacd7b6e")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("bitcoin.petertodd.org", "testnet-seed.bitcoin.petertodd.org")); // vSeeds.push_back(CDNSSeedData("bluematt.me", "testnet-seed.bluematt.me")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xae; pchMessageStart[2] = 0xc6; pchMessageStart[3] = 0xdf; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 2; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 19444; strDataDir = "regtest"; vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>new genesis block<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "assert.h" #include "core.h" #include "protocol.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; // // Main network // unsigned int pnSeed[] = { 0x00000000 }; class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xb8; pchMessageStart[1] = 0xeb; pchMessageStart[2] = 0xb3; pchMessageStart[3] = 0xdf; vAlertPubKey = ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); nDefaultPort = 9340; nRPCPort = 9341; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 32); nSubsidyHalvingInterval = 2100000; // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // // CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1408638282, nBits=1d00ffff, nNonce=1408638282, vtx=1) // CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01042654686520696e63657074696f6e206f662043726f776e636f696e2032302f4175672f32303134) // CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) // vMerkleTree: 4a5e1e const char* pszTimestamp = "The inception of Crowncoin 10/Oct/2014"; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 10 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1412760826; genesis.nBits = 0x1d00ffff; genesis.nNonce = 1612467894; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000000085370d5e122f64f4ab19c68614ff3df78c8d13cb814fd7e69a1dc6da")); //assert(genesis.hashMerkleRoot == uint256("0xf2ce47889874027a63af9cc324eb43b57bf1cfe68234089d5d68d88d9aef704f")); vSeeds.push_back(CDNSSeedData("crowncoin.org", "nodelist.crowncoin.org")); base58Prefixes[PUBKEY_ADDRESS] = list_of(0); base58Prefixes[SCRIPT_ADDRESS] = list_of(5); base58Prefixes[SECRET_KEY] = list_of(128); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); // Convert the pnSeeds array into usable address objects. for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vFixedSeeds.push_back(addr); } } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet (v3) // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x0c; pchMessageStart[1] = 0x17; pchMessageStart[2] = 0x0f; pchMessageStart[3] = 0x05; vAlertPubKey = ParseHex("04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a"); nDefaultPort = 19340; nRPCPort = 19341; strDataDir = "testnet3"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1405338325; genesis.nNonce = 1678912305; hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x000000005f94b67f20bf3cad62cf7cf74fd7f2878574d3e81015d38ffacd7b6e")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("bitcoin.petertodd.org", "testnet-seed.bitcoin.petertodd.org")); // vSeeds.push_back(CDNSSeedData("bluematt.me", "testnet-seed.bluematt.me")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; // // Regression test // class CRegTestParams : public CTestNetParams { public: CRegTestParams() { pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xae; pchMessageStart[2] = 0xc6; pchMessageStart[3] = 0xdf; nSubsidyHalvingInterval = 150; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1); genesis.nTime = 1296688602; genesis.nBits = 0x207fffff; genesis.nNonce = 2; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 19444; strDataDir = "regtest"; vSeeds.clear(); // Regtest mode doesn't have any DNS seeds. } virtual bool RequireRPCPassword() const { return false; } virtual Network NetworkID() const { return CChainParams::REGTEST; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; case CChainParams::REGTEST: pCurrentParams = &regTestParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) { return false; } if (fRegTest) { SelectParams(CChainParams::REGTEST); } else if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before> // A Sample of ORM Lite // https://github.com/BOT-Man-JL/ORM-Lite // BOT Man, 2016 #include <string> #include <iostream> #include "src/ORMLite.h" using namespace BOT_ORM; /* #0 Basic Usage */ struct MyClass { long id; double score; std::string name; // Inject ORM-Lite into this Class ORMAP (MyClass, id, score, name) }; int main () { /* #1 Basic Usage */ // Store the Data in "test.db" ORMapper<MyClass> mapper ("test.db"); // Create a table for "MyClass" mapper.CreateTbl (); // Insert Values into the table std::vector<MyClass> initObjs = { { 0, 0.2, "John" }, { 1, 0.4, "Jack" }, { 2, 0.6, "Jess" } }; for (const auto obj : initObjs) mapper.Insert (obj); // Update Entry by KEY (id) initObjs[1].score = 1.0; mapper.Update (initObjs[1]); // Delete Entry by KEY (id) mapper.Delete (initObjs[2]); // Select All to Vector auto query0 = mapper.Query (MyClass ()).ToVector (); // query0 = [{ 0, 0.2, "John"}, // { 1, 1.0, "Jack"}] // If 'Insert' Failed, Print the latest Error Message if (!mapper.Insert (MyClass { 1, 0, "Joke" })) auto err = mapper.ErrMsg (); // err = "SQL error: UNIQUE constraint failed: MyClass.id" /* #2 Batch Operations */ // Insert by Batch Insert // Performance is much Better than Separated Insert :-) std::vector<MyClass> dataToSeed; for (long i = 50; i < 100; i++) dataToSeed.emplace_back (MyClass { i, i * 0.2, "July" }); mapper.Insert (dataToSeed); // Update by Batch Update for (size_t i = 0; i < 50; i++) dataToSeed[i].score += 1; mapper.Update (dataToSeed); /* #3 Composite Query */ // Define a Query Helper Object MyClass _mc; // Select by Query :-) auto query1 = mapper.Query (_mc) // Link '_mc' to its fields .Where ( Expr (_mc.name, "=", "July") && ( Expr (_mc.id, "<=", 90) && Expr (_mc.id, ">=", 60) ) ) .OrderBy (_mc.id, true) .Limit (3, 10) .ToVector (); // Select by SQL, NOT Recommended :-( std::vector<MyClass> query2; mapper.Select (query2, "where (name='July' and (id<=90 and id>=60))" " order by id desc" " limit 3 offset 10"); // Note that: query1 = query2 = // [{ 80, 17.0, "July"}, { 79, 16.8, "July"}, { 78, 16.6, "July"}] // Count by Query :-) auto count1 = mapper.Query (_mc) // Link '_mc' to its fields // Auto Cosntruct Expr { _mc.name, "=", "July" } :-) .Where ({ _mc.name, "=", "July" }) .Count (); // Count by SQL, NOT Recommended :-( auto count2 = mapper.Count ("where (name='July')"); // Note that: // count1 = count2 = 50 // Delete by Query :-) mapper.Query (_mc) // Link '_mc' to its fields // Auto Cosntruct Expr { _mc.name, "=", "July" } :-) .Where ({ _mc.name = "July" }) .Delete (); // Delete by SQL, NOT Recommended :-( mapper.Delete ("where (name='July')"); // Drop the table "MyClass" mapper.DropTbl (); // Output to Console auto printVec = [] (const std::vector<MyClass> vec) { for (auto& item : vec) std::cout << item.id << "\t" << item.score << "\t" << item.name << std::endl; std::cout << std::endl; }; printVec (query0); printVec (query1); printVec (query2); std::cout << count1 << " " << count2 << std::endl; std::cin.get (); return 0; } <commit_msg>Fix alignment;<commit_after> // A Sample of ORM Lite // https://github.com/BOT-Man-JL/ORM-Lite // BOT Man, 2016 #include <string> #include <iostream> #include "src/ORMLite.h" using namespace BOT_ORM; /* #0 Basic Usage */ struct MyClass { long id; double score; std::string name; // Inject ORM-Lite into this Class ORMAP (MyClass, id, score, name) }; int main () { /* #1 Basic Usage */ // Store the Data in "test.db" ORMapper<MyClass> mapper ("test.db"); // Create a table for "MyClass" mapper.CreateTbl (); // Insert Values into the table std::vector<MyClass> initObjs = { { 0, 0.2, "John" }, { 1, 0.4, "Jack" }, { 2, 0.6, "Jess" } }; for (const auto obj : initObjs) mapper.Insert (obj); // Update Entry by KEY (id) initObjs[1].score = 1.0; mapper.Update (initObjs[1]); // Delete Entry by KEY (id) mapper.Delete (initObjs[2]); // Select All to Vector auto query0 = mapper.Query (MyClass ()).ToVector (); // query0 = [{ 0, 0.2, "John"}, // { 1, 1.0, "Jack"}] // If 'Insert' Failed, Print the latest Error Message if (!mapper.Insert (MyClass { 1, 0, "Joke" })) auto err = mapper.ErrMsg (); // err = "SQL error: UNIQUE constraint failed: MyClass.id" /* #2 Batch Operations */ // Insert by Batch Insert // Performance is much Better than Separated Insert :-) std::vector<MyClass> dataToSeed; for (long i = 50; i < 100; i++) dataToSeed.emplace_back (MyClass { i, i * 0.2, "July" }); mapper.Insert (dataToSeed); // Update by Batch Update for (size_t i = 0; i < 50; i++) dataToSeed[i].score += 1; mapper.Update (dataToSeed); /* #3 Composite Query */ // Define a Query Helper Object MyClass _mc; // Select by Query :-) auto query1 = mapper.Query (_mc) // Link '_mc' to its fields .Where ( Expr (_mc.name, "=", "July") && ( Expr (_mc.id, "<=", 90) && Expr (_mc.id, ">=", 60) ) ) .OrderBy (_mc.id, true) .Limit (3, 10) .ToVector (); // Select by SQL, NOT Recommended :-( std::vector<MyClass> query2; mapper.Select (query2, "where (name='July' and (id<=90 and id>=60))" " order by id desc" " limit 3 offset 10"); // Note that: query1 = query2 = // [{ 80, 17.0, "July"}, { 79, 16.8, "July"}, { 78, 16.6, "July"}] // Count by Query :-) auto count1 = mapper.Query (_mc) // Link '_mc' to its fields // Auto Cosntruct Expr { _mc.name, "=", "July" } :-) .Where ({ _mc.name, "=", "July" }) .Count (); // Count by SQL, NOT Recommended :-( auto count2 = mapper.Count ("where (name='July')"); // Note that: // count1 = count2 = 50 // Delete by Query :-) mapper.Query (_mc) // Link '_mc' to its fields // Auto Cosntruct Expr { _mc.name, "=", "July" } :-) .Where ({ _mc.name = "July" }) .Delete (); // Delete by SQL, NOT Recommended :-( mapper.Delete ("where (name='July')"); // Drop the table "MyClass" mapper.DropTbl (); // Output to Console auto printVec = [] (const std::vector<MyClass> vec) { for (auto& item : vec) std::cout << item.id << "\t" << item.score << "\t" << item.name << std::endl; std::cout << std::endl; }; printVec (query0); printVec (query1); printVec (query2); std::cout << count1 << " " << count2 << std::endl; std::cin.get (); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <geometry/point.h> #include <geometry/grid.h> #include <geometry/sampled_mapping.h> #include <numerics/corner_singularity_biharmonic.h> //#include <numerics/atez.h> using namespace MathTL; using namespace std; int main() { cout << "Testing CornerSingularity ..." << endl; Point<2> origin; #if 1 CornerSingularityBiharmonic s(origin, 0.5, 1.5); const bool matlab = true; // false -> Octave output if (matlab) cout << "- Matlab output of the corner singularity on a 2D grid..." << endl; else cout << "- Octave output of the corner singularity on a 2D grid..." << endl; Grid<2> grid(Point<2>(-1.0, -1.0), Point<2>(1.0, 1.0), 1<<6, 1<<6); // Grid<2> grid(Point<2>(-1.0, 0.0), Point<2>(0.0, 1.0), 1<<6, 1<<6); // only patch 0 // Grid<2> grid(Point<2>(-1.0, -1.0), Point<2>(0.0, 1.0), 1<<6, 1<<6); // only patches 0+1 // Grid<1> grid(0.0,1.0,1<<10); SampledMapping<2> h(grid, s); std::ofstream fs("corner_maple.m"); if (matlab) h.matlab_output(fs); else h.octave_output(fs); if (matlab) fs << "surf(x,y,z)" << endl; else fs << "mesh(x,y,z)" << endl; fs.close(); // cout << " ...done, see file corner.m!" << endl; CornerSingularityBiharmonicRHS rhs(origin, 0.5, 1.5); if (matlab) cout << "- Matlab output of the corner singularity rhs on a 2D grid..." << endl; else cout << "- Octave output of the corner singularity rhs on a 2D grid..." << endl; SampledMapping<2> h_rhs(grid, rhs); std::ofstream fs_rhs("corner_rhs_maple.m"); if (matlab) h_rhs.matlab_output(fs_rhs); else h_rhs.octave_output(fs_rhs); if (matlab) fs_rhs << "surf(x,y,z)" << endl; else fs_rhs << "mesh(x,y,z)" << endl; fs_rhs.close(); cout << " ...done, see file corner_rhs.m!" << endl; #endif // Atez zeta;//(double r0 0.01 , double r1 = 0.99); // SampledMapping<1> h(grid, zeta); // std::ofstream fs_rhs("zeta.m"); // h.matlab_output(fs_rhs); // fs_rhs.close(); return 0; } <commit_msg>Nothing changed.<commit_after>#include <iostream> #include <fstream> #include <geometry/point.h> #include <geometry/grid.h> #include <geometry/sampled_mapping.h> #include <numerics/corner_singularity_biharmonic.h> //#include <numerics/atez.h> using namespace MathTL; using namespace std; int main() { cout << "Testing CornerSingularity ..." << endl; Point<2> origin; #if 1 CornerSingularityBiharmonic s(origin, 0.5, 1.5); const bool matlab = true; // false -> Octave output if (matlab) cout << "- Matlab output of the corner singularity on a 2D grid..." << endl; else cout << "- Octave output of the corner singularity on a 2D grid..." << endl; Grid<2> grid(Point<2>(-1.0, -1.0), Point<2>(1.0, 1.0), 1<<6, 1<<6); // Grid<2> grid(Point<2>(-1.0, 0.0), Point<2>(0.0, 1.0), 1<<6, 1<<6); // only patch 0 // Grid<2> grid(Point<2>(-1.0, -1.0), Point<2>(0.0, 1.0), 1<<6, 1<<6); // only patches 0+1 // Grid<1> grid(0.0,1.0,1<<10); SampledMapping<2> h(grid, s); std::ofstream fs("corner_maple.m"); if (matlab) h.matlab_output(fs); else h.octave_output(fs); if (matlab) fs << "surf(x,y,z)" << endl; else fs << "mesh(x,y,z)" << endl; fs.close(); // cout << " ...done, see file corner.m!" << endl; //CornerSingularityBiharmonicRHS rhs(origin, 0.5, 1.5); CornerSingularityBiharmonic rhs(origin, 0.5, 1.5); if (matlab) cout << "- Matlab output of the corner singularity rhs on a 2D grid..." << endl; else cout << "- Octave output of the corner singularity rhs on a 2D grid..." << endl; SampledMapping<2> h_rhs(grid, rhs); std::ofstream fs_rhs("corner_rhs_maple.m"); if (matlab) h_rhs.matlab_output(fs_rhs); else h_rhs.octave_output(fs_rhs); if (matlab) fs_rhs << "surf(x,y,z)" << endl; else fs_rhs << "mesh(x,y,z)" << endl; fs_rhs.close(); cout << " ...done, see file corner_rhs.m!" << endl; #endif // Atez zeta;//(double r0 0.01 , double r1 = 0.99); // SampledMapping<1> h(grid, zeta); // std::ofstream fs_rhs("zeta.m"); // h.matlab_output(fs_rhs); // fs_rhs.close(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x4d96a915f49d40b1e5c2844d1ee2dccb90013a990ccea12c492d22110489f0c4")) ( 24200, uint256("0xd7ed819858011474c8b0cae4ad0b9bdbb745becc4c386bc22d1220cc5a4d1787")) ; static const CCheckpointData data = { &mapCheckpoints, 1390701333, // * UNIX timestamp of last checkpoint block 55013, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 8000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1389241455, 0, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Checkpoint mainnet at block 65000<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x4d96a915f49d40b1e5c2844d1ee2dccb90013a990ccea12c492d22110489f0c4")) ( 24200, uint256("0xd7ed819858011474c8b0cae4ad0b9bdbb745becc4c386bc22d1220cc5a4d1787")) ( 65000, uint256("0x9e673a69c35a423f736ab66f9a195d7c42f979847a729c0f3cef2c0b8b9d0289")) ; static const CCheckpointData data = { &mapCheckpoints, 1396856613, // * UNIX timestamp of last checkpoint block 511112, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 8000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1389241455, 0, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "txdb.h" #include "main.h" #include "uint256.h" static const int nCheckpointSpan = 500; namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000095667f3c1fdbf0b9b4937be57c6401162fcfe72be373df27393f0c69d93") ) // genesis ( 50000, uint256("0x38de11fd0ac1ef41a3fab6d5faac3e597c509244ad028dba20a12832f9b38e92") ) ( 100000, uint256("0x4d32d90e958c1060a8346dbcd72b96459bcc9ded1241d51f7b09be3eaf405901") ) ( 150000, uint256("0x3efea69afbdfaab1a9e2d1240a014aa7c88c66cf246107febbe0d2db147e7350") ) ( 200000, uint256("0xf0bb302a774b841e03d3818f980ecb0c1354f7ff048ff2dc004c3003178c3d56") ) ( 250000, uint256("0xa7325d458200a636d20f3be182d2121acb725de486adf1f855cb72ea9203f56d") ) ( 300000, uint256("0x3c536e6c98d1eb54610a7133d671f560627d731aaef8a46db35335255217d2eb") ) ( 330000, uint256("0xbc45b022e71c2c83765009426a5a54db7e6fa4f94d3ee53e1418a54388529b95") ) ( 360000, uint256("0x103c1ee3cf53529a1bee0bfdff21a32bec361c668df6f7bfc3665d84cbad394d") ) ( 423000, uint256("0x00000000000000940d7a26bfaf12ac74bcefb22ff231560b805deac6728917fc") ) ( 451000, uint256("0x66e23ed10acad88fe2b81c3e31d510dd37ee351c217c5c1a2146bcab754e89cc") ) ( 472737, uint256("0x2b306a5c48b16fd7fd84017ef6a9df4da86bb9871bf8a015a74044d41ec84aaa") ) ( 482666, uint256("0x9291b42d4b06da001a471a306888c0a58329b812ed26509129e0231545d7a93a") ) ( 499888, uint256("0xe9c977ab38ce0d47dc222e078ad71a548c67425d563d79d8f25247eaf6457e1c") ) ; // TestNet has no checkpoints static MapCheckpoints mapCheckpointsTestnet; bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); if (checkpoints.empty()) return 0; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } // Automatically select a suitable sync-checkpoint const CBlockIndex* AutoSelectSyncCheckpoint() { const CBlockIndex *pindex = pindexBest; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Check against synchronized checkpoint bool CheckSync(int nHeight) { const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; return true; } } <commit_msg>Add CP at 511111<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "txdb.h" #include "main.h" #include "uint256.h" static const int nCheckpointSpan = 500; namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0x0000095667f3c1fdbf0b9b4937be57c6401162fcfe72be373df27393f0c69d93") ) // genesis ( 50000, uint256("0x38de11fd0ac1ef41a3fab6d5faac3e597c509244ad028dba20a12832f9b38e92") ) ( 100000, uint256("0x4d32d90e958c1060a8346dbcd72b96459bcc9ded1241d51f7b09be3eaf405901") ) ( 150000, uint256("0x3efea69afbdfaab1a9e2d1240a014aa7c88c66cf246107febbe0d2db147e7350") ) ( 200000, uint256("0xf0bb302a774b841e03d3818f980ecb0c1354f7ff048ff2dc004c3003178c3d56") ) ( 250000, uint256("0xa7325d458200a636d20f3be182d2121acb725de486adf1f855cb72ea9203f56d") ) ( 300000, uint256("0x3c536e6c98d1eb54610a7133d671f560627d731aaef8a46db35335255217d2eb") ) ( 330000, uint256("0xbc45b022e71c2c83765009426a5a54db7e6fa4f94d3ee53e1418a54388529b95") ) ( 360000, uint256("0x103c1ee3cf53529a1bee0bfdff21a32bec361c668df6f7bfc3665d84cbad394d") ) ( 423000, uint256("0x00000000000000940d7a26bfaf12ac74bcefb22ff231560b805deac6728917fc") ) ( 451000, uint256("0x66e23ed10acad88fe2b81c3e31d510dd37ee351c217c5c1a2146bcab754e89cc") ) ( 472737, uint256("0x2b306a5c48b16fd7fd84017ef6a9df4da86bb9871bf8a015a74044d41ec84aaa") ) ( 482666, uint256("0x9291b42d4b06da001a471a306888c0a58329b812ed26509129e0231545d7a93a") ) ( 499888, uint256("0xe9c977ab38ce0d47dc222e078ad71a548c67425d563d79d8f25247eaf6457e1c") ) ( 511111, uint256("0xf2e9623e0efe8fe23687126cb5cb7588584407e89121fa238d7729af38366de7") ) ; // TestNet has no checkpoints static MapCheckpoints mapCheckpointsTestnet; bool CheckHardened(int nHeight, const uint256& hash) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); if (checkpoints.empty()) return 0; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } // Automatically select a suitable sync-checkpoint const CBlockIndex* AutoSelectSyncCheckpoint() { const CBlockIndex *pindex = pindexBest; // Search backward for a block within max span and maturity window while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) pindex = pindex->pprev; return pindex; } // Check against synchronized checkpoint bool CheckSync(int nHeight) { const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint(); if (nHeight <= pindexSync->nHeight) return false; return true; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 1, uint256("0xe613b5a195556386f422875d8df68e3e154f37b4981dec641fe041211672870f")) ( 2016, uint256("0x94a9ab39b9e1e7dafdda1a5823c11556750157aa16e93ae2a59de426e185de58")) ( 4032, uint256("0xa29010ca0ec82b0d2d937f5d82d2e30918467b1f4b3bb51026d13782b7aac73a")) ( 8064, uint256("0x76ef2061b587842f424aae28fcab25fb8434612b58125258292799aaaed0f833")) ( 12096, uint256("0x5abe39584788a018296d97a6f00ca80c81603ebbe8ad84af5778e7d6fcdbed70")) ( 13422, uint256("0xc70a40fe1c53e5525636644e625d4c38c8493b180a0ca81c9d7c9801748e6b52")) ( 14496, uint256("0xd50a2656a6ac593ebb034c1d5ca5eac93220455727f677e7506629f61d566239")) ; static const CCheckpointData data = { &mapCheckpoints, 1398890889, // * UNIX timestamp of last checkpoint block 16135, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 600.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x0d44ae9be7f13a64253c9b61dbbddc37304e1c359fd593565caf356e4fd597c7")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1393990003, 0, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Checkpoint @ Block 15809<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 1, uint256("0xe613b5a195556386f422875d8df68e3e154f37b4981dec641fe041211672870f")) ( 2016, uint256("0x94a9ab39b9e1e7dafdda1a5823c11556750157aa16e93ae2a59de426e185de58")) ( 4032, uint256("0xa29010ca0ec82b0d2d937f5d82d2e30918467b1f4b3bb51026d13782b7aac73a")) ( 8064, uint256("0x76ef2061b587842f424aae28fcab25fb8434612b58125258292799aaaed0f833")) ( 12096, uint256("0x5abe39584788a018296d97a6f00ca80c81603ebbe8ad84af5778e7d6fcdbed70")) ( 13422, uint256("0xc70a40fe1c53e5525636644e625d4c38c8493b180a0ca81c9d7c9801748e6b52")) ( 14496, uint256("0xd50a2656a6ac593ebb034c1d5ca5eac93220455727f677e7506629f61d566239")) ( 15809, uint256("0x31cdc96eb5510e69bf2635b76b0266c0065839685bb30d9b94224d9a5c972b78")) ; static const CCheckpointData data = { &mapCheckpoints, 1399736336, // * UNIX timestamp of last checkpoint block 18226, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 600.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x0d44ae9be7f13a64253c9b61dbbddc37304e1c359fd593565caf356e4fd597c7")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1393990003, 0, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2014 BlitzCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xafaf057ef023cb6799f554c9faef896d20eda2594b8ee02c32f165486d4751ec")) ( 100, uint256("0xa0d7b106ae20ef57386998369826bfd87ea1d1c8af53984820f4e7c85a1c6f1c")) ( 150, uint256("0xbe14b2084e69121890fd2dea6a1e6644e7b0632471436adaac0fd9200bd43dbc")) ( 303, uint256("0x879902ffd867f4843bbba2c25ce43e32cba896b856c620afc5391ea6a4a9da79")) ( 500, uint256("0xeff58a380b74b9d5b0ecd1090fbc4732a7fac7ede4b078f23e1d7cf0aba6f84e")) ( 700, uint256("0x53e0f3005e6429ab162fcf73b398dda0afe71eb5e5bb8a9dd0d9ab6a47b5b318")) ( 999, uint256("0xedb846f5fd67278b47b160cf00a4f4a1d8a5ee83a4b01fccf43bbfc37a09ebfa")) ( 1500, uint256("0xed3a473ad4b9cdc66f345af53d130e3b5f0cd824fb129b713158001d76d87c1d")) ( 1901, uint256("0xeedee54336e3d372d2d17efa02fce71c10a49d0172daa781259b5b9d919fa380")) ( 2203, uint256("0xfca331d8f613bdcb924570b8f993cfee409e1f78ec2f2afd8347b33efad2d33a")) ( 2701, uint256("0x85618f98239b0f120914c17f7f37795aa32887e9b17e026f0c00323e05a77b06")) ( 3000, uint256("0xef6c66058e32c8d0d23161ef301988c04e9298157311b64c6fea1fe45e9b4bed")) ( 3150, uint256("0x22cedee94491c18bbdcb0a4da50cdcb0692c46c3bfccfe8a9d7b543e43c2337d")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>adding checkpoints<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2014 BlitzCoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xafaf057ef023cb6799f554c9faef896d20eda2594b8ee02c32f165486d4751ec")) ( 100, uint256("0xa0d7b106ae20ef57386998369826bfd87ea1d1c8af53984820f4e7c85a1c6f1c")) ( 150, uint256("0xbe14b2084e69121890fd2dea6a1e6644e7b0632471436adaac0fd9200bd43dbc")) ( 303, uint256("0x879902ffd867f4843bbba2c25ce43e32cba896b856c620afc5391ea6a4a9da79")) ( 500, uint256("0xeff58a380b74b9d5b0ecd1090fbc4732a7fac7ede4b078f23e1d7cf0aba6f84e")) ( 700, uint256("0x53e0f3005e6429ab162fcf73b398dda0afe71eb5e5bb8a9dd0d9ab6a47b5b318")) ( 999, uint256("0xedb846f5fd67278b47b160cf00a4f4a1d8a5ee83a4b01fccf43bbfc37a09ebfa")) ( 1500, uint256("0xed3a473ad4b9cdc66f345af53d130e3b5f0cd824fb129b713158001d76d87c1d")) ( 1901, uint256("0xeedee54336e3d372d2d17efa02fce71c10a49d0172daa781259b5b9d919fa380")) ( 2203, uint256("0xfca331d8f613bdcb924570b8f993cfee409e1f78ec2f2afd8347b33efad2d33a")) ( 2701, uint256("0x85618f98239b0f120914c17f7f37795aa32887e9b17e026f0c00323e05a77b06")) ( 3000, uint256("0xef6c66058e32c8d0d23161ef301988c04e9298157311b64c6fea1fe45e9b4bed")) ( 3150, uint256("0x22cedee94491c18bbdcb0a4da50cdcb0692c46c3bfccfe8a9d7b543e43c2337d")) ( 3375, uint256("0x89bc95c8f702110c9352ec8052a44e2cb318a26fef8c355036fe8f954043063e")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2015 The Bitcoin developers // Copyright (c) 2011-2015 Litecoin Developers // Copyright (c) 2013-2015 Globalcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of //Gensis and Checkpoints ( 0, uint256("0xa28dcb138cef4fa6ea6e1a49fafb352c72c4fffa6674f2bb7e506817e27bdfcc")) ( 2230, uint256("0x71a9d486b349c840ffdf29927414aa903c1443f945b7b2618d807ea8f3e15699")) ( 7000, uint256("0xf8aa8224404caeada717008f6df70db2a2b6d04e44c29ee1fa7abcee7ae2aa5a")) ( 12000, uint256("0x0f44a3b36b9d501f59a4e6b218a1f311b5342de436b134148cd902be7c3b4b05")) ( 18000, uint256("0x21fb15db01439362a5113ea3c1cac04163673798974fd43f0c0e6532fab5f26d")) ( 22300, uint256("0x063e89eae28119aa94cf44c9d7e155aec9ae4229dba37bd6456431e49868a039")) ( 22644, uint256("0x9aec5d2cb0f43cc8089878daf85d5c441e9ee9b0e030263f13c23befef11a0cd")) ( 26051, uint256("0x9541a7030ae49c99660ccf3242ccee6959153877fbfc1d53afe9cc9c04d85f6e")) ( 39058, uint256("0x1ff3b6e143861c01fd952c16501c32b3723c8c14b8f1c62ca63d1daa22f5b0dd")) ( 45053, uint256("0x403536342585bcfc3b299f919dff220c4a9facd2d4bb83f77aa8ab3ba3f0171c")) ( 52062, uint256("0xccfe2de478a51a69cccd6ee765caee4f78d8ee4655ca708555b806aac911feca")) ( 63390, uint256("0x9176fa0f727374ad7eda5206912cd81eefeb0a2ebb8878dab84f8cb1b65ee43f")) ( 63399, uint256("0xae14b26cab4753cd6f0d15c3223ac7046f944d7510988851a48a6af5fd556b51")) ( 63417, uint256("0xcc0a685b344f4fd1503974ef95d63f545edfe831fa30e1770cc676181d674fec")) ( 63424, uint256("0x8ebe2f5acebe0bce1819645ceca3337c3c312ab8b2c298a5d5cf542531117a4b")) ( 75000, uint256("0x2ace5643f4501d542bd6c047605c619c4854585050b677f97a6be7880eb02766")) ( 85000, uint256("0x18d9c82e34157fb48f7722d1557bb505f7794e3465bbf0dbbde7b22b8dd98ebd")) ( 90000, uint256("0xbd27920f0035a682e5807ed4539ee7e338538abca2915ce21b8e17725a161a7f")) ( 97000, uint256("0x90c415d63cf43621a28e9962d31c07ffeea01184bbd1f5f7ffc71dc7cc33e1a8")) ( 97200, uint256("0x5c561e62f3618555b8ace2345fd789fe2ba339da0882b28df46c372579eacf0b")) ( 130000, uint256("0x695ca714ab42b13425b59dcc4c861bcb78070a8bfd47250b42cd87fb1b1c9981")) ( 133000, uint256("0x16c8b8b8328c2236f221bdb1310fc73adc17367ec2c175af35ff2577d5a480d3")) ( 179849, uint256("0xffd88e4420b67f8f92fe793e9dd19bba3a929747d491afe923a170d07a98299d")) ( 185000, uint256("0x603af05e5e6964e5c2718658a4dbdc8f22d0826c266a3427468ae7bb7c129158")) ( 195000, uint256("0x2e64ac4387c738935800ea8462c61c28002205040f55c49755d8ed4be5740f0b")) ( 200000, uint256("0x693b6b5dab8cc79269da596598b245577dd0ea8bf0fc6b2cc09db38920012171")) ( 220000, uint256("0x4d5052d3ec3c989237ac66ab16026a13819d515836302beefd6b8d19c2979ed9")) ( 240000, uint256("0x715e10e343468c2383197c7c5ce463cb71c816fa35e6433bfff2f48b72d80142")) ( 260000, uint256("0x5f04c7584f6d93d3cb96a91c71b2003340e3fcb15d5be327ca70506acd8dff9d")) ( 300000, uint256("0x070e8e07c70bb1a3d25edfee44b08aed27291a92d4d6abe1966f16e90e97c5c6")) ( 320000, uint256("0x76e68781f7f6c54c9704b80350bb4059d42cd3af492bb7d848cce64c30af6004")) ( 340000, uint256("0xddc3e4e9ed5d39eaed20cc141148e7996f34dc0f0c8b263306279077d6d756a6")) ( 360000, uint256("0xfc9ed488ca4ef32cd2d04e7d55237087d3d2c8e313447c6883fb31eae8d09be8")) ( 380000, uint256("0x1e4dca66760910b9b14b58c1daf7b012603b9d6208e23ef3af1a5a0900d5aec4")) ( 400000, uint256("0xe6a0ec05a27a40ec3b8c2ddb414df9d5fba64c5761e3599f96c050da389d4a09")) ( 420000, uint256("0x1c8a82a688555e36ba8e376a770d6910dafadf9dff01d2d65fe08174fbe5bbf0")) ( 440000, uint256("0x324170f6f6a3d3fa172121b5d221c7f0602ce603040ceb9af7ebfc3c8f2cfa2c")) ( 460000, uint256("0xe8c5582aad569778ab9d610a501100f987d8bf05345d90b16284211c48b4d159")) ( 480000, uint256("0x03f2e5815706d70d2dd88c25851086ad51173b7677f555b585d9abbdf65677c0")) ( 500000, uint256("0xff93802621e2e90824c73ec6d672406a1beaee9610582cd28613e4abc0c1e855")) ( 520000, uint256("0x8b65b813bf3e3d796cae87c3ceac9a3f129008aa678a557dd7727cb18a6b1625")) ( 540000, uint256("0xc1ef13c7ebd3f946598096671da5df8d145aaab44a78f70702632824ec4ac6cf")) ( 560000, uint256("0xca37279c1255f018dd4e989bcf5edacd098cbac67dc67ef9b8898fae0aa58013")) ( 580000, uint256("0x57eb0935278e79883a5523b2a2a8d72a16430494a0e60b20dea40068a62ed846")) ( 600000, uint256("0xdfc25b486ee340967320ebb8439f6bc238ee3e90781515bc21e1588b50d54eb4")) ( 620000, uint256("0x3125d821fb513aaf682211d9d128b8854bd6aa4aa206fe2a9e317500516f5447")) ( 640000, uint256("0x87d58fc3185cc85c4cdbc49505c66a3e64cc5087e4b6604686f80be16e4a2714")) ( 660000, uint256("0x6ae70c28f3b942d9c0b6ce1d44c98f58e61aa8e4ace0573718cf9faed33438e0")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <commit_msg>Clean Up + add Checkpoints<commit_after>// Copyright (c) 2009-2015 The Bitcoin developers // Copyright (c) 2011-2015 Litecoin Developers // Copyright (c) 2013-2015 Globalcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of //Gensis and Checkpoints ( 0, uint256("0xa28dcb138cef4fa6ea6e1a49fafb352c72c4fffa6674f2bb7e506817e27bdfcc")) ( 2230, uint256("0x71a9d486b349c840ffdf29927414aa903c1443f945b7b2618d807ea8f3e15699")) ( 7000, uint256("0xf8aa8224404caeada717008f6df70db2a2b6d04e44c29ee1fa7abcee7ae2aa5a")) ( 12000, uint256("0x0f44a3b36b9d501f59a4e6b218a1f311b5342de436b134148cd902be7c3b4b05")) ( 85000, uint256("0x18d9c82e34157fb48f7722d1557bb505f7794e3465bbf0dbbde7b22b8dd98ebd")) ( 185000, uint256("0x603af05e5e6964e5c2718658a4dbdc8f22d0826c266a3427468ae7bb7c129158")) ( 240000, uint256("0x715e10e343468c2383197c7c5ce463cb71c816fa35e6433bfff2f48b72d80142")) ( 260000, uint256("0x5f04c7584f6d93d3cb96a91c71b2003340e3fcb15d5be327ca70506acd8dff9d")) ( 380000, uint256("0x1e4dca66760910b9b14b58c1daf7b012603b9d6208e23ef3af1a5a0900d5aec4")) ( 480000, uint256("0x03f2e5815706d70d2dd88c25851086ad51173b7677f555b585d9abbdf65677c0")) ( 500000, uint256("0xff93802621e2e90824c73ec6d672406a1beaee9610582cd28613e4abc0c1e855")) ( 580000, uint256("0x57eb0935278e79883a5523b2a2a8d72a16430494a0e60b20dea40068a62ed846")) ( 600000, uint256("0xdfc25b486ee340967320ebb8439f6bc238ee3e90781515bc21e1588b50d54eb4")) ( 660000, uint256("0x6ae70c28f3b942d9c0b6ce1d44c98f58e61aa8e4ace0573718cf9faed33438e0")) ( 800000, uint256("0xe907d0d8963409581d65507434c90c3ce3719f058a1865282e28fc492e42c3dc")) ( 900000, uint256("0xa5e3ed21f3e14764987f2ac9445c7ab0a601fd56cfe62187ece99e685ebf124e")) ( 1000000, uint256("0xfea5852b22a9f82d9f90b3a1430b43926292b124b7ed5fb10de1353594f8e572")) ( 1193100, uint256("0x124c12e426c1acf0c868fccec009bff2dc84ca91cff77cc599b91505fa4bdccd")) ; bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); if (i == mapCheckpoints.end()) return true; return hash == i->second; } int GetTotalBlocksEstimate() { if (fTestNet) return 0; return mapCheckpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } } <|endoftext|>
<commit_before>#include "Arith256.h" #include "Runtime.h" #include "Type.h" #include <llvm/IR/Function.h> namespace dev { namespace eth { namespace jit { Arith256::Arith256(llvm::IRBuilder<>& _builder) : CompilerHelper(_builder) { using namespace llvm; m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result"); m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1"); m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2"); m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3"); using Linkage = GlobalValue::LinkageTypes; llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr}; llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr}; m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule()); m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule()); m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule()); m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule()); m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule()); m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule()); m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule()); m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule()); } Arith256::~Arith256() {} llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateStore(_arg3, m_arg3); m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mul, _arg1, _arg2); } llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_div, _arg1, _arg2); } llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mod, _arg1, _arg2); } llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_sdiv, _arg1, _arg2); } llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_smod, _arg1, _arg2); } llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_exp, _arg1, _arg2); } llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_addmod, _arg1, _arg2, _arg3); } llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_mulmod, _arg1, _arg2, _arg3); } namespace { using s256 = boost::multiprecision::int256_t; inline s256 u2s(u256 _u) { static const bigint c_end = (bigint)1 << 256; static const u256 c_send = (u256)1 << 255; if (_u < c_send) return (s256)_u; else return (s256)-(c_end - _u); } inline u256 s2u(s256 _u) { static const bigint c_end = (bigint)1 << 256; if (_u >= 0) return (u256)_u; else return (u256)(c_end + _u); } } } } } extern "C" { using namespace dev::eth::jit; EXPORT void arith_mul(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg1 * arg2); } EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 / arg2); } EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2); } EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) / u2s(arg2))); } EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2))); } EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result) { bigint left = llvm2eth(*_arg1); bigint right = llvm2eth(*_arg2); auto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256)); *o_result = eth2llvm(ret); } EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3)); else *o_result = {}; } EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3)); else *o_result = {}; } } <commit_msg>Internal mul256 implementation<commit_after>#include "Arith256.h" #include "Runtime.h" #include "Type.h" #include <llvm/IR/Function.h> namespace dev { namespace eth { namespace jit { Arith256::Arith256(llvm::IRBuilder<>& _builder) : CompilerHelper(_builder) { using namespace llvm; m_result = m_builder.CreateAlloca(Type::Word, nullptr, "arith.result"); m_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg1"); m_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg2"); m_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, "arith.arg3"); using Linkage = GlobalValue::LinkageTypes; llvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr}; llvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr}; m_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mul", getModule()); m_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_div", getModule()); m_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_mod", getModule()); m_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_sdiv", getModule()); m_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_smod", getModule()); m_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, "arith_exp", getModule()); m_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_addmod", getModule()); m_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, "arith_mulmod", getModule()); } Arith256::~Arith256() {} llvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateCall3(_op, m_arg1, m_arg2, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { m_builder.CreateStore(_arg1, m_arg1); m_builder.CreateStore(_arg2, m_arg2); m_builder.CreateStore(_arg3, m_arg3); m_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result); return m_builder.CreateLoad(m_result); } llvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mul, _arg1, _arg2); } llvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_div, _arg1, _arg2); } llvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_mod, _arg1, _arg2); } llvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_sdiv, _arg1, _arg2); } llvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_smod, _arg1, _arg2); } llvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2) { return binaryOp(m_exp, _arg1, _arg2); } llvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_addmod, _arg1, _arg2, _arg3); } llvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3) { return ternaryOp(m_mulmod, _arg1, _arg2, _arg3); } namespace { using s256 = boost::multiprecision::int256_t; inline s256 u2s(u256 _u) { static const bigint c_end = (bigint)1 << 256; static const u256 c_send = (u256)1 << 255; if (_u < c_send) return (s256)_u; else return (s256)-(c_end - _u); } inline u256 s2u(s256 _u) { static const bigint c_end = (bigint)1 << 256; if (_u >= 0) return (u256)_u; else return (u256)(c_end + _u); } using uint128 = __uint128_t; // uint128 add(uint128 a, uint128 b) { return a + b; } // uint128 mul(uint128 a, uint128 b) { return a * b; } // // uint128 mulq(uint64_t x, uint64_t y) // { // return (uint128)x * (uint128)y; // } // // uint128 addc(uint64_t x, uint64_t y) // { // return (uint128)x * (uint128)y; // } struct uint256 { uint64_t lo; uint64_t mid; uint128 hi; }; // uint256 add(uint256 x, uint256 y) // { // auto lo = (uint128) x.lo + y.lo; // auto mid = (uint128) x.mid + y.mid + (lo >> 64); // return {lo, mid, x.hi + y.hi + (mid >> 64)}; // } uint256 mul(uint256 x, uint256 y) { auto t1 = (uint128) x.lo * y.lo; auto t2 = (uint128) x.lo * y.mid; auto t3 = x.lo * y.hi; auto t4 = (uint128) x.mid * y.lo; auto t5 = (uint128) x.mid * y.mid; auto t6 = x.mid * y.hi; auto t7 = x.hi * y.lo; auto t8 = x.hi * y.mid; auto lo = (uint64_t) t1; auto m1 = (t1 >> 64) + (uint64_t) t2; auto m2 = (uint64_t) m1; auto mid = (uint128) m2 + (uint64_t) t4; auto hi = (t2 >> 64) + t3 + (t4 >> 64) + t5 + (t6 << 64) + t7 + (t8 << 64) + (m1 >> 64) + (mid >> 64); return {lo, (uint64_t)mid, hi}; } } } } } extern "C" { using namespace dev::eth::jit; EXPORT void arith_mul(uint256* _arg1, uint256* _arg2, uint256* o_result) { *o_result = mul(*_arg1, *_arg2); } EXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 / arg2); } EXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2); } EXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) / u2s(arg2))); } EXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); *o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2))); } EXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result) { bigint left = llvm2eth(*_arg1); bigint right = llvm2eth(*_arg2); auto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256)); *o_result = eth2llvm(ret); } EXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3)); else *o_result = {}; } EXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result) { auto arg1 = llvm2eth(*_arg1); auto arg2 = llvm2eth(*_arg2); auto arg3 = llvm2eth(*_arg3); if (arg3 != 0) *o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3)); else *o_result = {}; } } <|endoftext|>
<commit_before>#include <search-manager/NumericPropertyTable.h> #include "NumericRangeGroupLabel.h" NS_FACETED_BEGIN NumericRangeGroupLabel::NumericRangeGroupLabel(const NumericPropertyTable *propertyTable, const float &targetValue) : propertyTable_(propertyTable) , targetValue_(targetValue) , test_(&NumericRangeGroupLabel::test1) {} NumericRangeGroupLabel::NumericRangeGroupLabel(const NumericPropertyTable *propertyTable, const int64_t &lowerBound, const int64_t &upperBound) : propertyTable_(propertyTable) , lowerBound_(lowerBound) , upperBound_(upperBound) , test_(&NumericRangeGroupLabel::test2) {} NumericRangeGroupLabel::~NumericRangeGroupLabel() { delete propertyTable_; } bool NumericRangeGroupLabel::test(docid_t doc) const { return (this->*test_)(doc); } bool NumericRangeGroupLabel::test1(docid_t doc) const { float value; propertyTable_->convertPropertyValue(doc, value); return (value == targetValue_); } bool NumericRangeGroupLabel::test2(docid_t doc) const { int64_t value; propertyTable_->convertPropertyValue(doc, value); return (value >= lowerBound_ && value <= upperBound_); } NS_FACETED_END <commit_msg>make NumericRangeGroupLabel::test() more robust by checking conversion result.<commit_after>#include <search-manager/NumericPropertyTable.h> #include "NumericRangeGroupLabel.h" NS_FACETED_BEGIN NumericRangeGroupLabel::NumericRangeGroupLabel(const NumericPropertyTable *propertyTable, const float &targetValue) : propertyTable_(propertyTable) , targetValue_(targetValue) , test_(&NumericRangeGroupLabel::test1) {} NumericRangeGroupLabel::NumericRangeGroupLabel(const NumericPropertyTable *propertyTable, const int64_t &lowerBound, const int64_t &upperBound) : propertyTable_(propertyTable) , lowerBound_(lowerBound) , upperBound_(upperBound) , test_(&NumericRangeGroupLabel::test2) {} NumericRangeGroupLabel::~NumericRangeGroupLabel() { delete propertyTable_; } bool NumericRangeGroupLabel::test(docid_t doc) const { return (this->*test_)(doc); } bool NumericRangeGroupLabel::test1(docid_t doc) const { float value = 0; if (propertyTable_->convertPropertyValue(doc, value)) return (value == targetValue_); return false; } bool NumericRangeGroupLabel::test2(docid_t doc) const { int64_t value = 0; if (propertyTable_->convertPropertyValue(doc, value)) return (value >= lowerBound_ && value <= upperBound_); return false; } NS_FACETED_END <|endoftext|>
<commit_before>#include "dtex2/DrawTexture.h" #include "dtex2/Texture.h" #include "dtex2/typedef.h" #include "dtex2/RenderAPI.h" #include "dtex2/ResCache.h" #include "dtex2/Target.h" namespace dtex { CU_SINGLETON_DEFINITION(DrawTexture); DrawTexture::DrawTexture() : m_curr(nullptr) { } bool DrawTexture::Draw(int src_tex_id, int src_w, int src_h, const Rect& src_r, Texture* dst, const Rect& dst_r, bool rotate) { Bind(dst); if (!RenderAPI::CheckTargetStatus()) { return false; } float vertices[8]; float w_inv = m_curr->GetWidthInv(), h_inv = m_curr->GetHeightInv(); float dst_xmin = dst_r.xmin * w_inv * 2 - 1, dst_xmax = dst_r.xmax * w_inv * 2 - 1, dst_ymin = dst_r.ymin * h_inv * 2 - 1, dst_ymax = dst_r.ymax * h_inv * 2 - 1; vertices[0] = dst_xmin; vertices[1] = dst_ymin; vertices[2] = dst_xmax; vertices[3] = dst_ymin; vertices[4] = dst_xmax; vertices[5] = dst_ymax; vertices[6] = dst_xmin; vertices[7] = dst_ymax; if (rotate) { float x, y; x = vertices[6]; y = vertices[7]; vertices[6] = vertices[4]; vertices[7] = vertices[5]; vertices[4] = vertices[2]; vertices[5] = vertices[3]; vertices[2] = vertices[0]; vertices[3] = vertices[1]; vertices[0] = x; vertices[1] = y; } float texcoords[8]; float src_w_inv = 1.0f / src_w, src_h_inv = 1.0f / src_h; float src_xmin = src_r.xmin * src_w_inv, src_xmax = src_r.xmax * src_w_inv, src_ymin = src_r.ymin * src_h_inv, src_ymax = src_r.ymax * src_h_inv; texcoords[0] = src_xmin; texcoords[1] = src_ymin; texcoords[2] = src_xmax; texcoords[3] = src_ymin; texcoords[4] = src_xmax; texcoords[5] = src_ymax; texcoords[6] = src_xmin; texcoords[7] = src_ymax; RenderAPI::SetProgram(); RenderAPI::Draw(vertices, texcoords, src_tex_id); return true; } void DrawTexture::ClearTex(Texture* tex, float xmin, float ymin, float xmax, float ymax) { Bind(tex); int w = m_curr->GetWidth(), h = m_curr->GetHeight(); RenderAPI::ScissorPush( static_cast<int>(w * xmin), static_cast<int>(h * ymin), static_cast<int>(w * (xmax - xmin)), static_cast<int>(h * (ymax - ymin))); RenderAPI::ClearColor(0, 0, 0, 0); RenderAPI::ScissorPop(); } void DrawTexture::Flush() { if (m_curr) { DrawAfter(m_ctx); m_curr = nullptr; } } void DrawTexture::Clear() { Flush(); m_curr = nullptr; if (m_ctx.target) { ResCache::Instance()->ReturnTarget(m_ctx.target); m_ctx.target = nullptr; } } void DrawTexture::ClearAllTex(Texture* tex) { Target* target = ResCache::Instance()->FetchTarget(); target->Bind(); target->BindTexture(tex->GetID()); RenderAPI::ClearColor(0, 0, 0, 0); target->UnbindTexture(); target->Unbind(); ResCache::Instance()->ReturnTarget(target); } void DrawTexture::DrawBefore(Context& ctx) { RenderAPI::DrawBegin(); RenderAPI::GetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::SetViewport(0, 0, m_curr->GetWidth(), m_curr->GetHeight()); Target* target = ResCache::Instance()->FetchTarget(); target->Bind(); target->BindTexture(m_curr->GetID()); ctx.target = target; } void DrawTexture::DrawAfter(Context& ctx) { ctx.target->UnbindTexture(); ctx.target->Unbind(); ResCache::Instance()->ReturnTarget(ctx.target); ctx.target = nullptr; RenderAPI::SetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::DrawEnd(); } void DrawTexture::Bind(Texture* tex) { if (!tex || m_curr == tex) { return; } if (m_curr) { DrawAfter(m_ctx); } m_curr = tex; DrawBefore(m_ctx); } }<commit_msg>[ADDED] check rt status<commit_after>#include "dtex2/DrawTexture.h" #include "dtex2/Texture.h" #include "dtex2/typedef.h" #include "dtex2/RenderAPI.h" #include "dtex2/ResCache.h" #include "dtex2/Target.h" namespace dtex { CU_SINGLETON_DEFINITION(DrawTexture); DrawTexture::DrawTexture() : m_curr(nullptr) { } bool DrawTexture::Draw(int src_tex_id, int src_w, int src_h, const Rect& src_r, Texture* dst, const Rect& dst_r, bool rotate) { Bind(dst); if (!RenderAPI::CheckTargetStatus()) { return false; } float vertices[8]; float w_inv = m_curr->GetWidthInv(), h_inv = m_curr->GetHeightInv(); float dst_xmin = dst_r.xmin * w_inv * 2 - 1, dst_xmax = dst_r.xmax * w_inv * 2 - 1, dst_ymin = dst_r.ymin * h_inv * 2 - 1, dst_ymax = dst_r.ymax * h_inv * 2 - 1; vertices[0] = dst_xmin; vertices[1] = dst_ymin; vertices[2] = dst_xmax; vertices[3] = dst_ymin; vertices[4] = dst_xmax; vertices[5] = dst_ymax; vertices[6] = dst_xmin; vertices[7] = dst_ymax; if (rotate) { float x, y; x = vertices[6]; y = vertices[7]; vertices[6] = vertices[4]; vertices[7] = vertices[5]; vertices[4] = vertices[2]; vertices[5] = vertices[3]; vertices[2] = vertices[0]; vertices[3] = vertices[1]; vertices[0] = x; vertices[1] = y; } float texcoords[8]; float src_w_inv = 1.0f / src_w, src_h_inv = 1.0f / src_h; float src_xmin = src_r.xmin * src_w_inv, src_xmax = src_r.xmax * src_w_inv, src_ymin = src_r.ymin * src_h_inv, src_ymax = src_r.ymax * src_h_inv; texcoords[0] = src_xmin; texcoords[1] = src_ymin; texcoords[2] = src_xmax; texcoords[3] = src_ymin; texcoords[4] = src_xmax; texcoords[5] = src_ymax; texcoords[6] = src_xmin; texcoords[7] = src_ymax; RenderAPI::SetProgram(); RenderAPI::Draw(vertices, texcoords, src_tex_id); return true; } void DrawTexture::ClearTex(Texture* tex, float xmin, float ymin, float xmax, float ymax) { Bind(tex); if (!RenderAPI::CheckTargetStatus()) { return; } int w = m_curr->GetWidth(), h = m_curr->GetHeight(); RenderAPI::ScissorPush( static_cast<int>(w * xmin), static_cast<int>(h * ymin), static_cast<int>(w * (xmax - xmin)), static_cast<int>(h * (ymax - ymin))); RenderAPI::ClearColor(0, 0, 0, 0); RenderAPI::ScissorPop(); } void DrawTexture::Flush() { if (m_curr) { DrawAfter(m_ctx); m_curr = nullptr; } } void DrawTexture::Clear() { Flush(); m_curr = nullptr; if (m_ctx.target) { ResCache::Instance()->ReturnTarget(m_ctx.target); m_ctx.target = nullptr; } } void DrawTexture::ClearAllTex(Texture* tex) { Target* target = ResCache::Instance()->FetchTarget(); target->Bind(); target->BindTexture(tex->GetID()); if (RenderAPI::CheckTargetStatus() != 0) { RenderAPI::ClearColor(0, 0, 0, 0); } target->UnbindTexture(); target->Unbind(); ResCache::Instance()->ReturnTarget(target); } void DrawTexture::DrawBefore(Context& ctx) { RenderAPI::DrawBegin(); RenderAPI::GetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::SetViewport(0, 0, m_curr->GetWidth(), m_curr->GetHeight()); Target* target = ResCache::Instance()->FetchTarget(); target->Bind(); target->BindTexture(m_curr->GetID()); ctx.target = target; } void DrawTexture::DrawAfter(Context& ctx) { ctx.target->UnbindTexture(); ctx.target->Unbind(); ResCache::Instance()->ReturnTarget(ctx.target); ctx.target = nullptr; RenderAPI::SetViewport(ctx.vx, ctx.vy, ctx.vw, ctx.vh); RenderAPI::DrawEnd(); } void DrawTexture::Bind(Texture* tex) { if (!tex || m_curr == tex) { return; } if (m_curr) { DrawAfter(m_ctx); } m_curr = tex; DrawBefore(m_ctx); } }<|endoftext|>
<commit_before>#ifndef DUNE_STUFF_CONFIGCONTAINER_HH_INCLUDED #define DUNE_STUFF_CONFIGCONTAINER_HH_INCLUDED #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #include <dune/common/deprecated.hh> #include <dune/common/parametertree.hh> #include <dune/common/parametertreeparser.hh> #include <dune/common/exceptions.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/filesystem.hh> #include <dune/stuff/common/misc.hh> #include <dune/stuff/common/parameter/validation.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/type_utils.hh> #include <boost/format.hpp> #include <set> #define DSC_ORDER_REL_GENERIC(var,a,b) \ if (a.var < b.var) { \ return true;} \ if (a.var > b.var) { \ return false; } #define DSC_ORDER_REL(var) DSC_ORDER_REL_GENERIC(var,(*this),other) namespace Dune { namespace Stuff { namespace Common { //! use this to record defaults, placements and so forth struct Request { const int line; const std::string file; const std::string key; const std::string def; const std::string validator; Request(const int _line, const std::string _file, const std::string _key, const std::string _def, const std::string _validator) : line(_line) , file(_file) , key(_key) , def(_def) , validator(_validator) {} //! requests are considered bool operator < (const Request& other) const { DSC_ORDER_REL(key) DSC_ORDER_REL(def) DSC_ORDER_REL(file) DSC_ORDER_REL(line) return validator < other.validator; } }; bool strictRequestCompare(const Request& a, const Request& b) { DSC_ORDER_REL_GENERIC(key,a,b); return a.def < b.def; } std::ostream& operator <<(std::ostream& out, const Request& r) { boost::format out_f("Request for %s with default %s in %s:%d (validation: %s)"); out_f % r.key % r.def % r.file % r.line % r.validator; out << out_f.str(); return out; } class ConfigContainer { private: typedef std::map<std::string, std::set<Request> > RequestMapType; template< typename T, class Validator > T getValidValue(std::string name, T def, const ValidatorInterface< T, Validator >& validator) { T val = tree_.get(name, def); if( validator(val) ) return val; std::stringstream ss; validator.print(ss); DUNE_THROW(Dune::ParameterInvalid, ss.str()); } //! return a set of Request objects for keys that have been queried with non-matching default values std::set<Request> getMismatchedDefaults(RequestMapType::value_type pair) const { typedef bool (*func)(const Request&,const Request&); std::set<Request,func> mismatched(&strictRequestCompare); mismatched.insert(pair.second.begin(), pair.second.end()); return std::set<Request>(std::begin(mismatched), std::end(mismatched)); } //! all public get signatures call this one template< typename T, class Validator > T get(std::string name, T def, const ValidatorInterface< T, Validator >& validator, bool UNUSED_UNLESS_DEBUG(useDbgStream), const Request& request) { requests_map_[name].insert(request); #ifndef NDEBUG if ( warning_output_ && !tree_.hasKey(name) ) { if (useDbgStream) Logger().debug() << "WARNING: using default value for parameter \"" << name << "\"" << std::endl; else std::cerr << "WARNING: using default value for parameter \"" << name << "\"" << std::endl; } #endif // ifndef NDEBUG if ( record_defaults_ && !tree_.hasKey(name) ) set(name, def); return getValidValue(name, def, validator); } // getParam public: ConfigContainer(const Dune::ParameterTree& tree) : warning_output_(false) , tree_(tree) , record_defaults_(false) {} ConfigContainer() : warning_output_(true) , record_defaults_(false) {} ~ConfigContainer() { boost::filesystem::path logdir(get("global.datadir", "data", false)); logdir /= get("logging.dir", "log", false); boost::filesystem::ofstream out(logdir / "paramter.log"); tree_.report(out); } void readCommandLine(int argc, char* argv[]) { if (argc < 2) { boost::format usage("usage: %s parameter.file *[-section.key override-value]"); DUNE_THROW(Dune::Exception, (usage % argv[0]).str()); } Dune::ParameterTreeParser::readINITree(argv[1],tree_); Dune::ParameterTreeParser::readOptions(argc, argv, tree_); } // ReadCommandLine /** \brief passthrough to underlying Dune::ParameterTree * \param useDbgStream * needs to be set to false when using this function in Logging::Create, * otherwise an assertion will fire cause streams aren't available yet **/ template< typename T > T get(std::string name, T def, bool useDbgStream = true) { return get(name, def, ValidateAny< T >(), useDbgStream); } //! get variation with request recording template< typename T > T get(std::string name, T def, Request req, bool useDbgStream = true) { return get(name, def, ValidateAny< T >(), useDbgStream, req); } template< typename T, class Validator > T get(std::string name, T def, const ValidatorInterface< T, Validator >& validator, Request req, bool useDbgStream = true) { return get(name, def, validator, useDbgStream, req); } //! hack around the "CHARS" is no string issue std::string get(std::string name, const char* def, bool useDbgStream = true) { return get(name, std::string(def), ValidateAny< std::string >(), useDbgStream); } template< typename T, class Validator > T get(std::string name, T def, const ValidatorInterface< T, Validator >& validator, bool useDbgStream = true) { Request req(-1, std::string(), name, Dune::Stuff::Common::toString(def), Dune::Stuff::Common::getTypename(validator)); return get(name, def, validator, useDbgStream, req); } //! hack around the "CHARS" is no string issue again template< class Validator > std::string get(std::string name, const char* def, const ValidatorInterface< std::string, Validator >& validator, bool useDbgStream = true) { return get<std::string,Validator>(name, def, validator, useDbgStream); } //! get variation with request recording std::string get(std::string name, const char* def, Request req, bool useDbgStream = true) { return get(name, std::string(def), ValidateAny< std::string >(), useDbgStream, req); } template<class T> void set(const std::string key, const T value) { tree_[key] = toString(value); } void printRequests(std::ostream& out) const { out << "Config requests:"; for( const auto& pair : requests_map_ ) { out << "Key: " << pair.first; for( const auto& req : pair.second ) { out << "\n\t" << req; } out << std::endl; } } RequestMapType getMismatchedDefaultsMap() const { RequestMapType ret; for( const auto& pair : requests_map_ ) { auto mismatches = getMismatchedDefaults(pair); if(mismatches.size()) ret[pair.first] = mismatches; } return ret; } void printMismatchedDefaults(std::ostream& out) const { for( const auto& pair : requests_map_ ) { out << "Mismatched uses for key " << pair.first << ":"; for( const auto& req : getMismatchedDefaults(pair) ) { out << "\n\t" << req; } out << "\n"; } } /** * Control if the value map is filled with default values for missing entries * Initially false **/ void setRecordDefaults(bool record) { record_defaults_ = record; } private: bool warning_output_; ExtendedParameterTree tree_; //! config key -> requests map RequestMapType requests_map_; bool record_defaults_; }; //! global ConfigContainer instance ConfigContainer& Config() { static ConfigContainer parameters; return parameters; } } // namespace Common } // namespace Stuff } // namespace Dune #define DSC_CONFIG Dune::Stuff::Common::Config() #define DSC_CONFIG_GET(key,def) \ DSC_CONFIG.get(key,def,Dune::Stuff::Common::Request(__LINE__, __FILE__,key,Dune::Stuff::Common::toString(def), "none")) #define DSC_CONFIG_GETV(key,def,validator) \ DSC_CONFIG.get(key,def, validator, Dune::Stuff::Common::Request(__LINE__, __FILE__,key,Dune::Stuff::Common::toString(def), #validator )) #define DSC_CONFIG_GETB(key,def,use_logger) \ DSC_CONFIG.get(key,def,Dune::Stuff::Common::Request(__LINE__, __FILE__,key,Dune::Stuff::Common::toString(def), "none" ), use_logger) #endif // DUNE_STUFF_CONFIGCONTAINER_HH_INCLUDED /** Copyright (c) 2012, Rene Milk * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ <commit_msg>[common.parameter.configcontianer] fixed wrond exception<commit_after>#ifndef DUNE_STUFF_CONFIGCONTAINER_HH_INCLUDED #define DUNE_STUFF_CONFIGCONTAINER_HH_INCLUDED #ifdef HAVE_CMAKE_CONFIG #include "cmake_config.h" #elif defined (HAVE_CONFIG_H) #include <config.h> #endif // ifdef HAVE_CMAKE_CONFIG #include <dune/common/deprecated.hh> #include <dune/common/parametertree.hh> #include <dune/common/parametertreeparser.hh> #include <dune/common/exceptions.hh> #include <dune/stuff/common/logging.hh> #include <dune/stuff/common/filesystem.hh> #include <dune/stuff/common/misc.hh> #include <dune/stuff/common/parameter/validation.hh> #include <dune/stuff/common/parameter/tree.hh> #include <dune/stuff/common/type_utils.hh> #include <boost/format.hpp> #include <set> #define DSC_ORDER_REL_GENERIC(var,a,b) \ if (a.var < b.var) { \ return true;} \ if (a.var > b.var) { \ return false; } #define DSC_ORDER_REL(var) DSC_ORDER_REL_GENERIC(var,(*this),other) namespace Dune { namespace Stuff { namespace Common { //! use this to record defaults, placements and so forth struct Request { const int line; const std::string file; const std::string key; const std::string def; const std::string validator; Request(const int _line, const std::string _file, const std::string _key, const std::string _def, const std::string _validator) : line(_line) , file(_file) , key(_key) , def(_def) , validator(_validator) {} //! requests are considered bool operator < (const Request& other) const { DSC_ORDER_REL(key) DSC_ORDER_REL(def) DSC_ORDER_REL(file) DSC_ORDER_REL(line) return validator < other.validator; } }; bool strictRequestCompare(const Request& a, const Request& b) { DSC_ORDER_REL_GENERIC(key,a,b); return a.def < b.def; } std::ostream& operator <<(std::ostream& out, const Request& r) { boost::format out_f("Request for %s with default %s in %s:%d (validation: %s)"); out_f % r.key % r.def % r.file % r.line % r.validator; out << out_f.str(); return out; } class InvalidParameter : public Dune::Exception {}; class ConfigContainer { private: typedef std::map<std::string, std::set<Request> > RequestMapType; template< typename T, class Validator > T getValidValue(std::string name, T def, const ValidatorInterface< T, Validator >& validator) { T val = tree_.get(name, def); if( validator(val) ) return val; std::stringstream ss; validator.print(ss); DUNE_THROW(InvalidParameter, ss.str()); } //! return a set of Request objects for keys that have been queried with non-matching default values std::set<Request> getMismatchedDefaults(RequestMapType::value_type pair) const { typedef bool (*func)(const Request&,const Request&); std::set<Request,func> mismatched(&strictRequestCompare); mismatched.insert(pair.second.begin(), pair.second.end()); return std::set<Request>(std::begin(mismatched), std::end(mismatched)); } //! all public get signatures call this one template< typename T, class Validator > T get(std::string name, T def, const ValidatorInterface< T, Validator >& validator, bool UNUSED_UNLESS_DEBUG(useDbgStream), const Request& request) { requests_map_[name].insert(request); #ifndef NDEBUG if ( warning_output_ && !tree_.hasKey(name) ) { if (useDbgStream) Logger().debug() << "WARNING: using default value for parameter \"" << name << "\"" << std::endl; else std::cerr << "WARNING: using default value for parameter \"" << name << "\"" << std::endl; } #endif // ifndef NDEBUG if ( record_defaults_ && !tree_.hasKey(name) ) set(name, def); return getValidValue(name, def, validator); } // getParam public: ConfigContainer(const Dune::ParameterTree& tree) : warning_output_(false) , tree_(tree) , record_defaults_(false) {} ConfigContainer() : warning_output_(true) , record_defaults_(false) {} ~ConfigContainer() { boost::filesystem::path logdir(get("global.datadir", "data", false)); logdir /= get("logging.dir", "log", false); boost::filesystem::ofstream out(logdir / "paramter.log"); tree_.report(out); } void readCommandLine(int argc, char* argv[]) { if (argc < 2) { boost::format usage("usage: %s parameter.file *[-section.key override-value]"); DUNE_THROW(Dune::Exception, (usage % argv[0]).str()); } Dune::ParameterTreeParser::readINITree(argv[1],tree_); Dune::ParameterTreeParser::readOptions(argc, argv, tree_); } // ReadCommandLine /** \brief passthrough to underlying Dune::ParameterTree * \param useDbgStream * needs to be set to false when using this function in Logging::Create, * otherwise an assertion will fire cause streams aren't available yet **/ template< typename T > T get(std::string name, T def, bool useDbgStream = true) { return get(name, def, ValidateAny< T >(), useDbgStream); } //! get variation with request recording template< typename T > T get(std::string name, T def, Request req, bool useDbgStream = true) { return get(name, def, ValidateAny< T >(), useDbgStream, req); } template< typename T, class Validator > T get(std::string name, T def, const ValidatorInterface< T, Validator >& validator, Request req, bool useDbgStream = true) { return get(name, def, validator, useDbgStream, req); } //! hack around the "CHARS" is no string issue std::string get(std::string name, const char* def, bool useDbgStream = true) { return get(name, std::string(def), ValidateAny< std::string >(), useDbgStream); } template< typename T, class Validator > T get(std::string name, T def, const ValidatorInterface< T, Validator >& validator, bool useDbgStream = true) { Request req(-1, std::string(), name, Dune::Stuff::Common::toString(def), Dune::Stuff::Common::getTypename(validator)); return get(name, def, validator, useDbgStream, req); } //! hack around the "CHARS" is no string issue again template< class Validator > std::string get(std::string name, const char* def, const ValidatorInterface< std::string, Validator >& validator, bool useDbgStream = true) { return get<std::string,Validator>(name, def, validator, useDbgStream); } //! get variation with request recording std::string get(std::string name, const char* def, Request req, bool useDbgStream = true) { return get(name, std::string(def), ValidateAny< std::string >(), useDbgStream, req); } template<class T> void set(const std::string key, const T value) { tree_[key] = toString(value); } void printRequests(std::ostream& out) const { out << "Config requests:"; for( const auto& pair : requests_map_ ) { out << "Key: " << pair.first; for( const auto& req : pair.second ) { out << "\n\t" << req; } out << std::endl; } } RequestMapType getMismatchedDefaultsMap() const { RequestMapType ret; for( const auto& pair : requests_map_ ) { auto mismatches = getMismatchedDefaults(pair); if(mismatches.size()) ret[pair.first] = mismatches; } return ret; } void printMismatchedDefaults(std::ostream& out) const { for( const auto& pair : requests_map_ ) { out << "Mismatched uses for key " << pair.first << ":"; for( const auto& req : getMismatchedDefaults(pair) ) { out << "\n\t" << req; } out << "\n"; } } /** * Control if the value map is filled with default values for missing entries * Initially false **/ void setRecordDefaults(bool record) { record_defaults_ = record; } private: bool warning_output_; ExtendedParameterTree tree_; //! config key -> requests map RequestMapType requests_map_; bool record_defaults_; }; //! global ConfigContainer instance ConfigContainer& Config() { static ConfigContainer parameters; return parameters; } } // namespace Common } // namespace Stuff } // namespace Dune #define DSC_CONFIG Dune::Stuff::Common::Config() #define DSC_CONFIG_GET(key,def) \ DSC_CONFIG.get(key,def,Dune::Stuff::Common::Request(__LINE__, __FILE__,key,Dune::Stuff::Common::toString(def), "none")) #define DSC_CONFIG_GETV(key,def,validator) \ DSC_CONFIG.get(key,def, validator, Dune::Stuff::Common::Request(__LINE__, __FILE__,key,Dune::Stuff::Common::toString(def), #validator )) #define DSC_CONFIG_GETB(key,def,use_logger) \ DSC_CONFIG.get(key,def,Dune::Stuff::Common::Request(__LINE__, __FILE__,key,Dune::Stuff::Common::toString(def), "none" ), use_logger) #endif // DUNE_STUFF_CONFIGCONTAINER_HH_INCLUDED /** Copyright (c) 2012, Rene Milk * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/ <|endoftext|>
<commit_before>#include "CommonCMPT.h" #include "ArrangeSpriteOP.h" #include "view/StagePanel.h" #include "view/KeysPanel.h" #include "frame/FileIO.h" #include "frame/Controller.h" #include "dataset/Layer.h" #include "dataset/KeyFrame.h" namespace eanim { CommonCMPT::CommonCMPT(wxWindow* parent, const wxString& name, StagePanel* stage, d2d::PropertySettingPanel* property, bool vertical, Controller* ctrl) : d2d::AbstractEditCMPT(parent, name, stage) , m_vertical(vertical) , m_ctrl(ctrl) { m_editOP = new ArrangeSpriteOP(stage, property, ctrl); } wxSizer* CommonCMPT::initLayout() { return initEditPanel(); } wxSizer* CommonCMPT::initEditPanel() { int orient = m_vertical ? wxVERTICAL : wxHORIZONTAL; wxBoxSizer* sizer = new wxBoxSizer(orient); sizer->AddSpacer(10); sizer->Add(initLoadPanel()); sizer->AddSpacer(20); sizer->Add(initFillingPanel()); sizer->AddSpacer(10); sizer->Add(initSettingsPanel()); return sizer; } wxSizer* CommonCMPT::initLoadPanel() { wxSizer* sizer = new wxBoxSizer(wxVERTICAL); // folder { wxButton* btnLoad = new wxButton(this, wxID_ANY, wxT("Load Folder")); Connect(btnLoad->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onLoadFromFolder)); sizer->Add(btnLoad); } sizer->AddSpacer(10); // all image { wxButton* btnLoad = new wxButton(this, wxID_ANY, wxT("Load List")); Connect(btnLoad->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onLoadFromList)); sizer->Add(btnLoad); } return sizer; } wxSizer* CommonCMPT::initFillingPanel() { wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Filling")); int orient = m_vertical ? wxVERTICAL : wxHORIZONTAL; wxSizer* sizer = new wxStaticBoxSizer(bounding, orient); { wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add(new wxStaticText(this, wxID_ANY, wxT("tot frames: "))); m_filling = new wxSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(70, -1), wxSP_ARROW_KEYS, 10, 1000, 0); sizer->Add(m_filling); sizer->Add(sizer); } { wxButton* btnFill = new wxButton(this, wxID_ANY, wxT("Filling")); Connect(btnFill->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onFillingFrames)); sizer->Add(btnFill); } return sizer; } wxSizer* CommonCMPT::initSettingsPanel() { wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("")); int orient = m_vertical ? wxVERTICAL : wxHORIZONTAL; wxSizer* sizer = new wxStaticBoxSizer(bounding, orient); wxButton* btnAdd = new wxButton(this, wxID_ANY, "+", wxDefaultPosition, wxSize(25, 25)); sizer->Add(btnAdd, 0, wxLEFT | wxRIGHT, 5); Connect(btnAdd->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onAddCross)); wxButton* btnDel = new wxButton(this, wxID_ANY, "-", wxDefaultPosition, wxSize(25, 25)); sizer->Add(btnDel, 0, wxLEFT | wxRIGHT, 5); Connect(btnDel->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onDelCross)); return sizer; } void CommonCMPT::onLoadFromFolder(wxCommandEvent& event) { ArrangeSpriteOP* op = static_cast<ArrangeSpriteOP*>(m_editOP); op->setMouseMoveFocus(false); wxDirDialog dlg(NULL, "Images", wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dlg.ShowModal() != wxID_OK) return; clear(); op->setMouseMoveFocus(true); wxArrayString files; d2d::FilenameTools::fetchAllFiles(dlg.GetPath().ToStdString(), files); std::map<int, std::vector<wxString> > mapFrameSymbols; for (size_t i = 0, n = files.size(); i < n; ++i) { wxString filepath = files[i]; if (!d2d::FileNameParser::isType(filepath, d2d::FileNameParser::e_image)) continue; wxString name = d2d::FilenameTools::getFilename(filepath); size_t mid = name.find('_'); if (mid == wxString::npos) continue; wxString sitem = name.substr(0, mid); wxString sframe = name.substr(mid+1); long item, frame; sitem.ToLong(&item); sframe.ToLong(&frame); std::map<int, std::vector<wxString> >::iterator itr = mapFrameSymbols.find(frame); if (itr == mapFrameSymbols.end()) { std::vector<wxString> items; items.push_back(filepath); mapFrameSymbols.insert(std::make_pair(frame, items)); } else { itr->second.push_back(filepath); } } m_ctrl->ClearLayers(); Layer* layer = new Layer(m_ctrl); std::map<int, std::vector<wxString> >::iterator itr = mapFrameSymbols.begin(); for ( ; itr != mapFrameSymbols.end(); ++itr) { KeyFrame* frame = new KeyFrame(m_ctrl, itr->first); for (int i = 0, n = itr->second.size(); i < n; ++i) { d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(itr->second[i]); // symbol->refresh(); d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol); frame->Insert(sprite); sprite->Release(); symbol->Release(); } layer->InsertKeyFrame(frame); frame->Release(); } m_ctrl->InsertLayer(layer); m_ctrl->setCurrFrame(0, 1); m_ctrl->GetLibraryPanel()->loadFromSymbolMgr(*d2d::SymbolMgr::Instance()); m_ctrl->Refresh(); m_ctrl->GetStagePanel()->getCanvas()->resetViewport(); } void CommonCMPT::onLoadFromList(wxCommandEvent& event) { std::vector<d2d::ISymbol*> symbols; m_ctrl->GetImagePage()->getList()-> traverse(d2d::FetchAllVisitor<d2d::ISymbol>(symbols)); if (!symbols.empty()) { m_ctrl->ClearLayers(); } else { return; } Layer* layer = new Layer(m_ctrl); for (size_t i = 0, n = symbols.size(); i < n; ++i) { KeyFrame* frame = new KeyFrame(m_ctrl, i+1); d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbols[i]); frame->Insert(sprite); layer->InsertKeyFrame(frame); sprite->Release(); frame->Release(); } m_ctrl->InsertLayer(layer); m_ctrl->Refresh(); } void CommonCMPT::onFillingFrames(wxCommandEvent& event) { int tot = m_filling->GetValue(); LayersMgr& layers = m_ctrl->GetLayers(); for (size_t i = 0, n = layers.size(); i < n; ++i) { Layer* layer = layers.getLayer(i); const std::map<int, KeyFrame*>& frames = layer->getAllFrames(); std::vector<KeyFrame*> fixed; fixed.reserve(frames.size()); int dis = tot / frames.size(); std::map<int, KeyFrame*>::const_iterator itr = frames.begin(); for (size_t i = 0; itr != frames.end(); ++itr, ++i) { itr->second->setTime(1+dis*i); itr->second->Retain(); fixed.push_back(itr->second); } layer->Clear(); for (size_t i = 0, n = fixed.size(); i < n; ++i) { layer->InsertKeyFrame(fixed[i]); fixed[i]->Release(); } } m_ctrl->Refresh(); } void CommonCMPT::onChangeAnim(wxCommandEvent& event) { m_ctrl->GetResource().choice = event.GetInt(); FileIO::reload(m_ctrl); } void CommonCMPT::onAddCross(wxCommandEvent& event) { static_cast<ArrangeSpriteOP*>(m_editOP)->addCross(); } void CommonCMPT::onDelCross(wxCommandEvent& event) { static_cast<ArrangeSpriteOP*>(m_editOP)->delCross(); } void CommonCMPT::clear() { m_ctrl->Clear(); } }<commit_msg>[FIXED] anim的filling按钮<commit_after>#include "CommonCMPT.h" #include "ArrangeSpriteOP.h" #include "view/StagePanel.h" #include "view/KeysPanel.h" #include "frame/FileIO.h" #include "frame/Controller.h" #include "dataset/Layer.h" #include "dataset/KeyFrame.h" namespace eanim { CommonCMPT::CommonCMPT(wxWindow* parent, const wxString& name, StagePanel* stage, d2d::PropertySettingPanel* property, bool vertical, Controller* ctrl) : d2d::AbstractEditCMPT(parent, name, stage) , m_vertical(vertical) , m_ctrl(ctrl) { m_editOP = new ArrangeSpriteOP(stage, property, ctrl); } wxSizer* CommonCMPT::initLayout() { return initEditPanel(); } wxSizer* CommonCMPT::initEditPanel() { int orient = m_vertical ? wxVERTICAL : wxHORIZONTAL; wxBoxSizer* sizer = new wxBoxSizer(orient); sizer->AddSpacer(10); sizer->Add(initLoadPanel()); sizer->AddSpacer(20); sizer->Add(initFillingPanel()); sizer->AddSpacer(10); sizer->Add(initSettingsPanel()); return sizer; } wxSizer* CommonCMPT::initLoadPanel() { wxSizer* sizer = new wxBoxSizer(wxVERTICAL); // folder { wxButton* btnLoad = new wxButton(this, wxID_ANY, wxT("Load Folder")); Connect(btnLoad->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onLoadFromFolder)); sizer->Add(btnLoad); } sizer->AddSpacer(10); // all image { wxButton* btnLoad = new wxButton(this, wxID_ANY, wxT("Load List")); Connect(btnLoad->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onLoadFromList)); sizer->Add(btnLoad); } return sizer; } wxSizer* CommonCMPT::initFillingPanel() { wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("Filling")); int orient = m_vertical ? wxVERTICAL : wxHORIZONTAL; wxSizer* filling_sizer = new wxStaticBoxSizer(bounding, orient); { wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add(new wxStaticText(this, wxID_ANY, wxT("tot frames: "))); m_filling = new wxSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(70, -1), wxSP_ARROW_KEYS, 10, 1000, 0); sizer->Add(m_filling); filling_sizer->Add(sizer); } filling_sizer->AddSpacer(5); { wxButton* btn = new wxButton(this, wxID_ANY, wxT("Filling")); Connect(btn->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onFillingFrames)); filling_sizer->Add(btn); } return filling_sizer; } wxSizer* CommonCMPT::initSettingsPanel() { wxStaticBox* bounding = new wxStaticBox(this, wxID_ANY, wxT("")); int orient = m_vertical ? wxVERTICAL : wxHORIZONTAL; wxSizer* sizer = new wxStaticBoxSizer(bounding, orient); wxButton* btnAdd = new wxButton(this, wxID_ANY, "+", wxDefaultPosition, wxSize(25, 25)); sizer->Add(btnAdd, 0, wxLEFT | wxRIGHT, 5); Connect(btnAdd->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onAddCross)); wxButton* btnDel = new wxButton(this, wxID_ANY, "-", wxDefaultPosition, wxSize(25, 25)); sizer->Add(btnDel, 0, wxLEFT | wxRIGHT, 5); Connect(btnDel->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(CommonCMPT::onDelCross)); return sizer; } void CommonCMPT::onLoadFromFolder(wxCommandEvent& event) { ArrangeSpriteOP* op = static_cast<ArrangeSpriteOP*>(m_editOP); op->setMouseMoveFocus(false); wxDirDialog dlg(NULL, "Images", wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dlg.ShowModal() != wxID_OK) return; clear(); op->setMouseMoveFocus(true); wxArrayString files; d2d::FilenameTools::fetchAllFiles(dlg.GetPath().ToStdString(), files); std::map<int, std::vector<wxString> > mapFrameSymbols; for (size_t i = 0, n = files.size(); i < n; ++i) { wxString filepath = files[i]; if (!d2d::FileNameParser::isType(filepath, d2d::FileNameParser::e_image)) continue; wxString name = d2d::FilenameTools::getFilename(filepath); size_t mid = name.find('_'); if (mid == wxString::npos) continue; wxString sitem = name.substr(0, mid); wxString sframe = name.substr(mid+1); long item, frame; sitem.ToLong(&item); sframe.ToLong(&frame); std::map<int, std::vector<wxString> >::iterator itr = mapFrameSymbols.find(frame); if (itr == mapFrameSymbols.end()) { std::vector<wxString> items; items.push_back(filepath); mapFrameSymbols.insert(std::make_pair(frame, items)); } else { itr->second.push_back(filepath); } } m_ctrl->ClearLayers(); Layer* layer = new Layer(m_ctrl); std::map<int, std::vector<wxString> >::iterator itr = mapFrameSymbols.begin(); for ( ; itr != mapFrameSymbols.end(); ++itr) { KeyFrame* frame = new KeyFrame(m_ctrl, itr->first); for (int i = 0, n = itr->second.size(); i < n; ++i) { d2d::ISymbol* symbol = d2d::SymbolMgr::Instance()->fetchSymbol(itr->second[i]); // symbol->refresh(); d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbol); frame->Insert(sprite); sprite->Release(); symbol->Release(); } layer->InsertKeyFrame(frame); frame->Release(); } m_ctrl->InsertLayer(layer); m_ctrl->setCurrFrame(0, 1); m_ctrl->GetLibraryPanel()->loadFromSymbolMgr(*d2d::SymbolMgr::Instance()); m_ctrl->Refresh(); m_ctrl->GetStagePanel()->getCanvas()->resetViewport(); } void CommonCMPT::onLoadFromList(wxCommandEvent& event) { std::vector<d2d::ISymbol*> symbols; m_ctrl->GetImagePage()->getList()-> traverse(d2d::FetchAllVisitor<d2d::ISymbol>(symbols)); if (!symbols.empty()) { m_ctrl->ClearLayers(); } else { return; } Layer* layer = new Layer(m_ctrl); for (size_t i = 0, n = symbols.size(); i < n; ++i) { KeyFrame* frame = new KeyFrame(m_ctrl, i+1); d2d::ISprite* sprite = d2d::SpriteFactory::Instance()->create(symbols[i]); frame->Insert(sprite); layer->InsertKeyFrame(frame); sprite->Release(); frame->Release(); } m_ctrl->InsertLayer(layer); m_ctrl->Refresh(); } void CommonCMPT::onFillingFrames(wxCommandEvent& event) { int tot = m_filling->GetValue(); LayersMgr& layers = m_ctrl->GetLayers(); for (size_t i = 0, n = layers.size(); i < n; ++i) { Layer* layer = layers.getLayer(i); const std::map<int, KeyFrame*>& frames = layer->getAllFrames(); std::vector<KeyFrame*> fixed; fixed.reserve(frames.size()); int dis = tot / frames.size(); std::map<int, KeyFrame*>::const_iterator itr = frames.begin(); for (size_t i = 0; itr != frames.end(); ++itr, ++i) { itr->second->setTime(1+dis*i); itr->second->Retain(); fixed.push_back(itr->second); } layer->Clear(); for (size_t i = 0, n = fixed.size(); i < n; ++i) { layer->InsertKeyFrame(fixed[i]); fixed[i]->Release(); } } m_ctrl->Refresh(); } void CommonCMPT::onChangeAnim(wxCommandEvent& event) { m_ctrl->GetResource().choice = event.GetInt(); FileIO::reload(m_ctrl); } void CommonCMPT::onAddCross(wxCommandEvent& event) { static_cast<ArrangeSpriteOP*>(m_editOP)->addCross(); } void CommonCMPT::onDelCross(wxCommandEvent& event) { static_cast<ArrangeSpriteOP*>(m_editOP)->delCross(); } void CommonCMPT::clear() { m_ctrl->Clear(); } }<|endoftext|>
<commit_before>// $Id: PTE_test.C,v 1.2 2000/05/29 23:47:03 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/KERNEL/PTE.h> /////////////////////////// START_TEST(Element, "$Id: PTE_test.C,v 1.2 2000/05/29 23:47:03 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; Element* e; CHECK(Element()) e = new Element; TEST_NOT_EQUAL(e, 0) RESULT CHECK(~Element()) delete e; RESULT CHECK(Element(Element&, bool)) Element* e1 = new Element; e1->setName("testname"); Element* e2 = new Element(*e1, true); TEST_NOT_EQUAL(e2, 0) if (e2 != 0) { TEST_EQUAL(e2->getName(), "testname") delete e2; } RESULT CHECK(Element(const String& name, const String& symbol, Group group, Period period, AtomicNumber atomic_umber, float atomic_weight, float atomic_radius, float covalent_radius, float van_der_waals_radius, float electronegativity)) Element* e1 = new Element("e1", "id", 2, 3, 25, 25.0, 2.0, 3.0, 4.0, 5.0); TEST_NOT_EQUAL(e1, 0) if (e1 != 0) { TEST_EQUAL(e1->getName(), "e1") TEST_EQUAL(e1->getSymbol(), "id") TEST_EQUAL(e1->getGroup(), 2) TEST_EQUAL(e1->getPeriod(), 3) TEST_EQUAL(e1->getAtomicNumber(), 25) TEST_EQUAL(e1->getAtomicWeight(), 25.0) TEST_EQUAL(e1->getAtomicRadius(), 2.0) TEST_EQUAL(e1->getCovalentRadius(), 3.0) TEST_EQUAL(e1->getVanDerWaalsRadius(), 4.0) TEST_EQUAL(e1->getElectronegativity(), 5.0) delete e1; } Element* e2 = new Element(*e1); TEST_NOT_EQUAL(e2, 0) if (e2 != 0) { TEST_EQUAL(e2->getName(), "e1") TEST_EQUAL(e2->getSymbol(), "id") TEST_EQUAL(e2->getGroup(), 2) TEST_EQUAL(e2->getPeriod(), 3) TEST_EQUAL(e2->getAtomicNumber(), 25) TEST_EQUAL(e2->getAtomicWeight(), 25.0) TEST_EQUAL(e2->getAtomicRadius(), 2.0) TEST_EQUAL(e2->getCovalentRadius(), 3.0) TEST_EQUAL(e2->getVanDerWaalsRadius(), 4.0) TEST_EQUAL(e2->getElectronegativity(), 5.0) delete e2; } RESULT Element e1; Element e2; Element e3; CHECK(setName(const String& name)) e1.setName("e1"); RESULT CHECK(getName()) TEST_EQUAL(e1.getName(), "e1") TEST_EQUAL(e2.getName(), "Unknown") RESULT CHECK(setSymbol(const String& symbol)) e1.setSymbol("s"); RESULT CHECK(getSymbol()) TEST_EQUAL(e1.getSymbol(), "s") TEST_EQUAL(e2.getSymbol(), "?") RESULT CHECK(setGroup(Group group)) e1.setGroup(2); RESULT CHECK(getGroup()) TEST_EQUAL(e1.getGroup(), 2) TEST_EQUAL(e2.getGroup(), 0) RESULT CHECK(setPeriod(Period Period)) e1.setPeriod(3); RESULT CHECK(getPeriod()) TEST_EQUAL(e1.getPeriod(), 3) TEST_EQUAL(e2.getPeriod(), 0) RESULT CHECK(setAtomicNumber(AtomicNumber AtomicNumber)) e1.setAtomicNumber(4); RESULT CHECK(getAtomicNumber()) TEST_EQUAL(e1.getAtomicNumber(), 4) TEST_EQUAL(e2.getAtomicNumber(), 0) RESULT CHECK(setAtomicWeight(float AtomicWeight)) e1.setAtomicWeight(5.0); RESULT CHECK(getAtomicWeight()) TEST_EQUAL(e1.getAtomicWeight(), 5.0) TEST_EQUAL(e2.getAtomicWeight(), 0.0) RESULT CHECK(setAtomicRadius(float AtomicRadius)) e1.setAtomicRadius(6.0); RESULT CHECK(getAtomicRadius()) TEST_EQUAL(e1.getAtomicRadius(), 6.0) TEST_EQUAL(e2.getAtomicRadius(), 0.0) RESULT CHECK(setCovalentRadius(float CovalentRadius)) e1.setCovalentRadius(7.0); RESULT CHECK(getCovalentRadius()) TEST_EQUAL(e1.getCovalentRadius(), 7.0) TEST_EQUAL(e2.getCovalentRadius(), 0.0) RESULT CHECK(setVanDerWaalsRadius(float VanDerWaalsRadius)) e1.setVanDerWaalsRadius(8.0); RESULT CHECK(getVanDerWaalsRadius()) TEST_EQUAL(e1.getVanDerWaalsRadius(), 8.0) TEST_EQUAL(e2.getVanDerWaalsRadius(), 0.0) RESULT CHECK(setElectronegativity(float Electronegativity)) e1.setElectronegativity(9.0); RESULT CHECK(getElectronegativity()) TEST_EQUAL(e1.getElectronegativity(), 9.0) TEST_EQUAL(e2.getElectronegativity(), 0.0) RESULT CHECK(operator ==(const Element& element) const) TEST_EQUAL(e1 == e2, false) TEST_EQUAL(e3 == e2, true) RESULT CHECK(operator !=(const Element& element) const) TEST_EQUAL(e3 != e1, true) TEST_EQUAL(e3 != e2, false) RESULT CHECK(operator <(const Element& element) const) TEST_EQUAL(e2 < e1, true) TEST_EQUAL(e2 < e3, false) RESULT CHECK(operator <=(const Element& element) const) TEST_EQUAL(e1 <= e2, false) TEST_EQUAL(e3 <= e2, true) TEST_EQUAL(e2 <= e1, true) RESULT CHECK(operator >=(const Element& element) const) TEST_EQUAL(e2 >= e1, false) TEST_EQUAL(e1 >= e2, true) TEST_EQUAL(e2 >= e2, true) RESULT CHECK(operator >(const Element& element) const) TEST_EQUAL(e2 > e1, false) TEST_EQUAL(e1 > e2, true) TEST_EQUAL(e2 > e3, false) RESULT CHECK(isUnknown() const) TEST_EQUAL(e1.isUnknown(), false) TEST_EQUAL(e2.isUnknown(), true) RESULT String filename; NEW_TMP_FILE(filename) CHECK(std::ostream& operator << (std::ostream& s, const Element& element)) std::ofstream outstr(filename.c_str(), std::ios::out); outstr << e1; outstr.close(); TEST_FILE(filename.c_str(), "data/PTE_test.txt", false) RESULT CHECK(getElement(Position position)) TEST_EQUAL(PTE.getElement(1).getName(), "Aluminium") RESULT CHECK(getElement(const String& symbol)) TEST_EQUAL(PTE.getElement("Al").getName(), "Aluminium") RESULT CHECK(Element &operator [](const String& symbol)) TEST_EQUAL(PTE["Al"].getName(), "Aluminium") RESULT CHECK(Element &operator [](Element::Symbol symbol)) TEST_EQUAL(PTE[Element::Al].getName(), "Aluminium") RESULT CHECK(Element &operator [](Position position)) TEST_EQUAL(PTE[13].getName(), "Aluminium") RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>*** empty log message ***<commit_after>// $Id: PTE_test.C,v 1.3 2000/05/31 00:59:50 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/KERNEL/PTE.h> /////////////////////////// START_TEST(Element, "$Id: PTE_test.C,v 1.3 2000/05/31 00:59:50 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; Element* e; CHECK(Element()) e = new Element; TEST_NOT_EQUAL(e, 0) RESULT CHECK(~Element()) delete e; RESULT CHECK(Element(Element&, bool)) Element* e1 = new Element; e1->setName("testname"); Element* e2 = new Element(*e1, true); TEST_NOT_EQUAL(e2, 0) if (e2 != 0) { TEST_EQUAL(e2->getName(), "testname") delete e2; } RESULT CHECK(Element(const String& name, const String& symbol, Group group, Period period, AtomicNumber atomic_umber, float atomic_weight, float atomic_radius, float covalent_radius, float van_der_waals_radius, float electronegativity)) Element* e1 = new Element("e1", "id", 2, 3, 25, 25.0, 2.0, 3.0, 4.0, 5.0); TEST_NOT_EQUAL(e1, 0) if (e1 != 0) { TEST_EQUAL(e1->getName(), "e1") TEST_EQUAL(e1->getSymbol(), "id") TEST_EQUAL(e1->getGroup(), 2) TEST_EQUAL(e1->getPeriod(), 3) TEST_EQUAL(e1->getAtomicNumber(), 25) TEST_EQUAL(e1->getAtomicWeight(), 25.0) TEST_EQUAL(e1->getAtomicRadius(), 2.0) TEST_EQUAL(e1->getCovalentRadius(), 3.0) TEST_EQUAL(e1->getVanDerWaalsRadius(), 4.0) TEST_EQUAL(e1->getElectronegativity(), 5.0) } Element* e2 = new Element(*e1); TEST_NOT_EQUAL(e2, 0) if (e2 != 0) { TEST_EQUAL(e2->getName(), "e1") TEST_EQUAL(e2->getSymbol(), "id") TEST_EQUAL(e2->getGroup(), 2) TEST_EQUAL(e2->getPeriod(), 3) TEST_EQUAL(e2->getAtomicNumber(), 25) TEST_EQUAL(e2->getAtomicWeight(), 25.0) TEST_EQUAL(e2->getAtomicRadius(), 2.0) TEST_EQUAL(e2->getCovalentRadius(), 3.0) TEST_EQUAL(e2->getVanDerWaalsRadius(), 4.0) TEST_EQUAL(e2->getElectronegativity(), 5.0) delete e2; } RESULT Element e1; Element e2; Element e3; CHECK(setName(const String& name)) e1.setName("e1"); RESULT CHECK(getName()) TEST_EQUAL(e1.getName(), "e1") TEST_EQUAL(e2.getName(), "Unknown") RESULT CHECK(setSymbol(const String& symbol)) e1.setSymbol("s"); RESULT CHECK(getSymbol()) TEST_EQUAL(e1.getSymbol(), "s") TEST_EQUAL(e2.getSymbol(), "?") RESULT CHECK(setGroup(Group group)) e1.setGroup(2); RESULT CHECK(getGroup()) TEST_EQUAL(e1.getGroup(), 2) TEST_EQUAL(e2.getGroup(), 0) RESULT CHECK(setPeriod(Period Period)) e1.setPeriod(3); RESULT CHECK(getPeriod()) TEST_EQUAL(e1.getPeriod(), 3) TEST_EQUAL(e2.getPeriod(), 0) RESULT CHECK(setAtomicNumber(AtomicNumber AtomicNumber)) e1.setAtomicNumber(4); RESULT CHECK(getAtomicNumber()) TEST_EQUAL(e1.getAtomicNumber(), 4) TEST_EQUAL(e2.getAtomicNumber(), 0) RESULT CHECK(setAtomicWeight(float AtomicWeight)) e1.setAtomicWeight(5.0); RESULT CHECK(getAtomicWeight()) TEST_EQUAL(e1.getAtomicWeight(), 5.0) TEST_EQUAL(e2.getAtomicWeight(), 0.0) RESULT CHECK(setAtomicRadius(float AtomicRadius)) e1.setAtomicRadius(6.0); RESULT CHECK(getAtomicRadius()) TEST_EQUAL(e1.getAtomicRadius(), 6.0) TEST_EQUAL(e2.getAtomicRadius(), 0.0) RESULT CHECK(setCovalentRadius(float CovalentRadius)) e1.setCovalentRadius(7.0); RESULT CHECK(getCovalentRadius()) TEST_EQUAL(e1.getCovalentRadius(), 7.0) TEST_EQUAL(e2.getCovalentRadius(), 0.0) RESULT CHECK(setVanDerWaalsRadius(float VanDerWaalsRadius)) e1.setVanDerWaalsRadius(8.0); RESULT CHECK(getVanDerWaalsRadius()) TEST_EQUAL(e1.getVanDerWaalsRadius(), 8.0) TEST_EQUAL(e2.getVanDerWaalsRadius(), 0.0) RESULT CHECK(setElectronegativity(float Electronegativity)) e1.setElectronegativity(9.0); RESULT CHECK(getElectronegativity()) TEST_EQUAL(e1.getElectronegativity(), 9.0) TEST_EQUAL(e2.getElectronegativity(), 0.0) RESULT CHECK(operator ==(const Element& element) const) TEST_EQUAL(e1 == e2, false) TEST_EQUAL(e3 == e2, true) RESULT CHECK(operator !=(const Element& element) const) TEST_EQUAL(e3 != e1, true) TEST_EQUAL(e3 != e2, false) RESULT CHECK(operator <(const Element& element) const) TEST_EQUAL(e2 < e1, true) TEST_EQUAL(e2 < e3, false) RESULT CHECK(operator <=(const Element& element) const) TEST_EQUAL(e1 <= e2, false) TEST_EQUAL(e3 <= e2, true) TEST_EQUAL(e2 <= e1, true) RESULT CHECK(operator >=(const Element& element) const) TEST_EQUAL(e2 >= e1, false) TEST_EQUAL(e1 >= e2, true) TEST_EQUAL(e2 >= e2, true) RESULT CHECK(operator >(const Element& element) const) TEST_EQUAL(e2 > e1, false) TEST_EQUAL(e1 > e2, true) TEST_EQUAL(e2 > e3, false) RESULT CHECK(isUnknown() const) TEST_EQUAL(e1.isUnknown(), false) TEST_EQUAL(e2.isUnknown(), true) RESULT String filename; NEW_TMP_FILE(filename) CHECK(std::ostream& operator << (std::ostream& s, const Element& element)) std::ofstream outstr(filename.c_str(), std::ios::out); outstr << e1; outstr.close(); TEST_FILE(filename.c_str(), "data/PTE_test.txt", false) RESULT CHECK(getElement(Position position)) TEST_EQUAL(PTE.getElement(1).getName(), "Aluminium") RESULT CHECK(getElement(const String& symbol)) TEST_EQUAL(PTE.getElement("Al").getName(), "Aluminium") RESULT CHECK(Element &operator [](const String& symbol)) TEST_EQUAL(PTE["Al"].getName(), "Aluminium") RESULT CHECK(Element &operator [](Element::Symbol symbol)) TEST_EQUAL(PTE[Element::Al].getName(), "Aluminium") RESULT CHECK(Element &operator [](Position position)) TEST_EQUAL(PTE[13].getName(), "Aluminium") RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>#pragma once #include "routing/cross_mwm_connector.hpp" #include "routing/cross_mwm_connector_serialization.hpp" #include "routing/fake_feature_ids.hpp" #include "routing/routing_exceptions.hpp" #include "routing/segment.hpp" #include "routing/vehicle_mask.hpp" #include "routing_common/num_mwm_id.hpp" #include "routing_common/vehicle_model.hpp" #include "geometry/point2d.hpp" #include "coding/files_container.hpp" #include "coding/point_coding.hpp" #include "coding/reader.hpp" #include "indexer/data_source.hpp" #include "base/logging.hpp" #include <cstdint> #include <map> #include <memory> #include <type_traits> #include <vector> namespace routing { namespace connector { template <typename CrossMwmId> inline FilesContainerR::TReader GetReader(FilesContainerR const & cont) { return cont.GetReader(CROSS_MWM_FILE_TAG); } template <> inline FilesContainerR::TReader GetReader<TransitId>(FilesContainerR const & cont) { return cont.GetReader(TRANSIT_CROSS_MWM_FILE_TAG); } template <typename CrossMwmId> uint32_t constexpr GetFeaturesOffset() noexcept { return 0; } template <> uint32_t constexpr GetFeaturesOffset<TransitId>() noexcept { return FakeFeatureIds::kTransitGraphFeaturesStart; } template <typename CrossMwmId> void AssertConnectorIsFound(NumMwmId neighbor, bool isConnectorFound) { CHECK(isConnectorFound, ("Connector for mwm with number mwm id", neighbor, "was not deserialized.")); } template <> inline void AssertConnectorIsFound<TransitId>(NumMwmId /* neighbor */, bool /* isConnectorFound */) { } } // namespace connector template <typename CrossMwmId> class CrossMwmIndexGraph final { public: using ReaderSourceFile = ReaderSource<FilesContainerR::TReader>; CrossMwmIndexGraph(DataSource & dataSource, std::shared_ptr<NumMwmIds> numMwmIds, VehicleType vehicleType) : m_dataSource(dataSource), m_numMwmIds(numMwmIds), m_vehicleType(vehicleType) { } bool IsTransition(Segment const & s, bool isOutgoing) { CrossMwmConnector<CrossMwmId> const & c = GetCrossMwmConnectorWithTransitions(s.GetMwmId()); return c.IsTransition(s, isOutgoing); } bool IsFeatureTransit(NumMwmId numMwmId, uint32_t featureId) { return GetCrossMwmConnectorWithTransitions(numMwmId).IsFeatureCrossMwmConnector(featureId); } std::vector<uint32_t> const & GetTransitSegmentId(NumMwmId numMwmId, uint32_t featureId) { return GetCrossMwmConnectorWithTransitions(numMwmId).GetTransitSegmentId(featureId); } /// \brief Fills |twins| based on transitions defined in cross_mwm section. /// \note In cross_mwm section transitions are defined by osm ids of theirs features. /// \note This method fills |twins| with all available twins iff all neighboring of mwm of |s| // have cross_mwm section. void GetTwinsByCrossMwmId(Segment const & s, bool isOutgoing, std::vector<NumMwmId> const & neighbors, std::vector<Segment> & twins) { auto const & crossMwmId = GetCrossMwmConnectorWithTransitions(s.GetMwmId()).GetCrossMwmId(s); for (NumMwmId const neighbor : neighbors) { auto const it = m_connectors.find(neighbor); // In case of TransitId, a connector for a mwm with number id |neighbor| may not be found // if mwm with such id does not contain corresponding transit_cross_mwm section. // It may happen in case of obsolete mwms. // Note. Actually it is assumed that connectors always must be found for car routing case. // That means mwm without cross_mwm section is not supported. connector::AssertConnectorIsFound<CrossMwmId>(neighbor, it != m_connectors.cend()); if (it == m_connectors.cend()) continue; CrossMwmConnector<CrossMwmId> const & connector = it->second; // Note. Last parameter in the method below (isEnter) should be set to |isOutgoing|. // If |isOutgoing| == true |s| should be an exit transition segment and the method below searches enters // and the last parameter (|isEnter|) should be set to true. // If |isOutgoing| == false |s| should be an enter transition segment and the method below searches exits // and the last parameter (|isEnter|) should be set to false. Segment const * twinSeg = connector.GetTransition(crossMwmId, s.GetSegmentIdx(), isOutgoing); if (twinSeg == nullptr) continue; // Twins should have the same direction, because we assume that twins are the same segments // with one difference - they are in the different mwms. Twins could have not same direction // in case of different mwms versions. For example |s| is cross mwm Enter from elder version // and somebody moved points of ways such that |twinSeg| became cross mwm Exit from newer // version. Because of that |twinSeg.IsForward()| will differ from |s.IsForward()|. if (twinSeg->IsForward() != s.IsForward()) continue; CHECK_NOT_EQUAL(twinSeg->GetMwmId(), s.GetMwmId(), ()); // Checks twins for equality. // There are same in common, but in case of different version of mwms // their's geometry can differ from each other. Because of this we can not // build the route, because we fail in astar_algorithm.hpp CHECK(invariant) sometimes. if (SegmentsAreEqualByGeometry(s, *twinSeg)) twins.push_back(*twinSeg); else LOG(LINFO, ("Bad cross mwm feature, differ in geometry. Current:", s, ", twin:", *twinSeg)); } } void GetOutgoingEdgeList(Segment const & s, std::vector<SegmentEdge> & edges) { CrossMwmConnector<CrossMwmId> const & c = GetCrossMwmConnectorWithWeights(s.GetMwmId()); c.GetOutgoingEdgeList(s, edges); } void GetIngoingEdgeList(Segment const & s, std::vector<SegmentEdge> & edges) { CrossMwmConnector<CrossMwmId> const & c = GetCrossMwmConnectorWithWeights(s.GetMwmId()); c.GetIngoingEdgeList(s, edges); } void Clear() { m_connectors.clear(); } bool InCache(NumMwmId numMwmId) const { return m_connectors.count(numMwmId) != 0; } CrossMwmConnector<CrossMwmId> const & GetCrossMwmConnectorWithTransitions(NumMwmId numMwmId) { auto const it = m_connectors.find(numMwmId); if (it != m_connectors.cend()) return it->second; return Deserialize( numMwmId, CrossMwmConnectorSerializer::DeserializeTransitions<ReaderSourceFile, CrossMwmId>); } void LoadCrossMwmConnectorWithTransitions(NumMwmId numMwmId) { GetCrossMwmConnectorWithTransitions(numMwmId); } std::vector<Segment> const & GetTransitions(NumMwmId numMwmId, bool isEnter) { auto const & connector = GetCrossMwmConnectorWithTransitions(numMwmId); return isEnter ? connector.GetEnters() : connector.GetExits(); } private: std::vector<m2::PointD> GetFeaturePointsBySegment(Segment const & segment) { std::vector<m2::PointD> geometry; auto const & handle = m_dataSource.GetMwmHandleByCountryFile(m_numMwmIds->GetFile(segment.GetMwmId())); if (!handle.IsAlive()) return geometry; auto const & mwmId = handle.GetId(); auto const & featureId = FeatureID(mwmId, segment.GetFeatureId()); auto const fillGeometry = [&geometry](FeatureType & ftype) { ftype.ParseGeometry(FeatureType::BEST_GEOMETRY); geometry.reserve(ftype.GetPointsCount()); for (uint32_t i = 0; i < ftype.GetPointsCount(); ++i) geometry.emplace_back(ftype.GetPoint(i)); }; m_dataSource.ReadFeature(fillGeometry, featureId); return geometry; } /// \brief Checks segment for equality point by point. bool SegmentsAreEqualByGeometry(Segment const & one, Segment const & two) { // Do not check for transit graph. if (!one.IsRealSegment() || !two.IsRealSegment()) return true; static_assert(std::is_same<CrossMwmId, base::GeoObjectId>::value || std::is_same<CrossMwmId, connector::TransitId>::value, "Be careful of usage other ids here. " "Make sure, there is not crash with your new CrossMwmId"); std::vector<m2::PointD> geometryOne = GetFeaturePointsBySegment(one); std::vector<m2::PointD> geometryTwo = GetFeaturePointsBySegment(two); if (geometryOne.size() != geometryTwo.size()) return false; for (uint32_t i = 0; i < geometryOne.size(); ++i) { if (!base::AlmostEqualAbs(geometryOne[i], geometryTwo[i], kMwmPointAccuracy)) return false; } return true; } CrossMwmConnector<CrossMwmId> const & GetCrossMwmConnectorWithWeights(NumMwmId numMwmId) { auto const & c = GetCrossMwmConnectorWithTransitions(numMwmId); if (c.WeightsWereLoaded()) return c; return Deserialize( numMwmId, CrossMwmConnectorSerializer::DeserializeWeights<ReaderSourceFile, CrossMwmId>); } /// \brief Deserializes connectors for an mwm with |numMwmId|. /// \param fn is a function implementing deserialization. /// \note Each CrossMwmConnector contained in |m_connectors| may be deserialized in two stages. /// The first one is transition deserialization and the second is weight deserialization. /// Transition deserialization is much faster and used more often. template <typename Fn> CrossMwmConnector<CrossMwmId> const & Deserialize(NumMwmId numMwmId, Fn && fn) { MwmSet::MwmHandle handle = m_dataSource.GetMwmHandleByCountryFile(m_numMwmIds->GetFile(numMwmId)); if (!handle.IsAlive()) MYTHROW(RoutingException, ("Mwm", m_numMwmIds->GetFile(numMwmId), "cannot be loaded.")); MwmValue const * value = handle.GetValue(); CHECK(value != nullptr, ("Country file:", m_numMwmIds->GetFile(numMwmId))); FilesContainerR::TReader const reader = FilesContainerR::TReader(connector::GetReader<CrossMwmId>(value->m_cont)); ReaderSourceFile src(reader); auto it = m_connectors.find(numMwmId); if (it == m_connectors.end()) it = m_connectors .emplace(numMwmId, CrossMwmConnector<CrossMwmId>( numMwmId, connector::GetFeaturesOffset<CrossMwmId>())) .first; fn(m_vehicleType, it->second, src); return it->second; } DataSource & m_dataSource; std::shared_ptr<NumMwmIds> m_numMwmIds; VehicleType m_vehicleType; /// \note |m_connectors| contains cache with transition segments and leap edges. /// Each mwm in |m_connectors| may be in two conditions: /// * with loaded transition segments (after a call to /// CrossMwmConnectorSerializer::DeserializeTransitions()) /// * with loaded transition segments and with loaded weights /// (after a call to CrossMwmConnectorSerializer::DeserializeTransitions() /// and CrossMwmConnectorSerializer::DeserializeWeights()) std::map<NumMwmId, CrossMwmConnector<CrossMwmId>> m_connectors; }; } // namespace routing <commit_msg>[routing] Routing performance optimization. Stop checking twin features geometry on the same mwm versions.<commit_after>#pragma once #include "routing/cross_mwm_connector.hpp" #include "routing/cross_mwm_connector_serialization.hpp" #include "routing/fake_feature_ids.hpp" #include "routing/routing_exceptions.hpp" #include "routing/segment.hpp" #include "routing/vehicle_mask.hpp" #include "routing_common/num_mwm_id.hpp" #include "routing_common/vehicle_model.hpp" #include "geometry/point2d.hpp" #include "coding/files_container.hpp" #include "coding/point_coding.hpp" #include "coding/reader.hpp" #include "indexer/data_source.hpp" #include "base/logging.hpp" #include <cstdint> #include <map> #include <memory> #include <type_traits> #include <vector> namespace routing { namespace connector { template <typename CrossMwmId> inline FilesContainerR::TReader GetReader(FilesContainerR const & cont) { return cont.GetReader(CROSS_MWM_FILE_TAG); } template <> inline FilesContainerR::TReader GetReader<TransitId>(FilesContainerR const & cont) { return cont.GetReader(TRANSIT_CROSS_MWM_FILE_TAG); } template <typename CrossMwmId> uint32_t constexpr GetFeaturesOffset() noexcept { return 0; } template <> uint32_t constexpr GetFeaturesOffset<TransitId>() noexcept { return FakeFeatureIds::kTransitGraphFeaturesStart; } template <typename CrossMwmId> void AssertConnectorIsFound(NumMwmId neighbor, bool isConnectorFound) { CHECK(isConnectorFound, ("Connector for mwm with number mwm id", neighbor, "was not deserialized.")); } template <> inline void AssertConnectorIsFound<TransitId>(NumMwmId /* neighbor */, bool /* isConnectorFound */) { } } // namespace connector template <typename CrossMwmId> class CrossMwmIndexGraph final { public: using ReaderSourceFile = ReaderSource<FilesContainerR::TReader>; CrossMwmIndexGraph(DataSource & dataSource, std::shared_ptr<NumMwmIds> numMwmIds, VehicleType vehicleType) : m_dataSource(dataSource), m_numMwmIds(numMwmIds), m_vehicleType(vehicleType) { } bool IsTransition(Segment const & s, bool isOutgoing) { CrossMwmConnector<CrossMwmId> const & c = GetCrossMwmConnectorWithTransitions(s.GetMwmId()); return c.IsTransition(s, isOutgoing); } bool IsFeatureTransit(NumMwmId numMwmId, uint32_t featureId) { return GetCrossMwmConnectorWithTransitions(numMwmId).IsFeatureCrossMwmConnector(featureId); } std::vector<uint32_t> const & GetTransitSegmentId(NumMwmId numMwmId, uint32_t featureId) { return GetCrossMwmConnectorWithTransitions(numMwmId).GetTransitSegmentId(featureId); } /// \brief Fills |twins| based on transitions defined in cross_mwm section. /// \note In cross_mwm section transitions are defined by osm ids of theirs features. /// \note This method fills |twins| with all available twins iff all neighboring of mwm of |s| // have cross_mwm section. void GetTwinsByCrossMwmId(Segment const & s, bool isOutgoing, std::vector<NumMwmId> const & neighbors, std::vector<Segment> & twins) { auto const & crossMwmId = GetCrossMwmConnectorWithTransitions(s.GetMwmId()).GetCrossMwmId(s); for (NumMwmId const neighbor : neighbors) { auto const it = m_connectors.find(neighbor); // In case of TransitId, a connector for a mwm with number id |neighbor| may not be found // if mwm with such id does not contain corresponding transit_cross_mwm section. // It may happen in case of obsolete mwms. // Note. Actually it is assumed that connectors always must be found for car routing case. // That means mwm without cross_mwm section is not supported. connector::AssertConnectorIsFound<CrossMwmId>(neighbor, it != m_connectors.cend()); if (it == m_connectors.cend()) continue; CrossMwmConnector<CrossMwmId> const & connector = it->second; // Note. Last parameter in the method below (isEnter) should be set to |isOutgoing|. // If |isOutgoing| == true |s| should be an exit transition segment and the method below searches enters // and the last parameter (|isEnter|) should be set to true. // If |isOutgoing| == false |s| should be an enter transition segment and the method below searches exits // and the last parameter (|isEnter|) should be set to false. Segment const * twinSeg = connector.GetTransition(crossMwmId, s.GetSegmentIdx(), isOutgoing); if (twinSeg == nullptr) continue; // Twins should have the same direction, because we assume that twins are the same segments // with one difference - they are in the different mwms. Twins could have not same direction // in case of different mwms versions. For example |s| is cross mwm Enter from elder version // and somebody moved points of ways such that |twinSeg| became cross mwm Exit from newer // version. Because of that |twinSeg.IsForward()| will differ from |s.IsForward()|. if (twinSeg->IsForward() != s.IsForward()) continue; CHECK_NOT_EQUAL(twinSeg->GetMwmId(), s.GetMwmId(), ()); // Checks twins for equality if they are from different mwm versions. // There are same in common, but in case of different version of mwms // their's geometry can differ from each other. Because of this we can not // build the route, because we fail in astar_algorithm.hpp CHECK(invariant) sometimes. auto const & sMwmId = m_dataSource.GetMwmIdByCountryFile(m_numMwmIds->GetFile(s.GetMwmId())); CHECK(sMwmId.IsAlive(), (s)); auto const & twinSegMwmId = m_dataSource.GetMwmIdByCountryFile(m_numMwmIds->GetFile(twinSeg->GetMwmId())); CHECK(twinSegMwmId.IsAlive(), (*twinSeg)); if (sMwmId.GetInfo()->GetVersion() == twinSegMwmId.GetInfo()->GetVersion() || SegmentsAreEqualByGeometry(s, *twinSeg)) { twins.push_back(*twinSeg); } else { LOG(LINFO, ("Bad cross mwm feature, differ in geometry. Current:", s, ", twin:", *twinSeg)); } } } void GetOutgoingEdgeList(Segment const & s, std::vector<SegmentEdge> & edges) { CrossMwmConnector<CrossMwmId> const & c = GetCrossMwmConnectorWithWeights(s.GetMwmId()); c.GetOutgoingEdgeList(s, edges); } void GetIngoingEdgeList(Segment const & s, std::vector<SegmentEdge> & edges) { CrossMwmConnector<CrossMwmId> const & c = GetCrossMwmConnectorWithWeights(s.GetMwmId()); c.GetIngoingEdgeList(s, edges); } void Clear() { m_connectors.clear(); } bool InCache(NumMwmId numMwmId) const { return m_connectors.count(numMwmId) != 0; } CrossMwmConnector<CrossMwmId> const & GetCrossMwmConnectorWithTransitions(NumMwmId numMwmId) { auto const it = m_connectors.find(numMwmId); if (it != m_connectors.cend()) return it->second; return Deserialize( numMwmId, CrossMwmConnectorSerializer::DeserializeTransitions<ReaderSourceFile, CrossMwmId>); } void LoadCrossMwmConnectorWithTransitions(NumMwmId numMwmId) { GetCrossMwmConnectorWithTransitions(numMwmId); } std::vector<Segment> const & GetTransitions(NumMwmId numMwmId, bool isEnter) { auto const & connector = GetCrossMwmConnectorWithTransitions(numMwmId); return isEnter ? connector.GetEnters() : connector.GetExits(); } private: std::vector<m2::PointD> GetFeaturePointsBySegment(Segment const & segment) { std::vector<m2::PointD> geometry; auto const & handle = m_dataSource.GetMwmHandleByCountryFile(m_numMwmIds->GetFile(segment.GetMwmId())); if (!handle.IsAlive()) return geometry; auto const & mwmId = handle.GetId(); auto const & featureId = FeatureID(mwmId, segment.GetFeatureId()); auto const fillGeometry = [&geometry](FeatureType & ftype) { ftype.ParseGeometry(FeatureType::BEST_GEOMETRY); geometry.reserve(ftype.GetPointsCount()); for (uint32_t i = 0; i < ftype.GetPointsCount(); ++i) geometry.emplace_back(ftype.GetPoint(i)); }; m_dataSource.ReadFeature(fillGeometry, featureId); return geometry; } /// \brief Checks segment for equality point by point. bool SegmentsAreEqualByGeometry(Segment const & one, Segment const & two) { // Do not check for transit graph. if (!one.IsRealSegment() || !two.IsRealSegment()) return true; static_assert(std::is_same<CrossMwmId, base::GeoObjectId>::value || std::is_same<CrossMwmId, connector::TransitId>::value, "Be careful of usage other ids here. " "Make sure, there is not crash with your new CrossMwmId"); std::vector<m2::PointD> geometryOne = GetFeaturePointsBySegment(one); std::vector<m2::PointD> geometryTwo = GetFeaturePointsBySegment(two); if (geometryOne.size() != geometryTwo.size()) return false; for (uint32_t i = 0; i < geometryOne.size(); ++i) { if (!base::AlmostEqualAbs(geometryOne[i], geometryTwo[i], kMwmPointAccuracy)) return false; } return true; } CrossMwmConnector<CrossMwmId> const & GetCrossMwmConnectorWithWeights(NumMwmId numMwmId) { auto const & c = GetCrossMwmConnectorWithTransitions(numMwmId); if (c.WeightsWereLoaded()) return c; return Deserialize( numMwmId, CrossMwmConnectorSerializer::DeserializeWeights<ReaderSourceFile, CrossMwmId>); } /// \brief Deserializes connectors for an mwm with |numMwmId|. /// \param fn is a function implementing deserialization. /// \note Each CrossMwmConnector contained in |m_connectors| may be deserialized in two stages. /// The first one is transition deserialization and the second is weight deserialization. /// Transition deserialization is much faster and used more often. template <typename Fn> CrossMwmConnector<CrossMwmId> const & Deserialize(NumMwmId numMwmId, Fn && fn) { MwmSet::MwmHandle handle = m_dataSource.GetMwmHandleByCountryFile(m_numMwmIds->GetFile(numMwmId)); if (!handle.IsAlive()) MYTHROW(RoutingException, ("Mwm", m_numMwmIds->GetFile(numMwmId), "cannot be loaded.")); MwmValue const * value = handle.GetValue(); CHECK(value != nullptr, ("Country file:", m_numMwmIds->GetFile(numMwmId))); FilesContainerR::TReader const reader = FilesContainerR::TReader(connector::GetReader<CrossMwmId>(value->m_cont)); ReaderSourceFile src(reader); auto it = m_connectors.find(numMwmId); if (it == m_connectors.end()) it = m_connectors .emplace(numMwmId, CrossMwmConnector<CrossMwmId>( numMwmId, connector::GetFeaturesOffset<CrossMwmId>())) .first; fn(m_vehicleType, it->second, src); return it->second; } DataSource & m_dataSource; std::shared_ptr<NumMwmIds> m_numMwmIds; VehicleType m_vehicleType; /// \note |m_connectors| contains cache with transition segments and leap edges. /// Each mwm in |m_connectors| may be in two conditions: /// * with loaded transition segments (after a call to /// CrossMwmConnectorSerializer::DeserializeTransitions()) /// * with loaded transition segments and with loaded weights /// (after a call to CrossMwmConnectorSerializer::DeserializeTransitions() /// and CrossMwmConnectorSerializer::DeserializeWeights()) std::map<NumMwmId, CrossMwmConnector<CrossMwmId>> m_connectors; }; } // namespace routing <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2009 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <mapnik/datasource.hpp> #include <mapnik/wkb.hpp> #include "connection_manager.hpp" #include "cursorresultset.hpp" // boost #include <boost/cstdint.hpp> #include <boost/optional.hpp> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> #include <boost/lexical_cast.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/program_options.hpp> //stl #include <iostream> #include <fstream> /* osm_id | integer | access | text | addr:flats | text | addr:housenumber | text | addr:interpolation | text | admin_level | text | aerialway | text | aeroway | text | amenity | text | area | text | barrier | text | bicycle | text | bridge | text | boundary | text | building | text | cutting | text | disused | text | embankment | text | foot | text | highway | text | historic | text | horse | text | junction | text | landuse | text | layer | text | learning | text | leisure | text | lock | text | man_made | text | military | text | motorcar | text | name | text | natural | text | oneway | text | power | text | power_source | text | place | text | railway | text | ref | text | religion | text | residence | text | route | text | sport | text | tourism | text | tracktype | text | tunnel | text | waterway | text | width | text | wood | text | z_order | integer | way_area | real | way | geometry | */ struct blob_to_hex { std::string operator() (const char* blob, unsigned size) { std::string buf; buf.reserve(size*2); std::ostringstream s(buf); s.seekp(0); char hex[3]; std::memset(hex,0,3); for ( unsigned pos=0; pos < size; ++pos) { std::sprintf (hex, "%02X", int(blob[pos]) & 0xff); s << hex; } return s.str(); } }; template <typename Connection, typename OUT> void pgsql2sqlite(Connection conn, std::string const& table_name, OUT & out, unsigned tolerance) { using namespace mapnik; boost::shared_ptr<ResultSet> rs = conn->executeQuery("select * from " + table_name + " limit 0;"); int count = rs->getNumFields(); std::ostringstream select_sql; select_sql << "select "; for (int i=0; i<count; ++i) { if (i!=0) select_sql << ","; select_sql << "\"" << rs->getFieldName(i) << "\""; } select_sql << " from " << table_name ; std::ostringstream geom_col_sql; geom_col_sql << "select f_geometry_column,srid,type from geometry_columns "; geom_col_sql << "where f_table_name='" << table_name << "'"; rs = conn->executeQuery(geom_col_sql.str()); int srid = -1; std::string geom_col = "UNKNOWN"; std::string geom_type = "UNKNOWN"; if ( rs->next()) { try { srid = boost::lexical_cast<int>(rs->getValue("srid")); } catch (boost::bad_lexical_cast &ex) { std::clog << ex.what() << std::endl; } geom_col = rs->getValue("f_geometry_column"); geom_type = rs->getValue("type"); } // add AsBinary(<geometry_column>) modifier std::string select_sql_str = select_sql.str(); if (tolerance > 0) { std::string from = "\"" + geom_col + "\""; std::string to = (boost::format("AsBinary(Simplify(%1%,%2%)) as %1%") % geom_col % tolerance).str(); boost::algorithm::replace_all(select_sql_str,from ,to); } else { boost::algorithm::replace_all(select_sql_str, "\"" + geom_col + "\"","AsBinary(" + geom_col+") as " + geom_col); } std::cout << select_sql_str << "\n"; //std::string select_sql = "select asBinary(way) as way,name,highway,osm_id from " + table_name; std::ostringstream cursor_sql; std::string cursor_name("my_cursor"); cursor_sql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << select_sql_str << " FOR READ ONLY"; conn->execute(cursor_sql.str()); boost::shared_ptr<CursorResultSet> cursor(new CursorResultSet(conn,cursor_name,10000)); unsigned num_fields = cursor->getNumFields(); std::ostringstream create_sql; create_sql << "create table " << table_name << "(PK_UID INTEGER PRIMARY KEY AUTOINCREMENT,"; int geometry_oid = -1; for ( unsigned pos = 0; pos < num_fields ; ++pos) { if (pos > 0) create_sql << ","; if (geom_col == cursor->getFieldName(pos)) { geometry_oid = cursor->getTypeOID(pos); create_sql << "'" << cursor->getFieldName(pos) << "' BLOB"; } else { create_sql << "'" << cursor->getFieldName(pos) << "' TEXT"; } } create_sql << ");"; std::cout << "client_encoding=" << conn->client_encoding() << "\n"; std::cout << "geometry_column=" << geom_col << "(" << geom_type << ") srid=" << srid << " oid=" << geometry_oid << "\n"; // begin out << "begin;\n"; out << create_sql.str() << "\n"; // spatial index sql out << "create virtual table idx_"<< table_name << "_" << geom_col << " using rtree(pkid, xmin, xmax, ymin, ymax);\n"; blob_to_hex hex; int pkid = 0; while (cursor->next()) { ++pkid; std::ostringstream insert_sql; insert_sql << "insert into " << table_name << " values(" << pkid; for (unsigned pos=0 ; pos < num_fields; ++pos) { insert_sql << ","; if (! cursor->isNull(pos)) { int size=cursor->getFieldLength(pos); int oid = cursor->getTypeOID(pos); const char* buf=cursor->getValue(pos); switch (oid) { case 25: case 1042: case 1043: { std::string text(buf); boost::algorithm::replace_all(text,"'","''"); insert_sql << "'"<< text << "'"; break; } case 23: insert_sql << int4net(buf); break; default: { if (oid == geometry_oid) { mapnik::Feature feat(pkid); geometry_utils::from_wkb(feat,buf,size,false,wkbGeneric); if (feat.num_geometries() > 0) { geometry2d const& geom=feat.get_geometry(0); Envelope<double> bbox = geom.envelope(); out << "insert into idx_" << table_name << "_" << geom_col << " values (" ; out << pkid << "," << bbox.minx() << "," << bbox.maxx(); out << "," << bbox.miny() << "," << bbox.maxy() << ");\n"; } insert_sql << "X'" << hex(buf,size) << "'"; } else { insert_sql << "NULL"; } break; } } } else { insert_sql << "NULL"; } } insert_sql << ");"; out << insert_sql.str() << "\n"; if (pkid % 1000 == 0) { std::cout << "\r processing " << pkid << " features"; std::cout.flush(); } if (pkid % 100000 == 0) { out << "commit;\n"; out << "begin;\n"; } } // commit out << "commit;\n"; std::cout << "\r processed " << pkid << " features"; std::cout << "\n Done!" << std::endl; } int main ( int argc, char** argv) { namespace po = boost::program_options; po::options_description desc("Postgresql/PostGIS to SQLite3 converter\n Options"); desc.add_options() ("help,?","Display this help screen.") ("host,h",po::value<std::string>(),"Allows you to specify connection to a database on a machine other than the default.") ("port,p",po::value<std::string>(),"Allows you to specify a database port other than the default.") ("user,u",po::value<std::string>(),"Connect to the database as the specified user.") ("dbname,d",po::value<std::string>(),"postgresql database name") ("password,P",po::value<std::string>(),"Connect to the database with the specified password.") ("table,t",po::value<std::string>(),"Name of the table to export") ("simplify,s",po::value<unsigned>(),"Use this option to reduce the complexity\nand weight of a geometry using the Douglas-Peucker algorithm.") ("file,f",po::value<std::string>(),"Use this option to specify the name of the file to create.") ; po::positional_options_description p; p.add("table",1); po::variables_map vm; try { po::store(po::command_line_parser(argc,argv).options(desc).positional(p).run(),vm); po::notify(vm); if (vm.count("help") || !vm.count("file") || !vm.count("table")) { std::cout << desc << "\n"; return EXIT_SUCCESS; } } catch (...) { std::cout << desc << "\n"; return EXIT_FAILURE; } boost::optional<std::string> host; boost::optional<std::string> port ; boost::optional<std::string> dbname; boost::optional<std::string> user; boost::optional<std::string> password; if (vm.count("host")) host = vm["host"].as<std::string>(); if (vm.count("port")) port = vm["port"].as<std::string>(); if (vm.count("dbname")) dbname = vm["dbname"].as<std::string>(); if (vm.count("user")) user = vm["user"].as<std::string>(); if (vm.count("password")) password = vm["password"].as<std::string>(); unsigned tolerance = 0; if (vm.count("simplify")) tolerance = vm["simplify"].as<unsigned>(); ConnectionCreator<Connection> creator(host,port,dbname,user,password); try { boost::shared_ptr<Connection> conn(creator()); std::string table_name = vm["table"].as<std::string>(); std::string output_file = vm["file"].as<std::string>(); std::ofstream file(output_file.c_str()); if (file) { pgsql2sqlite(conn,table_name,file,tolerance); } file.close(); } catch (mapnik::datasource_exception & ex) { std::cerr << ex.what() << "\n"; } return EXIT_SUCCESS; } <commit_msg>+ discard empty geometries from output<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2009 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #include <mapnik/datasource.hpp> #include <mapnik/wkb.hpp> #include "connection_manager.hpp" #include "cursorresultset.hpp" // boost #include <boost/cstdint.hpp> #include <boost/optional.hpp> #include <boost/scoped_ptr.hpp> #include <boost/shared_ptr.hpp> #include <boost/lexical_cast.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/program_options.hpp> //stl #include <iostream> #include <fstream> struct blob_to_hex { std::string operator() (const char* blob, unsigned size) { std::string buf; buf.reserve(size*2); std::ostringstream s(buf); s.seekp(0); char hex[3]; std::memset(hex,0,3); for ( unsigned pos=0; pos < size; ++pos) { std::sprintf (hex, "%02X", int(blob[pos]) & 0xff); s << hex; } return s.str(); } }; bool valid_envelope(mapnik::Envelope<double> const& e) { return (e.minx() < e.maxx() && e.miny() < e.maxy()) ; } template <typename Connection, typename OUT> void pgsql2sqlite(Connection conn, std::string const& table_name, OUT & out, unsigned tolerance) { using namespace mapnik; boost::shared_ptr<ResultSet> rs = conn->executeQuery("select * from " + table_name + " limit 0;"); int count = rs->getNumFields(); std::ostringstream select_sql; select_sql << "select "; for (int i=0; i<count; ++i) { if (i!=0) select_sql << ","; select_sql << "\"" << rs->getFieldName(i) << "\""; } select_sql << " from " << table_name ; std::ostringstream geom_col_sql; geom_col_sql << "select f_geometry_column,srid,type from geometry_columns "; geom_col_sql << "where f_table_name='" << table_name << "'"; rs = conn->executeQuery(geom_col_sql.str()); int srid = -1; std::string geom_col = "UNKNOWN"; std::string geom_type = "UNKNOWN"; if ( rs->next()) { try { srid = boost::lexical_cast<int>(rs->getValue("srid")); } catch (boost::bad_lexical_cast &ex) { std::clog << ex.what() << std::endl; } geom_col = rs->getValue("f_geometry_column"); geom_type = rs->getValue("type"); } // add AsBinary(<geometry_column>) modifier std::string select_sql_str = select_sql.str(); if (tolerance > 0) { std::string from = "\"" + geom_col + "\""; std::string to = (boost::format("AsBinary(Simplify(%1%,%2%)) as %1%") % geom_col % tolerance).str(); boost::algorithm::replace_all(select_sql_str,from ,to); } else { boost::algorithm::replace_all(select_sql_str, "\"" + geom_col + "\"","AsBinary(" + geom_col+") as " + geom_col); } std::cout << select_sql_str << "\n"; std::ostringstream cursor_sql; std::string cursor_name("my_cursor"); cursor_sql << "DECLARE " << cursor_name << " BINARY INSENSITIVE NO SCROLL CURSOR WITH HOLD FOR " << select_sql_str << " FOR READ ONLY"; conn->execute(cursor_sql.str()); boost::shared_ptr<CursorResultSet> cursor(new CursorResultSet(conn,cursor_name,10000)); unsigned num_fields = cursor->getNumFields(); std::ostringstream create_sql; create_sql << "create table " << table_name << "(PK_UID INTEGER PRIMARY KEY AUTOINCREMENT,"; int geometry_oid = -1; for ( unsigned pos = 0; pos < num_fields ; ++pos) { if (pos > 0) create_sql << ","; if (geom_col == cursor->getFieldName(pos)) { geometry_oid = cursor->getTypeOID(pos); create_sql << "'" << cursor->getFieldName(pos) << "' BLOB"; } else { create_sql << "'" << cursor->getFieldName(pos) << "' TEXT"; } } create_sql << ");"; std::cout << "client_encoding=" << conn->client_encoding() << "\n"; std::cout << "geometry_column=" << geom_col << "(" << geom_type << ") srid=" << srid << " oid=" << geometry_oid << "\n"; // begin out << "begin;\n"; out << create_sql.str() << "\n"; // spatial index sql out << "create virtual table idx_"<< table_name << "_" << geom_col << " using rtree(pkid, xmin, xmax, ymin, ymax);\n"; blob_to_hex hex; int pkid = 0; while (cursor->next()) { ++pkid; std::ostringstream insert_sql; insert_sql << "insert into " << table_name << " values(" << pkid; bool empty_geom = true; for (unsigned pos=0 ; pos < num_fields; ++pos) { insert_sql << ","; if (! cursor->isNull(pos)) { int size=cursor->getFieldLength(pos); int oid = cursor->getTypeOID(pos); const char* buf=cursor->getValue(pos); switch (oid) { case 25: case 1042: case 1043: { std::string text(buf); boost::algorithm::replace_all(text,"'","''"); insert_sql << "'"<< text << "'"; break; } case 23: insert_sql << int4net(buf); break; default: { if (oid == geometry_oid) { mapnik::Feature feat(pkid); geometry_utils::from_wkb(feat,buf,size,false,wkbGeneric); if (feat.num_geometries() > 0) { geometry2d const& geom=feat.get_geometry(0); Envelope<double> bbox = geom.envelope(); if (valid_envelope(bbox)) { out << "insert into idx_" << table_name << "_" << geom_col << " values (" ; out << pkid << "," << bbox.minx() << "," << bbox.maxx(); out << "," << bbox.miny() << "," << bbox.maxy() << ");\n"; empty_geom = false; } } insert_sql << "X'" << hex(buf,size) << "'"; } else { insert_sql << "NULL"; } break; } } } else { insert_sql << "NULL"; } } insert_sql << ");"; if (!empty_geom) out << insert_sql.str() << "\n"; if (pkid % 1000 == 0) { std::cout << "\r processing " << pkid << " features"; std::cout.flush(); } if (pkid % 100000 == 0) { out << "commit;\n"; out << "begin;\n"; } } // commit out << "commit;\n"; std::cout << "\r processed " << pkid << " features"; std::cout << "\n Done!" << std::endl; } int main ( int argc, char** argv) { namespace po = boost::program_options; po::options_description desc("Postgresql/PostGIS to SQLite3 converter\n Options"); desc.add_options() ("help,?","Display this help screen.") ("host,h",po::value<std::string>(),"Allows you to specify connection to a database on a machine other than the default.") ("port,p",po::value<std::string>(),"Allows you to specify a database port other than the default.") ("user,u",po::value<std::string>(),"Connect to the database as the specified user.") ("dbname,d",po::value<std::string>(),"postgresql database name") ("password,P",po::value<std::string>(),"Connect to the database with the specified password.") ("table,t",po::value<std::string>(),"Name of the table to export") ("simplify,s",po::value<unsigned>(),"Use this option to reduce the complexity\nand weight of a geometry using the Douglas-Peucker algorithm.") ("file,f",po::value<std::string>(),"Use this option to specify the name of the file to create.") ; po::positional_options_description p; p.add("table",1); po::variables_map vm; try { po::store(po::command_line_parser(argc,argv).options(desc).positional(p).run(),vm); po::notify(vm); if (vm.count("help") || !vm.count("file") || !vm.count("table")) { std::cout << desc << "\n"; return EXIT_SUCCESS; } } catch (...) { std::cout << desc << "\n"; return EXIT_FAILURE; } boost::optional<std::string> host; boost::optional<std::string> port ; boost::optional<std::string> dbname; boost::optional<std::string> user; boost::optional<std::string> password; if (vm.count("host")) host = vm["host"].as<std::string>(); if (vm.count("port")) port = vm["port"].as<std::string>(); if (vm.count("dbname")) dbname = vm["dbname"].as<std::string>(); if (vm.count("user")) user = vm["user"].as<std::string>(); if (vm.count("password")) password = vm["password"].as<std::string>(); unsigned tolerance = 0; if (vm.count("simplify")) tolerance = vm["simplify"].as<unsigned>(); ConnectionCreator<Connection> creator(host,port,dbname,user,password); try { boost::shared_ptr<Connection> conn(creator()); std::string table_name = vm["table"].as<std::string>(); std::string output_file = vm["file"].as<std::string>(); std::ofstream file(output_file.c_str()); if (file) { pgsql2sqlite(conn,table_name,file,tolerance); } file.close(); } catch (mapnik::datasource_exception & ex) { std::cerr << ex.what() << "\n"; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#pragma once // trace_constants.hpp: definition of constants that direct intermediate result reporting // // Copyright (C) 2017 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. namespace sw { namespace unum { # ifndef POSIT_VERBOSE_OUTPUT // posit decode and conversion constexpr bool _trace_decode = false; constexpr bool _trace_conversion = false; constexpr bool _trace_rounding = false; // arithmetic operator tracing constexpr bool _trace_add = false; constexpr bool _trace_sub = false; constexpr bool _trace_mul = false; constexpr bool _trace_div = false; constexpr bool _trace_reciprocate = false; # else // !POSIT_VERBOSE_OUTPUT // posit decode and conversion constexpr bool _trace_decode = true; constexpr bool _trace_conversion = true; constexpr bool _trace_rounding = true; // arithmetic operator tracing constexpr bool _trace_add = true; constexpr bool _trace_sub = true; constexpr bool _trace_mul = true; constexpr bool _trace_div = true; constexpr bool _trace_reciprocate = true; # endif } // namespace unum } // namespace sw<commit_msg>Improving granularity of tracing arithmetic intermediate results<commit_after>#pragma once // trace_constants.hpp: definition of constants that direct intermediate result reporting // // Copyright (C) 2017 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. namespace sw { namespace unum { # ifndef POSIT_VERBOSE_OUTPUT // posit decode and conversion constexpr bool _trace_decode = false; constexpr bool _trace_conversion = false; constexpr bool _trace_rounding = false; // arithmetic operator tracing constexpr bool _trace_add = false; constexpr bool _trace_sub = false; constexpr bool _trace_mul = false; constexpr bool _trace_div = false; constexpr bool _trace_reciprocate = false; # else // !POSIT_VERBOSE_OUTPUT #ifndef POSIT_TRACE_CONVERSION // posit decode and conversion constexpr bool _trace_decode = false; constexpr bool _trace_conversion = false; constexpr bool _trace_rounding = false; #else // posit decode and conversion constexpr bool _trace_decode = true; constexpr bool _trace_conversion = true; constexpr bool _trace_rounding = true; #endif // !POSIT_VERBOSE_CONVERSION // arithmetic operator tracing #ifndef POSIT_TRACE_ADD constexpr bool _trace_add = false; #else constexpr bool _trace_add = true; #endif #ifndef POSIT_TRACE_SUB constexpr bool _trace_sub = false; #else constexpr bool _trace_sub = true; #endif #ifndef POSIT_TRACE_MUL constexpr bool _trace_mul = false; #else constexpr bool _trace_mul = true; #endif #ifndef POSIT_TRACE_DIV constexpr bool _trace_div = false; #else constexpr bool _trace_div = true; #endif #ifndef POSIT_TRACE_RECIPROCATE constexpr bool _trace_reciprocate = false; #else constexpr bool _trace_reciprocate = true; #endif # endif } // namespace unum } // namespace sw<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <cstdlib> #include <fstream> #include <exception> using namespace std; typedef long unsigned int filePosition; //to index the file class XOREncryptor { void showProgressBar(filePosition ,filePosition); //it will display progress bar filePosition getFileSize(string); //to get the complete file size to calculate progress public: XOREncryptor(){} void encrypt(string ,string); void decrypt(string ,string); }; class unableToOpenFileException:public exception { public: virtual const char* what() { return "Unable to open file"; } }myExep; int main(int argc,char* argv[]) { XOREncryptor xorEncryptor; string fileName,key,choice; if(argc==4) { fileName=argv[2]; key=argv[3]; choice=argv[1]; if(choice=="encrypt") xorEncryptor.encrypt(fileName,key); else if(choice=="decrypt") xorEncryptor.decrypt(fileName,key); else cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl; } else cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl; cout<<"Press enter to continue..."<<endl; cin.get(); return 0; } void XOREncryptor::encrypt(string fileName,string key) { ifstream iFile; ofstream oFile; string outFileName=fileName+".xre"; int i=0; char temp; char *charptr=&temp; filePosition fullFileSize=getFileSize(fileName); try { iFile.open(fileName,ios::binary|ios::in); oFile.open(outFileName,ios::binary|ios::out|ios::trunc); if(!(oFile.is_open()||iFile.is_open())) throw myExep; cout<<"Encrypting File... Please wait!!!"<<endl; while(iFile.read(charptr,1)) { temp=temp^key[(i++)%key.length()]; oFile.put(temp); showProgressBar(iFile.tellg(),fullFileSize); } iFile.close(); oFile.close(); } catch(unableToOpenFileException ex) { cout<<ex.what()<<endl; exit(1); } cout<<"\nFile encrypted successfully!!!"<<endl; } void XOREncryptor::decrypt(string fileName,string key) { ifstream iFile; ofstream oFile; string outFileName; outFileName=fileName.substr(0,fileName.length()-4); int i=0; char temp; char *charptr=&temp; filePosition fullFileSize=getFileSize(fileName); try { iFile.open(fileName,ios::binary|ios::in); oFile.open(outFileName,ios::binary|ios::out|ios::trunc); if(!(oFile.is_open()||iFile.is_open())) throw myExep; cout<<"Decrypting File... Please wait!!!"<<endl; while(iFile.read(charptr,1)) { temp=temp^key[(i++)%key.length()]; oFile.put(temp); showProgressBar(iFile.tellg(),fullFileSize); } iFile.close(); oFile.close(); } catch(unableToOpenFileException ex) { cout<<ex.what()<<endl; exit(1); } cout<<"\nFile decrypted successfully!!!"<<endl; } void XOREncryptor::showProgressBar(filePosition completed,filePosition total) { float progress=static_cast<float>(completed)/total; int width=50; cout<<"["; for(int i=1;i<width;i++) { if(i<width*progress) cout<<"="; else cout<<" "; } cout<<"] "<<static_cast<int>(progress*100)<<"%\r"; } filePosition XOREncryptor::getFileSize(string fileName) { ifstream file(fileName,ios::in|ios::ate|ios::binary); return file.tellg(); } <commit_msg>minor fix<commit_after>#include <iostream> #include <string> #include <cstdlib> #include <fstream> #include <exception> using namespace std; typedef long unsigned int filePosition; //to index the file class XOREncryptor { void showProgressBar(filePosition ,filePosition); //it will display progress bar filePosition getFileSize(string); //to get the complete file size to calculate progress public: XOREncryptor(){} void encrypt(string ,string); void decrypt(string ,string); }; class unableToOpenFileException:public exception { public: virtual const char* what() { return "Unable to open file!!! Exiting..."; } }myExep; int main(int argc,char* argv[]) { XOREncryptor xorEncryptor; string fileName,key,choice; if(argc==4) { fileName=argv[2]; key=argv[3]; choice=argv[1]; if(choice=="encrypt") xorEncryptor.encrypt(fileName,key); else if(choice=="decrypt") xorEncryptor.decrypt(fileName,key); else cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl; } else cout<<"Usage: "<<argv[0]<<" <encrypt/decrypt> <filename> <key>"<<endl; cout<<"Press enter to continue..."<<endl; cin.get(); return 0; } void XOREncryptor::encrypt(string fileName,string key) { ifstream iFile; ofstream oFile; string outFileName=fileName+".xre"; int i=0; char temp; char *charptr=&temp; filePosition fullFileSize=getFileSize(fileName); try { iFile.open(fileName,ios::binary|ios::in); oFile.open(outFileName,ios::binary|ios::out|ios::trunc); if(!(oFile.is_open()||iFile.is_open())) throw myExep; cout<<"Encrypting File... Please wait!!!"<<endl; while(iFile.read(charptr,1)) { temp=temp^key[(i++)%key.length()]; oFile.put(temp); showProgressBar(iFile.tellg(),fullFileSize); } iFile.close(); oFile.close(); } catch(exception ex) { cout<<ex.what()<<endl; exit(1); } cout<<"\nFile encrypted successfully!!!"<<endl; } void XOREncryptor::decrypt(string fileName,string key) { ifstream iFile; ofstream oFile; string outFileName; outFileName=fileName.substr(0,fileName.length()-4); int i=0; char temp; char *charptr=&temp; filePosition fullFileSize=getFileSize(fileName); try { iFile.open(fileName,ios::binary|ios::in); oFile.open(outFileName,ios::binary|ios::out|ios::trunc); if(!(oFile.is_open()||iFile.is_open())) throw myExep; cout<<"Decrypting File... Please wait!!!"<<endl; while(iFile.read(charptr,1)) { temp=temp^key[(i++)%key.length()]; oFile.put(temp); showProgressBar(iFile.tellg(),fullFileSize); } iFile.close(); oFile.close(); } catch(exception ex) { cout<<ex.what()<<endl; exit(1); } cout<<"\nFile decrypted successfully!!!"<<endl; } void XOREncryptor::showProgressBar(filePosition completed,filePosition total) { float progress=static_cast<float>(completed)/total; int width=50; cout<<"["; for(int i=1;i<width;i++) { if(i<width*progress) cout<<"="; else cout<<" "; } cout<<"] "<<static_cast<int>(progress*100)<<"%\r"; } filePosition XOREncryptor::getFileSize(string fileName) { ifstream file(fileName,ios::in|ios::ate|ios::binary); return file.tellg(); } <|endoftext|>
<commit_before>#include "AnimusKeyboard.h" #include "ArduinoKeyboard.h" // this is for the modified arduino HID IKeyboard::IKeyboard(void) { //nothing } void IKeyboard::Begin(void) { Keyboard.begin(); } void IKeyboard::End(void) { Keyboard.end(); } void IKeyboard::Press(byte k) { Keyboard.press(k); } void IKeyboard::Release(byte k) { Keyboard.release(k); } void IKeyboard::SetNKRO(byte mode) { Keyboard.setNKROMode(mode); } uint8_t IKeyboard::GetNKRO(void) { return Keyboard.getNKROMode(); } void IKeyboard::ReleaseAll(void) { Keyboard.releaseAll(); } IKeyboard AnimusKeyboard; <commit_msg>add: mod modifier progress<commit_after>#include "AnimusKeyboard.h" #include "ArduinoKeyboard.h" // this is for the modified arduino HID IKeyboard::IKeyboard(void) { //nothing } void IKeyboard::Begin(void) { Keyboard.begin(); } void IKeyboard::End(void) { Keyboard.end(); } void IKeyboard::Press(byte k) { Keyboard.press(k); KeyState[k] = true; } void IKeyboard::Release(byte k) { KeyState[k] = false; Keyboard.release(k); } void IKeyboard::SetNKRO(byte mode) { Keyboard.setNKROMode(mode); } uint8_t IKeyboard::GetNKRO(void) { return Keyboard.getNKROMode(); } void IKeyboard::ReleaseAll(void) { Keyboard.releaseAll(); for (short i = 0; i < 256; i++) { KeyState[i] = false; } } IKeyboard AnimusKeyboard; <|endoftext|>
<commit_before>#pragma once #include <functional> #include <system_error> //============================================================================= namespace riak { namespace transport { //============================================================================= /*! * Indicates to the connection pool that the associated request has ended, whether successfully * or otherwise. The connection pool may cancel any ongoing requests by the mechanism it * wishes. Following the exercise of a cancel option, the connection pool guarantees it * will make no further callbacks related to the associated request, and no callback will * be made as part of the exercise. * * The given boolean parameter is a "dirty" bit. It will be set to "true" if the request * is being cancelled before complete and orderly termination. In all other cases, the * connection used to make the request may be reused. * * This signal must be idempotent. */ typedef std::function<void(bool)> option_to_terminate_request; /*! * A callback used to deliver a response with an error code. The error code must evaluate * to false unless the transport encountered an error during receive. */ typedef std::function<void(std::error_code, std::size_t, const std::string&)> response_handler; /*! * Dispatches the given request at the next available opportunity. This function * may optionally return immediately, constituting asynchronous behavior. * * \param r is an opaque binary blob to be transmitted to the server. * \param h must always be called to indicate either failure or success, including upon * destruction of the connection pool prior to resolution of a request. Multiple calls * are permissible, and calls with empty payloads will affect timeouts. A conforming * implementation will deliver std::network_reset in case the transport is destroyed * before the request can be satisfied. */ typedef std::function<option_to_terminate_request(const std::string&, response_handler)> delivery_provider; //============================================================================= } // namespace transport } // namespace riak //============================================================================= <commit_msg>Clarify a documentation comment.<commit_after>#pragma once #include <functional> #include <system_error> //============================================================================= namespace riak { namespace transport { //============================================================================= /*! * Indicates to the connection pool that the associated request has ended, whether successfully * or otherwise. The connection pool may cancel any ongoing requests by the mechanism it * wishes. Following the exercise of a cancel option, the connection pool guarantees it * will make no further callbacks related to the associated request, and no callback will * be made as part of the exercise. * * The given boolean parameter is a "dirty" bit. It will be set to "true" if the request * is being cancelled before complete and orderly termination. In all other cases, the * connection used to make the request may be reused. * * This signal must be idempotent. */ typedef std::function<void(bool)> option_to_terminate_request; /*! * A callback used to deliver a response with an error code. The error code must evaluate * to false unless the transport encountered an error during receive. */ typedef std::function<void(std::error_code, std::size_t, const std::string&)> response_handler; /*! * Dispatches the given request at the next available opportunity. This function * may optionally return immediately, constituting asynchronous behavior. * * \param request_data is an opaque binary blob to be transmitted to the server. * \param on_result must always be called to indicate either failure or success, including upon * destruction of the connection pool prior to resolution of a request. Multiple calls * are permissible, and calls with empty payloads will affect timeouts. A conforming * implementation will deliver std::network_reset in case the transport is destroyed * before the request can be satisfied. */ typedef std::function<option_to_terminate_request( const std::string& request_data, response_handler on_result)> delivery_provider; //============================================================================= } // namespace transport } // namespace riak //============================================================================= <|endoftext|>
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/runtime/dart_plugin_registrant.h" #include <string> #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/logging/dart_invoke.h" namespace flutter { const char* dart_plugin_registrant_library_override = nullptr; bool InvokeDartPluginRegistrantIfAvailable(Dart_Handle library_handle) { TRACE_EVENT0("flutter", "InvokeDartPluginRegistrantIfAvailable"); // The Dart plugin registrant is a static method with signature `void // register()` within the class `_PluginRegistrant` generated by the Flutter // tool. // // This method binds a plugin implementation to their platform // interface based on the configuration of the app's pubpec.yaml, and the // plugin's pubspec.yaml. // // Since this method may or may not be defined, check if the class is defined // in the default library before calling the method. Dart_Handle plugin_registrant = ::Dart_GetClass(library_handle, tonic::ToDart("_PluginRegistrant")); if (Dart_IsError(plugin_registrant)) { return false; } tonic::LogIfError(tonic::DartInvokeField(plugin_registrant, "register", {})); return true; } bool FindAndInvokeDartPluginRegistrant() { std::string library_name = dart_plugin_registrant_library_override == nullptr ? "package:flutter/src/dart_plugin_registrant.dart" : dart_plugin_registrant_library_override; Dart_Handle library = Dart_LookupLibrary(tonic::ToDart(library_name)); if (Dart_IsError(library)) { return false; } Dart_Handle registrant_file_uri = Dart_GetField(library, tonic::ToDart("dartPluginRegistrantLibrary")); if (Dart_IsError(registrant_file_uri)) { // TODO(gaaclarke): Find a way to remove this branch so the field is // required. I couldn't get it working with unit tests. return InvokeDartPluginRegistrantIfAvailable(library); } std::string registrant_file_uri_string = tonic::DartConverter<std::string>::FromDart(registrant_file_uri); if (registrant_file_uri_string.empty()) { FML_LOG(ERROR) << "Unexpected empty dartPluginRegistrantLibrary."; return false; } Dart_Handle registrant_library = Dart_LookupLibrary(registrant_file_uri); return InvokeDartPluginRegistrantIfAvailable(registrant_library); } } // namespace flutter <commit_msg>Removed error log statement for dart plugin registrant. (#32321)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/runtime/dart_plugin_registrant.h" #include <string> #include "flutter/fml/logging.h" #include "flutter/fml/trace_event.h" #include "third_party/tonic/converter/dart_converter.h" #include "third_party/tonic/logging/dart_invoke.h" namespace flutter { const char* dart_plugin_registrant_library_override = nullptr; bool InvokeDartPluginRegistrantIfAvailable(Dart_Handle library_handle) { TRACE_EVENT0("flutter", "InvokeDartPluginRegistrantIfAvailable"); // The Dart plugin registrant is a static method with signature `void // register()` within the class `_PluginRegistrant` generated by the Flutter // tool. // // This method binds a plugin implementation to their platform // interface based on the configuration of the app's pubpec.yaml, and the // plugin's pubspec.yaml. // // Since this method may or may not be defined, check if the class is defined // in the default library before calling the method. Dart_Handle plugin_registrant = ::Dart_GetClass(library_handle, tonic::ToDart("_PluginRegistrant")); if (Dart_IsError(plugin_registrant)) { return false; } tonic::LogIfError(tonic::DartInvokeField(plugin_registrant, "register", {})); return true; } bool FindAndInvokeDartPluginRegistrant() { std::string library_name = dart_plugin_registrant_library_override == nullptr ? "package:flutter/src/dart_plugin_registrant.dart" : dart_plugin_registrant_library_override; Dart_Handle library = Dart_LookupLibrary(tonic::ToDart(library_name)); if (Dart_IsError(library)) { return false; } Dart_Handle registrant_file_uri = Dart_GetField(library, tonic::ToDart("dartPluginRegistrantLibrary")); if (Dart_IsError(registrant_file_uri)) { // TODO(gaaclarke): Find a way to remove this branch so the field is // required. I couldn't get it working with unit tests. return InvokeDartPluginRegistrantIfAvailable(library); } std::string registrant_file_uri_string = tonic::DartConverter<std::string>::FromDart(registrant_file_uri); if (registrant_file_uri_string.empty()) { return false; } Dart_Handle registrant_library = Dart_LookupLibrary(registrant_file_uri); return InvokeDartPluginRegistrantIfAvailable(registrant_library); } } // namespace flutter <|endoftext|>
<commit_before>// Copyright (c) 2012, Ilya Arefiev <arefiev.id@gmail.com> // 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 // 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 <iostream> #include "libqtlogger_common.h" #include "libqtlogger.h" QtLogger::QtLogger() : currentLevel( LL_DEBUG ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << std::endl; #endif ll_string[ LL_EROR ].sprintf( "ERROR" ); ll_string[ LL_WARNING ].sprintf( "WARN " ); ll_string[ LL_LOG ].sprintf( "LOG " ); ll_string[ LL_DEBUG ].sprintf( "DEBUG" ); ll_string[ LL_STUB ].sprintf( " " ); this->start(); } QtLogger::~QtLogger() { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << std::endl; #endif mqMutex.lock(); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " messageQueue size: " << messageQueue.size() << std::endl; #endif messageQueue.clear(); shutdown = true; mqWait.wakeAll(); mqMutex.unlock(); this->wait(); while ( !writersList.isEmpty() ) { delete( writersList.front() ); writersList.pop_front(); } } QtLogger& QtLogger::getInstance() { static QtLogger _instance; return _instance; } void QtLogger::foo( void* bar ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << std::endl; #endif } QString QtLogger::describeLogLevel(QtLogger::LOG_LEVEL level) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " level: " << level << " (" << ll_string[((level>=0 && level<=LL_STUB)?level:LL_STUB)].toStdString() << ")" << std::endl; #endif return ll_string[ ((level>=0 && level<=LL_STUB) ? level : LL_STUB) ]; } /** * */ void QtLogger::run() { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " start" << std::endl; #endif QString message; while ( !shutdown ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " waiting" << std::endl; #endif mqMutex.lock(); mqWait.wait( &mqMutex ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " woken" << std::endl; #endif if ( !messageQueue.isEmpty() ) { message = messageQueue.dequeue(); } #if ENABLE_LOGGER_LOGGING else { std::clog << FUNCTION_NAME << " queue already empty" << std::endl; } #endif mqMutex.unlock(); while ( !message.isEmpty() ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " pass message \"" << message.toStdString() << "\" to writers" << std::endl; #endif wlMutex.lock(); if ( !writersList.isEmpty() ) { QListIterator<LogWriterInterface*> iter( writersList ); while ( iter.hasNext() ) { LogWriterInterface* writer = iter.next(); bool status = writer->writeLog( message ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << QString().sprintf( " writer @ %p returned %c", writer, (status?'t':'F') ).toStdString() << std::endl; #endif } } wlMutex.unlock(); mqMutex.lock(); if ( !messageQueue.isEmpty() ) { message = messageQueue.dequeue(); } else { message.clear(); } mqMutex.unlock(); } } #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " end" << std::endl; #endif this->quit(); } bool QtLogger::addWriter( LogWriterInterface* writer ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " writer: " << (writer?(QString().sprintf( "%p", writer ).toStdString()):"(null)") << std::endl; #endif if ( !writer ) { #if ENABLE_LOGGER_LOGGING std::cerr << FUNCTION_NAME << " NULL writer" << std::endl; #endif return false; } wlMutex.lock(); writersList.append( writer ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " wl.size: " << writersList.size() << std::endl; #endif wlMutex.unlock(); return true; } /** * */ void QtLogger::log(LOG_LEVEL level, QString message) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " lvl: " << ll_string[ (level>=LL_STUB || level<0)?LL_STUB:level ].toStdString() << " msg: \"" << message.toStdString() << "\"" << std::endl; #endif if ( level >= LL_STUB || level < 0 ) { #if ENABLE_LOGGER_LOGGING std::cerr << FUNCTION_NAME << "incorrect log level" << std::endl; #endif return; } if ( level > currentLevel ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " log message rejected: currentLevel: " << ll_string[ currentLevel ].toStdString() << std::endl; #endif return; } mqMutex.lock(); messageQueue.enqueue( message ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " message queue size: " << messageQueue.size() << std::endl; #endif mqWait.wakeAll(); mqMutex.unlock(); return; } <commit_msg>allow logger thread to cleanup messageQueue on destruction<commit_after>// Copyright (c) 2012, Ilya Arefiev <arefiev.id@gmail.com> // 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 // 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 <iostream> #include "libqtlogger_common.h" #include "libqtlogger.h" QtLogger::QtLogger() : currentLevel( LL_DEBUG ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << std::endl; #endif ll_string[ LL_EROR ].sprintf( "ERROR" ); ll_string[ LL_WARNING ].sprintf( "WARN " ); ll_string[ LL_LOG ].sprintf( "LOG " ); ll_string[ LL_DEBUG ].sprintf( "DEBUG" ); ll_string[ LL_STUB ].sprintf( " " ); this->start(); } QtLogger::~QtLogger() { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << std::endl; #endif mqMutex.lock(); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " messageQueue size: " << messageQueue.size() << std::endl; #endif shutdown = true; mqWait.wakeAll(); mqMutex.unlock(); this->wait(); while ( !writersList.isEmpty() ) { delete( writersList.front() ); writersList.pop_front(); } } QtLogger& QtLogger::getInstance() { static QtLogger _instance; return _instance; } void QtLogger::foo( void* bar ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << std::endl; #endif } QString QtLogger::describeLogLevel(QtLogger::LOG_LEVEL level) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " level: " << level << " (" << ll_string[((level>=0 && level<=LL_STUB)?level:LL_STUB)].toStdString() << ")" << std::endl; #endif return ll_string[ ((level>=0 && level<=LL_STUB) ? level : LL_STUB) ]; } /** * */ void QtLogger::run() { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " start" << std::endl; #endif QString message; while ( !shutdown ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " waiting" << std::endl; #endif mqMutex.lock(); mqWait.wait( &mqMutex ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " woken" << std::endl; #endif if ( !messageQueue.isEmpty() ) { message = messageQueue.dequeue(); } #if ENABLE_LOGGER_LOGGING else { std::clog << FUNCTION_NAME << " queue already empty" << std::endl; } #endif mqMutex.unlock(); while ( !message.isEmpty() ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " pass message \"" << message.toStdString() << "\" to writers" << std::endl; #endif wlMutex.lock(); if ( !writersList.isEmpty() ) { QListIterator<LogWriterInterface*> iter( writersList ); while ( iter.hasNext() ) { LogWriterInterface* writer = iter.next(); bool status = writer->writeLog( message ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << QString().sprintf( " writer @ %p returned %c", writer, (status?'t':'F') ).toStdString() << std::endl; #endif } } wlMutex.unlock(); mqMutex.lock(); if ( !messageQueue.isEmpty() ) { message = messageQueue.dequeue(); } else { message.clear(); } mqMutex.unlock(); } } #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " end" << std::endl; #endif this->quit(); } bool QtLogger::addWriter( LogWriterInterface* writer ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " writer: " << (writer?(QString().sprintf( "%p", writer ).toStdString()):"(null)") << std::endl; #endif if ( !writer ) { #if ENABLE_LOGGER_LOGGING std::cerr << FUNCTION_NAME << " NULL writer" << std::endl; #endif return false; } wlMutex.lock(); writersList.append( writer ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " wl.size: " << writersList.size() << std::endl; #endif wlMutex.unlock(); return true; } /** * */ void QtLogger::log(LOG_LEVEL level, QString message) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " lvl: " << ll_string[ (level>=LL_STUB || level<0)?LL_STUB:level ].toStdString() << " msg: \"" << message.toStdString() << "\"" << std::endl; #endif if ( level >= LL_STUB || level < 0 ) { #if ENABLE_LOGGER_LOGGING std::cerr << FUNCTION_NAME << "incorrect log level" << std::endl; #endif return; } if ( level > currentLevel ) { #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " log message rejected: currentLevel: " << ll_string[ currentLevel ].toStdString() << std::endl; #endif return; } mqMutex.lock(); messageQueue.enqueue( message ); #if ENABLE_LOGGER_LOGGING std::clog << FUNCTION_NAME << " message queue size: " << messageQueue.size() << std::endl; #endif mqWait.wakeAll(); mqMutex.unlock(); return; } <|endoftext|>
<commit_before>#include "simulation/SerialSimulation.hpp" //#include <omp.h> namespace Simulation { SerialSimulation::SerialSimulation(const Initialization::SimulationPlan & in, const vector<std::shared_ptr<Solver::ISolver>> & solvers) : AbstractSimulation(in,solvers) { } SerialSimulation::~SerialSimulation() { } void SerialSimulation::simulate() { bool_type running; //MF only set, not used size_type iterationCount = 0; const vector<shared_ptr<Solver::ISolver>>& solver = getSolver(); std::vector<size_type> numSteps(solver.size(),15); size_type tmpStepCount; double s (0.0) , e (0.0); //s = omp_get_wtime(); while (running && getMaxIterations() > ++iterationCount) { running = false; for (size_type i = 0; i < solver.size(); ++i) { if((tmpStepCount = solver[i]->solve(numSteps[i])) == std::numeric_limits<size_type>::max()) { LOGGER_WRITE("Abort simulation at " + to_string(solver[i]->getCurrentTime()) , Util::LC_SOLVER, Util::LL_ERROR); return; } if(tmpStepCount < numSteps[i]) --numSteps[i]; else ++numSteps[i]; //LOGGER_WRITE("(" + to_string(i) + ") numSteps: " + to_string(numSteps[i]),Util::LC_SOLVER, Util::LL_ERROR); if (solver[i]->getCurrentTime() < getSimulationEndTime()) running = true; else LOGGER_WRITE("(" + to_string(i) + ") Stopping at " + to_string(solver[i]->getCurrentTime()), Util::LC_SOLVER,Util::LL_DEBUG); } } //e = omp_get_wtime(); LOGGER_WRITE("thread 0 time: " + to_string(e - s), Util::LC_SOLVER, Util::LL_INFO); } string_type SerialSimulation::getSimulationType() const { return "serial"; } } /* namespace Simulation */ <commit_msg>Make the boolean variable a bool<commit_after>#include "simulation/SerialSimulation.hpp" //#include <omp.h> namespace Simulation { SerialSimulation::SerialSimulation(const Initialization::SimulationPlan & in, const vector<std::shared_ptr<Solver::ISolver>> & solvers) : AbstractSimulation(in,solvers) { } SerialSimulation::~SerialSimulation() { } void SerialSimulation::simulate() { bool running; size_type iterationCount = 0; const vector<shared_ptr<Solver::ISolver>>& solver = getSolver(); std::vector<size_type> numSteps(solver.size(),15); size_type tmpStepCount; double s (0.0) , e (0.0); //s = omp_get_wtime(); while (running && getMaxIterations() > ++iterationCount) { running = false; for (size_type i = 0; i < solver.size(); ++i) { if((tmpStepCount = solver[i]->solve(numSteps[i])) == std::numeric_limits<size_type>::max()) { LOGGER_WRITE("Abort simulation at " + to_string(solver[i]->getCurrentTime()) , Util::LC_SOLVER, Util::LL_ERROR); return; } if(tmpStepCount < numSteps[i]) --numSteps[i]; else ++numSteps[i]; //LOGGER_WRITE("(" + to_string(i) + ") numSteps: " + to_string(numSteps[i]),Util::LC_SOLVER, Util::LL_ERROR); if (solver[i]->getCurrentTime() < getSimulationEndTime()) running = true; else LOGGER_WRITE("(" + to_string(i) + ") Stopping at " + to_string(solver[i]->getCurrentTime()), Util::LC_SOLVER,Util::LL_DEBUG); } } //e = omp_get_wtime(); LOGGER_WRITE("thread 0 time: " + to_string(e - s), Util::LC_SOLVER, Util::LL_INFO); } string_type SerialSimulation::getSimulationType() const { return "serial"; } } /* namespace Simulation */ <|endoftext|>
<commit_before>#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(),(x).end() using namespace std; const vector<int> const_num = {5, 3, 2, 1}; int N; vector<int> v; string res; vector<int> memo; vector<string> memor; map<vector<int>,int> se; void dfs(int s, int c) { if (c + 1 < (int)v.size()) return; if (c < 0) return; if (c == 0 && (int)v.size() == 1) { int num = v[0]; if (0 <= num && num <= N && memo[num] == -1) { memo[num] = s; memor[num] = res; } return; } if (se[v] >= c) return; se[v] = c; auto const_process = [](int s, int c, char n, string& res, vector<int>& v){ res.push_back(n); dfs(s, c); v.pop_back(); res.pop_back(); }; for (int i : const_num) { v.push_back(i); const_process(s, c - i, '0' + i, res, v); } if (1 <= (int)v.size()) { int num = v.back(); v.push_back(num); const_process(s, c - 1, 'd', res, v); } auto binary_pop = [](vector<int>& v) -> tuple<int, int> { int lhs = v[v.size() - 2]; int rhs = v[v.size() - 1]; v.pop_back(); v.pop_back(); return make_tuple(lhs, rhs); }; auto binary_process = [](int s, int c, int n, char op, string& res, vector<int>& v){ v.push_back(n); res.push_back(op); dfs(s, c); }; auto binary_push = [](int lhs, int rhs, string& res, vector<int>& v){ v.pop_back(); v.push_back(lhs); v.push_back(rhs); res.pop_back(); }; if (2 <= (int)v.size()) { int lhs = 0, rhs = 0; tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, lhs + rhs, '+', res, v); binary_push(lhs, rhs, res, v); tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, lhs * rhs > 3e4 ? 0 : lhs * rhs, '*', res, v); binary_push(lhs, rhs, res, v); tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, lhs - rhs, '-', res, v); binary_push(lhs, rhs, res, v); tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, rhs == 0 ? 0 : lhs / rhs, '/', res, v); binary_push(lhs, rhs, res, v); /* tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, rhs == 0 ? 0 : lhs % rhs, '%', res, v); binary_push(lhs, rhs, res, v); */ } } int main() { N = 100000; memo.assign(N+1, -1); memor.resize(N+1); int depth = 0; for (int n = 1; n <= N; ++n) { while (memo[n] == -1) { if (n > 100 && depth == memo[n-1] + 2) { memo[n] = memo[n-1] + 2; memor[n] = memor[n-1] + "1+"; } else if (n > 100 && depth == memo[n-2] + 3) { memo[n] = memo[n-2] + 3; memor[n] = memor[n-2] + "2+"; } else if (n > 100 && depth == memo[n+1] + 2) { memo[n] = memo[n+1] + 2; memor[n] = memor[n+1] + "1-"; } else if (n > 100 && depth == memo[n+2] + 3) { memo[n] = memo[n+2] + 3; memor[n] = memor[n+2] + "2-"; } else { if (depth == 22) break; cerr << "DEPTH : " << depth << endl; v.clear(); res.clear(); dfs(depth, depth); ++depth; } } cout << n << "\t"; if (memo[n] == -1) { cout << "NULL" << endl; } else { cout << memo[n] << "\t"; cout << memor[n] << endl; } } return 0; } <commit_msg>bug fix<commit_after>#include <bits/stdc++.h> #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(),(x).end() using namespace std; const vector<int> const_num = {5, 3, 2, 1}; int N; vector<int> v; string res; vector<int> memo; vector<string> memor; map<vector<int>,int> se; void dfs(int s, int c) { if (c + 1 < (int)v.size()) return; if (c < 0) return; if (c == 0 && (int)v.size() == 1) { int num = v[0]; if (0 <= num && num <= N && memo[num] == -1) { memo[num] = s; memor[num] = res; } return; } if (se[v] >= c) return; se[v] = c; auto const_process = [](int s, int c, char n, string& res, vector<int>& v){ res.push_back(n); dfs(s, c); v.pop_back(); res.pop_back(); }; for (int i : const_num) { v.push_back(i); const_process(s, c - i, '0' + i, res, v); } if (1 <= (int)v.size()) { int num = v.back(); v.push_back(num); const_process(s, c - 1, 'd', res, v); } auto binary_pop = [](vector<int>& v) -> tuple<int, int> { int lhs = v[v.size() - 2]; int rhs = v[v.size() - 1]; v.pop_back(); v.pop_back(); return make_tuple(lhs, rhs); }; auto binary_process = [](int s, int c, int n, char op, string& res, vector<int>& v){ v.push_back(n); res.push_back(op); dfs(s, c); }; auto binary_push = [](int lhs, int rhs, string& res, vector<int>& v){ v.pop_back(); v.push_back(lhs); v.push_back(rhs); res.pop_back(); }; if (2 <= (int)v.size()) { int lhs = 0, rhs = 0; tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, lhs + rhs, '+', res, v); binary_push(lhs, rhs, res, v); tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, abs((long long)lhs * rhs) > 1e9 ? 0 : lhs * rhs, '*', res, v); binary_push(lhs, rhs, res, v); tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, lhs - rhs, '-', res, v); binary_push(lhs, rhs, res, v); tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, rhs == 0 ? 0 : lhs / rhs, '/', res, v); binary_push(lhs, rhs, res, v); /* tie(lhs, rhs) = binary_pop(v); binary_process(s, c - 1, rhs == 0 ? 0 : lhs % rhs, '%', res, v); binary_push(lhs, rhs, res, v); */ } } int main() { N = 1000; memo.assign(N+1, -1); memor.resize(N+1); int depth = 0; for (int n = 1; n <= N; ++n) { while (memo[n] == -1) { if (n > 100 && depth == memo[n-1] + 2) { memo[n] = memo[n-1] + 2; memor[n] = memor[n-1] + "1+"; } else if (n > 100 && depth == memo[n-2] + 3) { memo[n] = memo[n-2] + 3; memor[n] = memor[n-2] + "2+"; } else if (n > 100 && depth == memo[n+1] + 2) { memo[n] = memo[n+1] + 2; memor[n] = memor[n+1] + "1-"; } else if (n > 100 && depth == memo[n+2] + 3) { memo[n] = memo[n+2] + 3; memor[n] = memor[n+2] + "2-"; } else { if (depth == 23) break; cerr << "DEPTH : " << depth << endl; v.clear(); res.clear(); dfs(depth, depth); ++depth; } } cout << n << "\t"; if (memo[n] == -1) { cout << "NULL" << endl; } else { cout << memo[n] << "\t"; cout << memor[n] << endl; } } return 0; } <|endoftext|>
<commit_before>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "Transform.h" #include "ControlFlow.h" namespace { using RegMap = transform::RegMap; void remap_debug(DexDebugInstruction& dbgop, const RegMap& reg_map) { switch (dbgop.opcode()) { case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_END_LOCAL: case DBG_RESTART_LOCAL: { auto it = reg_map.find(dbgop.uvalue()); if (it == reg_map.end()) return; dbgop.set_uvalue(it->second); break; } default: break; } } void remap_dest(IRInstruction* inst, const RegMap& reg_map) { if (!inst->dests_size()) return; auto it = reg_map.find(inst->dest()); if (it == reg_map.end()) return; inst->set_dest(it->second); } void remap_srcs(IRInstruction* inst, const RegMap& reg_map) { for (unsigned i = 0; i < inst->srcs_size(); i++) { auto it = reg_map.find(inst->src(i)); if (it == reg_map.end()) continue; inst->set_src(i, it->second); } } } // anonymous namespace namespace transform { void remap_registers(IRInstruction* insn, const RegMap& reg_map) { remap_dest(insn, reg_map); remap_srcs(insn, reg_map); if (opcode::has_range(insn->opcode())) { auto it = reg_map.find(insn->range_base()); if (it != reg_map.end()) { insn->set_range_base(it->second); } } } void remap_registers(MethodItemEntry& mei, const RegMap& reg_map) { switch (mei.type) { case MFLOW_OPCODE: remap_registers(mei.insn, reg_map); break; case MFLOW_DEBUG: remap_debug(*mei.dbgop, reg_map); break; default: break; } } void remap_registers(IRCode* code, const RegMap& reg_map) { for (auto& mei : *code) { remap_registers(mei, reg_map); } } static size_t remove_block(IRCode* code, Block* b) { size_t insns_removed{0}; for (auto& mei : InstructionIterable(b)) { code->remove_opcode(mei.insn); ++insns_removed; } return insns_removed; } void visit(Block* b, std::unordered_set<Block*>& visited) { if (visited.find(b) != visited.end()) { return; } visited.emplace(b); for (auto& s : b->succs()) { visit(s, visited); } } void remove_succ_edges(Block* b, ControlFlowGraph* cfg) { std::vector<std::pair<Block*, Block*>> remove_edges; for (auto& s : b->succs()) { remove_edges.emplace_back(b, s); } for (auto& p : remove_edges) { cfg->remove_all_edges(p.first, p.second); } } size_t remove_unreachable_blocks(IRCode* code) { auto& cfg = code->cfg(); auto& blocks = cfg.blocks(); size_t insns_removed{0}; // remove unreachable blocks std::unordered_set<Block*> visited; visit(blocks.at(0), visited); for (size_t i = 1; i < blocks.size(); ++i) { auto& b = blocks.at(i); if (visited.find(b) != visited.end()) { continue; } // Remove all successor edges. Note that we don't need to try and remove // predecessors since by definition, unreachable blocks have no preds remove_succ_edges(b, &cfg); insns_removed += remove_block(code, b); } return insns_removed; } MethodItemEntry* find_active_catch(IRCode* code, FatMethod::iterator pos) { while (++pos != code->end() && pos->type != MFLOW_TRY) ; return pos != code->end() && pos->tentry->type == TRY_END ? pos->tentry->catch_start : nullptr; } // delete old_block and reroute its predecessors to new_block // // if new_block is null, just delete old_block and don't reroute void replace_block(IRCode* code, Block* old_block, Block* new_block) { const ControlFlowGraph& cfg = code->cfg(); std::vector<MethodItemEntry*> will_move; if (new_block != nullptr) { // make a copy of the targets we're going to move for (MethodItemEntry& mie : *old_block) { if (mie.type == MFLOW_TARGET) { will_move.push_back(new MethodItemEntry(mie.target)); } } } // delete old_block for (auto it = old_block->begin(); it != old_block->end(); it++) { switch (it->type) { case MFLOW_OPCODE: code->remove_opcode(it); break; case MFLOW_TARGET: it->type = MFLOW_FALLTHROUGH; it->throwing_mie = nullptr; if (new_block == nullptr) { delete it->target; } // else, new_block takes ownership of the targets break; default: break; } } if (new_block != nullptr) { for (auto mie : will_move) { // insert the branch target at the beginning of new_block // and make sure `m_begin` and `m_end`s point to the right places Block* before = cfg.find_block_that_ends_here(new_block->m_begin); new_block->m_begin = code->insert_before(new_block->begin(), *mie); if (before != nullptr) { before->m_end = new_block->m_begin; } } } } } // namespace transform <commit_msg>make transform::visit non-recursive<commit_after>/** * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "Transform.h" #include <stack> #include "ControlFlow.h" namespace { using RegMap = transform::RegMap; void remap_debug(DexDebugInstruction& dbgop, const RegMap& reg_map) { switch (dbgop.opcode()) { case DBG_START_LOCAL: case DBG_START_LOCAL_EXTENDED: case DBG_END_LOCAL: case DBG_RESTART_LOCAL: { auto it = reg_map.find(dbgop.uvalue()); if (it == reg_map.end()) return; dbgop.set_uvalue(it->second); break; } default: break; } } void remap_dest(IRInstruction* inst, const RegMap& reg_map) { if (!inst->dests_size()) return; auto it = reg_map.find(inst->dest()); if (it == reg_map.end()) return; inst->set_dest(it->second); } void remap_srcs(IRInstruction* inst, const RegMap& reg_map) { for (unsigned i = 0; i < inst->srcs_size(); i++) { auto it = reg_map.find(inst->src(i)); if (it == reg_map.end()) continue; inst->set_src(i, it->second); } } } // anonymous namespace namespace transform { void remap_registers(IRInstruction* insn, const RegMap& reg_map) { remap_dest(insn, reg_map); remap_srcs(insn, reg_map); if (opcode::has_range(insn->opcode())) { auto it = reg_map.find(insn->range_base()); if (it != reg_map.end()) { insn->set_range_base(it->second); } } } void remap_registers(MethodItemEntry& mei, const RegMap& reg_map) { switch (mei.type) { case MFLOW_OPCODE: remap_registers(mei.insn, reg_map); break; case MFLOW_DEBUG: remap_debug(*mei.dbgop, reg_map); break; default: break; } } void remap_registers(IRCode* code, const RegMap& reg_map) { for (auto& mei : *code) { remap_registers(mei, reg_map); } } static size_t remove_block(IRCode* code, Block* b) { size_t insns_removed{0}; for (auto& mei : InstructionIterable(b)) { code->remove_opcode(mei.insn); ++insns_removed; } return insns_removed; } void visit(Block* start, std::unordered_set<Block*>& visited) { std::stack<Block*> to_visit; to_visit.push(start); while (!to_visit.empty()) { Block* b = to_visit.top(); to_visit.pop(); if (visited.find(b) != visited.end()) { continue; } visited.emplace(b); for (auto& s : b->succs()) { to_visit.push(s); } } } void remove_succ_edges(Block* b, ControlFlowGraph* cfg) { std::vector<std::pair<Block*, Block*>> remove_edges; for (auto& s : b->succs()) { remove_edges.emplace_back(b, s); } for (auto& p : remove_edges) { cfg->remove_all_edges(p.first, p.second); } } size_t remove_unreachable_blocks(IRCode* code) { auto& cfg = code->cfg(); auto& blocks = cfg.blocks(); size_t insns_removed{0}; // remove unreachable blocks std::unordered_set<Block*> visited; visit(blocks.at(0), visited); for (size_t i = 1; i < blocks.size(); ++i) { auto& b = blocks.at(i); if (visited.find(b) != visited.end()) { continue; } // Remove all successor edges. Note that we don't need to try and remove // predecessors since by definition, unreachable blocks have no preds remove_succ_edges(b, &cfg); insns_removed += remove_block(code, b); } return insns_removed; } MethodItemEntry* find_active_catch(IRCode* code, FatMethod::iterator pos) { while (++pos != code->end() && pos->type != MFLOW_TRY) ; return pos != code->end() && pos->tentry->type == TRY_END ? pos->tentry->catch_start : nullptr; } // delete old_block and reroute its predecessors to new_block // // if new_block is null, just delete old_block and don't reroute void replace_block(IRCode* code, Block* old_block, Block* new_block) { const ControlFlowGraph& cfg = code->cfg(); std::vector<MethodItemEntry*> will_move; if (new_block != nullptr) { // make a copy of the targets we're going to move for (MethodItemEntry& mie : *old_block) { if (mie.type == MFLOW_TARGET) { will_move.push_back(new MethodItemEntry(mie.target)); } } } // delete old_block for (auto it = old_block->begin(); it != old_block->end(); it++) { switch (it->type) { case MFLOW_OPCODE: code->remove_opcode(it); break; case MFLOW_TARGET: it->type = MFLOW_FALLTHROUGH; it->throwing_mie = nullptr; if (new_block == nullptr) { delete it->target; } // else, new_block takes ownership of the targets break; default: break; } } if (new_block != nullptr) { for (auto mie : will_move) { // insert the branch target at the beginning of new_block // and make sure `m_begin` and `m_end`s point to the right places Block* before = cfg.find_block_that_ends_here(new_block->m_begin); new_block->m_begin = code->insert_before(new_block->begin(), *mie); if (before != nullptr) { before->m_end = new_block->m_begin; } } } } } // namespace transform <|endoftext|>
<commit_before>#include <iostream> #include "TinyCL.hpp" int main() { // GPUのデバイスを取得する auto device = tcl::information.GetGPU(); // ソースコードのコンパイル tcl::CLSource source("test.cl", "test", tcl::SourceType::Text); // カーネル実行クラスの生成 tcl::CLExecute exec(source, device); // デバイスに渡すための配列を初期化 const size_t N = 10; std::vector<float> input(N); for (int i = 0; i < N; ++i) input[i] = i; // デバイス側のメモリを確保 tcl::CLReadWriteBuffer x(exec, input); // 並列実行したいカーネル(GPUクラスタ)の数を設定する // 1次元配列で,0からスタートし,N個の長さを持っていて,それをN個ごとに区切る auto settings = tcl::CLWorkGroupSettings(1, { 0 }, { N }, { N }).Optimize(device); // 引数を設定する exec.SetArg(x); // 設定を渡して実行 exec.Run(settings); // デバイスのメモリから,配列へ読み出す x.Read(input); // かくにん for (int i = 0; i < N; ++i) std::cout << i << "," << input[i] << std::endl; // TODO: 速度を取ってみたい char a; std::cin >> a; } <commit_msg>サンプルコードを短くする<commit_after>#include <iostream> #include "TinyCL.hpp" int main() { // GPUのデバイスを取得する auto device = tcl::information.GetGPU(); // ソースコードのコンパイル tcl::CLSource source("test.cl", "test", tcl::SourceType::Text); // カーネル実行クラスの生成 tcl::CLExecute exec(source, device); // デバイスに渡すための配列を初期化 const size_t N = 10; std::vector<float> input(N); for (int i = 0; i < N; ++i) input[i] = i; // デバイス側のメモリを確保 tcl::CLReadWriteBuffer x(exec, input); // 並列実行したいカーネル(GPUクラスタ)の数を設定する // 1次元配列で,0からスタートし,N個の長さを持っていて,それをN個ごとに区切る auto settings = tcl::CLWorkGroupSettings(1, { 0 }, { N }, { N }).Optimize(device); // 引数を設定して実行 exec.SetArg(x).Run(settings); // デバイスのメモリから,配列へ読み出す x.Read(input); // 中身が正しいかどうか確認する for (int i = 0; i < N; ++i) std::cout << i << "," << input[i] << std::endl; // TODO: 速度を取ってみたい char a; std::cin >> a; } <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Features.hpp> #include <DO/Graphics.hpp> #include <DO/ImageProcessing.hpp> using namespace DO; using namespace std; const bool draw_feature_center_only = false; const Rgb8& c = Cyan8; void check_affine_adaptation(const Image<unsigned char>& image, const OERegion& f) { int w = image.width(); int h = image.height(); display(image); f.draw(Blue8); Image<float> flt_image(image.convert<float>()); float r = 100; float patchSz = 2*r; Image<float> patch(w, h); patch.array().fill(0.f); OERegion rg(f); rg.center().fill(patchSz/2.f); rg.orientation() = 0.f; rg.shape_matrix() = Matrix2f::Identity()*4.f / (r*r); Matrix3d A(f.affinity().cast<double>()); cout << "A=\n" << A << endl; for (int y = 0; y < patchSz; ++y) { float v = 2*(y-r)/r; for (int x = 0; x < patchSz; ++x) { float u = 2*(x-r)/r; Point3d pp(u, v, 1.); pp = A*pp; Point2d p; p << pp(0), pp(1); if (p.x() < 0 || p.x() >= w || p.y() < 0 || p.y() >= h) continue; patch(x,y) = static_cast<float>(interpolate(flt_image, p)); } } Window w1 = active_window(); Window w2 = create_window(static_cast<int>(patchSz), static_cast<int>(patchSz)); set_active_window(w2); set_antialiasing(); display(patch); rg.draw(Blue8); millisleep(1000); close_window(w2); millisleep(40); set_active_window(w1); } void read_features(const Image<unsigned char>& image, const string& filepath) { cout << "Reading DoG features... " << endl; vector<OERegion> features; DescriptorMatrix<float> descriptors; cout << "Reading keypoints..." << endl; read_keypoints(features, descriptors, filepath); for (int i = 0; i < 10; ++i) check_affine_adaptation(image, features[i]); string ext = filepath.substr(filepath.find_last_of("."), filepath.size()); string name = filepath.substr(0, filepath.find_last_of(".")); string copy_filepath = name + "_copy" + ext; write_keypoints(features, descriptors, name + "_copy" + ext); vector<OERegion> features2; DescriptorMatrix<float> descriptors2; cout << "Checking written file..." << endl; read_keypoints(features2, descriptors2, copy_filepath); cout << "Printing the 10 first keypoints..." << endl; for(size_t i = 0; i < 10; ++i) cout << features[i] << endl; // Draw features. cout << "Drawing features... "; display(image); draw_oe_regions(features, Red8); cout << "done!" << endl; millisleep(1000); } GRAPHICS_MAIN_SIMPLE() { Image<unsigned char> I; load(I, src_path("obama_2.jpg")); set_active_window(create_window(I.width(), I.height())); set_antialiasing(active_window()); read_features(I, src_path("test.dogkey")); read_features(I, src_path("test.haraffkey")); read_features(I, src_path("test.mserkey")); return 0; }<commit_msg>MAINT: remove unused variable.<commit_after>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <DO/Features.hpp> #include <DO/Graphics.hpp> #include <DO/ImageProcessing.hpp> using namespace DO; using namespace std; const Rgb8& c = Cyan8; void check_affine_adaptation(const Image<unsigned char>& image, const OERegion& f) { int w = image.width(); int h = image.height(); display(image); f.draw(Blue8); Image<float> flt_image(image.convert<float>()); float r = 100; float patchSz = 2*r; Image<float> patch(w, h); patch.array().fill(0.f); OERegion rg(f); rg.center().fill(patchSz/2.f); rg.orientation() = 0.f; rg.shape_matrix() = Matrix2f::Identity()*4.f / (r*r); Matrix3d A(f.affinity().cast<double>()); cout << "A=\n" << A << endl; for (int y = 0; y < patchSz; ++y) { float v = 2*(y-r)/r; for (int x = 0; x < patchSz; ++x) { float u = 2*(x-r)/r; Point3d pp(u, v, 1.); pp = A*pp; Point2d p; p << pp(0), pp(1); if (p.x() < 0 || p.x() >= w || p.y() < 0 || p.y() >= h) continue; patch(x,y) = static_cast<float>(interpolate(flt_image, p)); } } Window w1 = active_window(); Window w2 = create_window(static_cast<int>(patchSz), static_cast<int>(patchSz)); set_active_window(w2); set_antialiasing(); display(patch); rg.draw(Blue8); millisleep(1000); close_window(w2); millisleep(40); set_active_window(w1); } void read_features(const Image<unsigned char>& image, const string& filepath) { cout << "Reading DoG features... " << endl; vector<OERegion> features; DescriptorMatrix<float> descriptors; cout << "Reading keypoints..." << endl; read_keypoints(features, descriptors, filepath); for (int i = 0; i < 10; ++i) check_affine_adaptation(image, features[i]); string ext = filepath.substr(filepath.find_last_of("."), filepath.size()); string name = filepath.substr(0, filepath.find_last_of(".")); string copy_filepath = name + "_copy" + ext; write_keypoints(features, descriptors, name + "_copy" + ext); vector<OERegion> features2; DescriptorMatrix<float> descriptors2; cout << "Checking written file..." << endl; read_keypoints(features2, descriptors2, copy_filepath); cout << "Printing the 10 first keypoints..." << endl; for(size_t i = 0; i < 10; ++i) cout << features[i] << endl; // Draw features. cout << "Drawing features... "; display(image); draw_oe_regions(features, Red8); cout << "done!" << endl; millisleep(1000); } GRAPHICS_MAIN_SIMPLE() { Image<unsigned char> I; load(I, src_path("obama_2.jpg")); set_active_window(create_window(I.width(), I.height())); set_antialiasing(active_window()); read_features(I, src_path("test.dogkey")); read_features(I, src_path("test.haraffkey")); read_features(I, src_path("test.mserkey")); return 0; }<|endoftext|>
<commit_before>#include "mex.h" #include "opencv_matlab_interop.h" #define PRINT_INPUTS void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { ASSERT_NUM_LHS_ARGS_EQ(1); ASSERT_NUM_ } <commit_msg>Prediction done, and apparently working. bam!<commit_after>#include "mex.h" #include "opencv_matlab_interop.h" #define PRINT_INPUTS void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { ASSERT_NUM_LHS_ARGS_EQUALS(1); ASSERT_NUM_RHS_ARGS_EQUALS(2); //retrieve the pointer to the random forest CvRTrees *forest = (CvRTrees *)unpack_pointer(prhs[0]); //get the data which we need to predict on into opencv format CvMat* dataMtx = matlab_matrix_to_opencv_matrix(prhs[1]); CvMat sample; //this is used to point to each row, one at a time int numSamples = dataMtx->rows; mexPrintf("predicting on %d samples\n", numSamples); mxArray* output = mxCreateDoubleMatrix(numSamples, 1, mxREAL); double *outputData = (double *)mxGetPr(output); // for (unsigned int i=0; i<numSamples; i++) { cvGetRow(dataMtx, &sample, i); outputData[i] = (double)forest->predict(&sample); } plhs[0] = output; cvReleaseMat(&dataMtx); } <|endoftext|>
<commit_before>#include "../SDP_Solver.hxx" // Create and initialize an SDPSolver for the given SDP and // SDP_Solver_Parameters SDP_Solver::SDP_Solver(const std::vector<boost::filesystem::path> &sdp_files, const SDP_Solver_Parameters &parameters) : sdp(sdp_files), parameters(parameters), x(sdp.schur_block_sizes), X(sdp.psd_matrix_block_sizes), y(sdp.dual_objective_b.Height(), 1), Y(X), primal_residues(X), // FIXME: Maybe we can use schur_block_sizes() instead of making a copy? dual_residues(x) { X.set_zero(); Y.set_zero(); for(auto &b : x.blocks) { Zero(b); } Zero(y); // X = \Omega_p I X.add_diagonal(parameters.initial_matrix_scale_primal); // Y = \Omega_d I Y.add_diagonal(parameters.initial_matrix_scale_dual); } <commit_msg>Use sdp.schur_block_sizes to setup SDP::dual_residues<commit_after>#include "../SDP_Solver.hxx" // Create and initialize an SDPSolver for the given SDP and // SDP_Solver_Parameters SDP_Solver::SDP_Solver(const std::vector<boost::filesystem::path> &sdp_files, const SDP_Solver_Parameters &parameters) : sdp(sdp_files), parameters(parameters), x(sdp.schur_block_sizes), X(sdp.psd_matrix_block_sizes), y(sdp.dual_objective_b.Height(), 1), Y(X), primal_residues(X), dual_residues(sdp.schur_block_sizes) { X.set_zero(); Y.set_zero(); for(auto &b : x.blocks) { Zero(b); } Zero(y); // X = \Omega_p I X.add_diagonal(parameters.initial_matrix_scale_primal); // Y = \Omega_d I Y.add_diagonal(parameters.initial_matrix_scale_dual); } <|endoftext|>
<commit_before>#include <hrl_phri_2011/pc_utils.h> int main(int argc, char **argv) { ros::init(argc, argv, "pub_head"); if(argc < 2 || argc > 5) { printf("Usage pub_head bag_file [topic] [frame] [rate]\n"); return 1; } // Load bag rosbag::Bag bag; bag.open(std::string(argv[1]), rosbag::bagmode::Read); rosbag::View view(bag, rosbag::TopicQuery("/stitched_head")); PCRGB::Ptr pc_head(new PCRGB()); BOOST_FOREACH(rosbag::MessageInstance const m, view) { sensor_msgs::PointCloud2::Ptr pc2 = m.instantiate<sensor_msgs::PointCloud2>(); pcl::fromROSMsg(*pc2, *pc_head); break; } if(argc >= 4) pc_head->header.frame_id = argv[3]; if(argc == 2) pubLoop(*pc_head, "/stitched_head"); else if(argc == 3) pubLoop(*pc_head, argv[2]); else if(argc == 5) pubLoop(*pc_head, argv[2], atof(argv[4])); return 0; } <commit_msg>Fixed pub_head problems.<commit_after>#include <hrl_phri_2011/pc_utils.h> int main(int argc, char **argv) { ros::init(argc, argv, "pub_head"); if(argc < 2 || argc > 5) { printf("Usage pub_head bag_file [topic] [frame] [rate]\n"); return 1; } // Load bag rosbag::Bag bag; bag.open(std::string(argv[1]), rosbag::bagmode::Read); rosbag::View view(bag); PCRGB::Ptr pc_head(new PCRGB()); BOOST_FOREACH(rosbag::MessageInstance const m, view) { sensor_msgs::PointCloud2::Ptr pc2 = m.instantiate<sensor_msgs::PointCloud2>(); pcl::fromROSMsg(*pc2, *pc_head); break; } if(argc == 2) pubLoop(*pc_head, "/stitched_head"); else if(argc == 3) pubLoop(*pc_head, std::string(argv[2])); else if(argc == 4) { pc_head->header.frame_id = std::string(argv[3]); pubLoop(*pc_head, std::string(argv[2])); } else if(argc == 5) { pc_head->header.frame_id = std::string(argv[3]); pubLoop(*pc_head, std::string(argv[2]), atof(argv[4])); } return 0; } <|endoftext|>
<commit_before>/* * camera.cpp * * Created on: 2016年11月28日 * Author: zhuqian */ #include "camera.h" #include "film.h" Camera::Camera(const Transform& c2w, Float shutterOpen, Float shutterEnd, Film * f, const Medium* medium) : film(f), cameraToWorld(c2w), shutterOpen(shutterOpen), shutterEnd( shutterEnd), medium(medium){ } float Camera::GenerateRayDifferential(const CameraSample &sample, RayDifferential *rd) const { float wt = GenerateRay(sample, rd); //生成x偏移射线 CameraSample sshift = sample; ++sshift.pFilm.x; Ray rx; float wtx = GenerateRay(sshift, &rx); if (wtx == 0) { return 0; } rd->ox = rx.o; rd->dx = rx.d; //生成y偏移射线 --sshift.pFilm.x; ++sshift.pFilm.y; Ray ry; float wty = GenerateRay(sshift, &ry); if (wty == 0) { return 0; } rd->oy = ry.o; rd->dy = ry.d; //设置射线为微分射线 rd->hasDifferential = true; rd->medium = medium; return wt; } Spectrum Camera::We(const Ray& ray, Point2f* rasterPos) const { Assert(false); LError<<"Camera::We is not implemented."; return 0; } void Camera::Pdf_We(const Ray& ray, Float* posPdf, Float* dirPdf) const { Assert(false); LError<<"Camera::Pdf_We is not implemented."; } Spectrum Camera::Sample_Wi(const Interaction& ref, const Point2f&sample, Vector3f* wi, Float* pdf, Point2f* rasterPos, VisibilityTester* tester) const { Assert(false); LError<<"Camera::Sample_Wi is not implemented."; return 0; } ProjectiveCamera::ProjectiveCamera(const Transform& c2w, const Transform& c2s, const Bound2f& screenWindow,Float shutterOpen, Float shutterEnd, Float lensr, Float focald, Film * f, const Medium* medium): Camera(c2w, shutterOpen, shutterEnd, f, medium) { _cameraToScreen = c2s; //投影矩阵 _lensRadius = lensr; _focalDistance = focald; //从底往上看1.把screen的原点挪到00位置,然后你懂得 _screenToRaster = Scale(Float(film->fullResolution.x), Float(film->fullResolution.y), 1.f) * Scale( 1.0f / (screenWindow.maxPoint.x - screenWindow.minPoint.x), 1.0f / (screenWindow.minPoint.y - screenWindow.maxPoint.y), 1.0f) * Translate( Vector3f(-screenWindow.minPoint.x, -screenWindow.maxPoint.y, 0.0f)); _rasterToScreen = Inverse(_screenToRaster); _rasterToCamera = Inverse(_cameraToScreen) * _rasterToScreen; } <commit_msg>修正相机中的float类型为Float类型<commit_after>/* * camera.cpp * * Created on: 2016年11月28日 * Author: zhuqian */ #include "camera.h" #include "film.h" Camera::Camera(const Transform& c2w, Float shutterOpen, Float shutterEnd, Film * f, const Medium* medium) : film(f), cameraToWorld(c2w), shutterOpen(shutterOpen), shutterEnd( shutterEnd), medium(medium){ } Float Camera::GenerateRayDifferential(const CameraSample &sample, RayDifferential *rd) const { Float wt = GenerateRay(sample, rd); //生成x偏移射线 CameraSample sshift = sample; ++sshift.pFilm.x; Ray rx; Float wtx = GenerateRay(sshift, &rx); if (wtx == 0) { return 0; } rd->ox = rx.o; rd->dx = rx.d; //生成y偏移射线 --sshift.pFilm.x; ++sshift.pFilm.y; Ray ry; Float wty = GenerateRay(sshift, &ry); if (wty == 0) { return 0; } rd->oy = ry.o; rd->dy = ry.d; //设置射线为微分射线 rd->hasDifferential = true; rd->medium = medium; return wt; } Spectrum Camera::We(const Ray& ray, Point2f* rasterPos) const { Assert(false); LError<<"Camera::We is not implemented."; return 0; } void Camera::Pdf_We(const Ray& ray, Float* posPdf, Float* dirPdf) const { Assert(false); LError<<"Camera::Pdf_We is not implemented."; } Spectrum Camera::Sample_Wi(const Interaction& ref, const Point2f&sample, Vector3f* wi, Float* pdf, Point2f* rasterPos, VisibilityTester* tester) const { Assert(false); LError<<"Camera::Sample_Wi is not implemented."; return 0; } ProjectiveCamera::ProjectiveCamera(const Transform& c2w, const Transform& c2s, const Bound2f& screenWindow,Float shutterOpen, Float shutterEnd, Float lensr, Float focald, Film * f, const Medium* medium): Camera(c2w, shutterOpen, shutterEnd, f, medium) { _cameraToScreen = c2s; //投影矩阵 _lensRadius = lensr; _focalDistance = focald; //从底往上看1.把screen的原点挪到00位置,然后你懂得 _screenToRaster = Scale(Float(film->fullResolution.x), Float(film->fullResolution.y), 1.f) * Scale( 1.0f / (screenWindow.maxPoint.x - screenWindow.minPoint.x), 1.0f / (screenWindow.minPoint.y - screenWindow.maxPoint.y), 1.0f) * Translate( Vector3f(-screenWindow.minPoint.x, -screenWindow.maxPoint.y, 0.0f)); _rasterToScreen = Inverse(_screenToRaster); _rasterToCamera = Inverse(_cameraToScreen) * _rasterToScreen; } <|endoftext|>
<commit_before>/** @copyright (C) 2017 Melexis N.V. 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 <M5Stack.h> #include <Wire.h> #include "MLX90640_I2C_Driver.h" void MLX90640_I2CInit() { } //Read a number of words from startAddress. Store into Data array. //Returns 0 if successful, -1 if error int MLX90640_I2CRead(uint8_t _deviceAddress, unsigned int startAddress, unsigned int nWordsRead, uint16_t *data) { //Caller passes number of 'unsigned ints to read', increase this to 'bytes to read' uint16_t bytesRemaining = nWordsRead * 2; //It doesn't look like sequential read works. Do we need to re-issue the address command each time? uint16_t dataSpot = 0; //Start at beginning of array //Setup a series of chunked I2C_BUFFER_LENGTH byte reads while (bytesRemaining > 0) { Wire.beginTransmission(_deviceAddress); Wire.write(startAddress >> 8); //MSB Wire.write(startAddress & 0xFF); //LSB if (Wire.endTransmission(false) != 7) //Do not release bus { Serial.println("No ack read"); return (0); //Sensor did not ACK } uint16_t numberOfBytesToRead = bytesRemaining; if (numberOfBytesToRead > I2C_BUFFER_LENGTH) numberOfBytesToRead = I2C_BUFFER_LENGTH; Wire.requestFrom((uint8_t)_deviceAddress, numberOfBytesToRead); if (Wire.available()) { for (uint16_t x = 0 ; x < numberOfBytesToRead / 2; x++) { //Store data into array data[dataSpot] = Wire.read() << 8; //MSB data[dataSpot] |= Wire.read(); //LSB dataSpot++; } } bytesRemaining -= numberOfBytesToRead; startAddress += numberOfBytesToRead / 2; } return (0); //Success } //Set I2C Freq, in kHz //MLX90640_I2CFreqSet(1000) sets frequency to 1MHz void MLX90640_I2CFreqSet(int freq) { //i2c.frequency(1000 * freq); Wire.setClock((long)1000 * freq); } //Write two bytes to a two byte address int MLX90640_I2CWrite(uint8_t _deviceAddress, unsigned int writeAddress, uint16_t data) { Wire.beginTransmission((uint8_t)_deviceAddress); Wire.write(writeAddress >> 8); //MSB Wire.write(writeAddress & 0xFF); //LSB Wire.write(data >> 8); //MSB Wire.write(data & 0xFF); //LSB if (Wire.endTransmission() != 0) { //Sensor did not ACK Serial.println("Error: Sensor did not ack"); return (-1); } uint16_t dataCheck; MLX90640_I2CRead(_deviceAddress, writeAddress, 1, &dataCheck); if (dataCheck != data) { //Serial.println("The write request didn't stick"); return -2; } return (0); //Success } <commit_msg>Update MLX90640_I2C_Driver.cpp (#117)<commit_after>/** @copyright (C) 2017 Melexis N.V. 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 <M5Stack.h> #include <Wire.h> #include "MLX90640_I2C_Driver.h" void MLX90640_I2CInit() { } //Read a number of words from startAddress. Store into Data array. //Returns 0 if successful, -1 if error int MLX90640_I2CRead(uint8_t _deviceAddress, unsigned int startAddress, unsigned int nWordsRead, uint16_t *data) { //Caller passes number of 'unsigned ints to read', increase this to 'bytes to read' uint16_t bytesRemaining = nWordsRead * 2; //It doesn't look like sequential read works. Do we need to re-issue the address command each time? uint16_t dataSpot = 0; //Start at beginning of array //Setup a series of chunked I2C_BUFFER_LENGTH byte reads while (bytesRemaining > 0) { Wire.beginTransmission(_deviceAddress); Wire.write(startAddress >> 8); //MSB Wire.write(startAddress & 0xFF); //LSB if (Wire.endTransmission(false) != 0) //Do not release bus { Serial.println("No ack read"); return (0); //Sensor did not ACK } uint16_t numberOfBytesToRead = bytesRemaining; if (numberOfBytesToRead > I2C_BUFFER_LENGTH) numberOfBytesToRead = I2C_BUFFER_LENGTH; Wire.requestFrom((uint8_t)_deviceAddress, numberOfBytesToRead); if (Wire.available()) { for (uint16_t x = 0 ; x < numberOfBytesToRead / 2; x++) { //Store data into array data[dataSpot] = Wire.read() << 8; //MSB data[dataSpot] |= Wire.read(); //LSB dataSpot++; } } bytesRemaining -= numberOfBytesToRead; startAddress += numberOfBytesToRead / 2; } return (0); //Success } //Set I2C Freq, in kHz //MLX90640_I2CFreqSet(1000) sets frequency to 1MHz void MLX90640_I2CFreqSet(int freq) { //i2c.frequency(1000 * freq); Wire.setClock((long)1000 * freq); } //Write two bytes to a two byte address int MLX90640_I2CWrite(uint8_t _deviceAddress, unsigned int writeAddress, uint16_t data) { Wire.beginTransmission((uint8_t)_deviceAddress); Wire.write(writeAddress >> 8); //MSB Wire.write(writeAddress & 0xFF); //LSB Wire.write(data >> 8); //MSB Wire.write(data & 0xFF); //LSB if (Wire.endTransmission() != 0) { //Sensor did not ACK Serial.println("Error: Sensor did not ack"); return (-1); } uint16_t dataCheck; MLX90640_I2CRead(_deviceAddress, writeAddress, 1, &dataCheck); if (dataCheck != data) { //Serial.println("The write request didn't stick"); return -2; } return (0); //Success } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "shape_datasource.hpp" #include "shape_featureset.hpp" #include "shape_index_featureset.hpp" #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/version.hpp> #include <boost/algorithm/string.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/debug.hpp> #include <mapnik/make_unique.hpp> #include <mapnik/util/fs.hpp> #include <mapnik/global.hpp> #include <mapnik/util/utf_conv_win.hpp> #include <mapnik/boolean.hpp> #include <mapnik/util/conversions.hpp> #include <mapnik/geom_util.hpp> #include <mapnik/timer.hpp> #include <mapnik/value_types.hpp> // stl #include <fstream> #include <sstream> #include <stdexcept> DATASOURCE_PLUGIN(shape_datasource) using mapnik::String; using mapnik::Double; using mapnik::Integer; using mapnik::Boolean; using mapnik::datasource_exception; using mapnik::filter_in_box; using mapnik::filter_at_point; using mapnik::attribute_descriptor; shape_datasource::shape_datasource(parameters const& params) : datasource (params), type_(datasource::Vector), file_length_(0), indexed_(false), row_limit_(*params.get<mapnik::value_integer>("row_limit",0)), desc_(shape_datasource::name(), *params.get<std::string>("encoding","utf-8")) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::init"); #endif boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw datasource_exception("Shape Plugin: missing <file> parameter"); boost::optional<std::string> base = params.get<std::string>("base"); if (base) shape_name_ = *base + "/" + *file; else shape_name_ = *file; boost::algorithm::ireplace_last(shape_name_,".shp",""); if (!mapnik::util::exists(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' does not exist"); } if (mapnik::util::is_directory(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' appears to be a directory not a file"); } if (!mapnik::util::exists(shape_name_ + ".dbf")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".dbf' does not exist"); } try { #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "shape_datasource::init(get_column_description)"); #endif std::unique_ptr<shape_io> shape_ref = std::make_unique<shape_io>(shape_name_); init(*shape_ref); for (int i=0;i<shape_ref->dbf().num_fields();++i) { field_descriptor const& fd = shape_ref->dbf().descriptor(i); std::string fld_name=fd.name_; switch (fd.type_) { case 'C': // character case 'D': // date desc_.add_descriptor(attribute_descriptor(fld_name, String)); break; case 'L': // logical desc_.add_descriptor(attribute_descriptor(fld_name, Boolean)); break; case 'N': // numeric case 'O': // double case 'F': // float { if (fd.dec_>0) { desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8)); } else { desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4)); } break; } default: // I - long // G - ole // + - autoincrement // @ - timestamp // B - binary // l - long // M - memo MAPNIK_LOG_ERROR(shape) << "shape_datasource: Unknown type=" << fd.type_; break; } } } catch (datasource_exception const& ex) { MAPNIK_LOG_ERROR(shape) << "Shape Plugin: error processing field attributes, " << ex.what(); throw; } catch (const std::exception& ex) { MAPNIK_LOG_ERROR(shape) << "Shape Plugin: error processing field attributes, " << ex.what(); throw; } catch (...) // exception: pipe_select_interrupter: Too many open files { MAPNIK_LOG_ERROR(shape) << "Shape Plugin: error processing field attributes"; throw; } } void shape_datasource::init(shape_io& shape) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::init"); #endif //first read header from *.shp shape_file::record_type header(100); shape.shp().read_record(header); int file_code = header.read_xdr_integer(); if (file_code != 9994) { std::ostringstream s; s << "Shape Plugin: wrong file code " << file_code; throw datasource_exception(s.str()); } header.skip(5 * 4); file_length_ = header.read_xdr_integer(); int version = header.read_ndr_integer(); if (version != 1000) { std::ostringstream s; s << "Shape Plugin: nvalid version number " << version; throw datasource_exception(s.str()); } shape_type_ = static_cast<shape_io::shapeType>(header.read_ndr_integer()); if (shape_type_ == shape_io::shape_multipatch) throw datasource_exception("Shape Plugin: shapefile multipatch type is not supported"); const double lox = header.read_double(); const double loy = header.read_double(); const double hix = header.read_double(); const double hiy = header.read_double(); extent_.init(lox, loy, hix, hiy); #ifdef MAPNIK_LOG const double zmin = header.read_double(); const double zmax = header.read_double(); const double mmin = header.read_double(); const double mmax = header.read_double(); MAPNIK_LOG_DEBUG(shape) << "shape_datasource: Z min/max=" << zmin << "," << zmax; MAPNIK_LOG_DEBUG(shape) << "shape_datasource: M min/max=" << mmin << "," << mmax; #endif // check if we have an index file around indexed_ = shape.has_index(); MAPNIK_LOG_DEBUG(shape) << "shape_datasource: Extent=" << extent_; MAPNIK_LOG_DEBUG(shape) << "shape_datasource: File length=" << file_length_; MAPNIK_LOG_DEBUG(shape) << "shape_datasource: Shape type=" << shape_type_; } shape_datasource::~shape_datasource() {} const char * shape_datasource::name() { return "shape"; } datasource::datasource_t shape_datasource::type() const { return type_; } layer_descriptor shape_datasource::get_descriptor() const { return desc_; } featureset_ptr shape_datasource::features(query const& q) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::features"); #endif filter_in_box filter(q.get_bbox()); if (indexed_) { std::unique_ptr<shape_io> shape_ptr = std::make_unique<shape_io>(shape_name_); return featureset_ptr (new shape_index_featureset<filter_in_box>(filter, std::move(shape_ptr), q.property_names(), desc_.get_encoding(), shape_name_, row_limit_)); } else { return std::make_shared<shape_featureset<filter_in_box> >(filter, shape_name_, q.property_names(), desc_.get_encoding(), row_limit_); } } featureset_ptr shape_datasource::features_at_point(coord2d const& pt, double tol) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::features_at_point"); #endif filter_at_point filter(pt,tol); // collect all attribute names auto const& desc = desc_.get_descriptors(); std::set<std::string> names; for (auto const& attr_info : desc) { names.insert(attr_info.get_name()); } if (indexed_) { std::unique_ptr<shape_io> shape_ptr = std::make_unique<shape_io>(shape_name_); return featureset_ptr (new shape_index_featureset<filter_at_point>(filter, std::move(shape_ptr), names, desc_.get_encoding(), shape_name_, row_limit_)); } else { return std::make_shared<shape_featureset<filter_at_point> >(filter, shape_name_, names, desc_.get_encoding(), row_limit_); } } box2d<double> shape_datasource::envelope() const { return extent_; } boost::optional<mapnik::datasource_geometry_t> shape_datasource::get_geometry_type() const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::get_geometry_type"); #endif boost::optional<mapnik::datasource_geometry_t> result; switch (shape_type_) { case shape_io::shape_point: case shape_io::shape_pointm: case shape_io::shape_pointz: case shape_io::shape_multipoint: case shape_io::shape_multipointm: case shape_io::shape_multipointz: { result.reset(mapnik::datasource_geometry_t::Point); break; } case shape_io::shape_polyline: case shape_io::shape_polylinem: case shape_io::shape_polylinez: { result.reset(mapnik::datasource_geometry_t::LineString); break; } case shape_io::shape_polygon: case shape_io::shape_polygonm: case shape_io::shape_polygonz: { result.reset(mapnik::datasource_geometry_t::Polygon); break; } default: break; } return result; } <commit_msg>remove redundant unique_ptr usage for local variable<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "shape_datasource.hpp" #include "shape_featureset.hpp" #include "shape_index_featureset.hpp" #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/version.hpp> #include <boost/algorithm/string.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/debug.hpp> #include <mapnik/make_unique.hpp> #include <mapnik/util/fs.hpp> #include <mapnik/global.hpp> #include <mapnik/util/utf_conv_win.hpp> #include <mapnik/boolean.hpp> #include <mapnik/util/conversions.hpp> #include <mapnik/geom_util.hpp> #include <mapnik/timer.hpp> #include <mapnik/value_types.hpp> // stl #include <fstream> #include <sstream> #include <stdexcept> DATASOURCE_PLUGIN(shape_datasource) using mapnik::String; using mapnik::Double; using mapnik::Integer; using mapnik::Boolean; using mapnik::datasource_exception; using mapnik::filter_in_box; using mapnik::filter_at_point; using mapnik::attribute_descriptor; shape_datasource::shape_datasource(parameters const& params) : datasource (params), type_(datasource::Vector), file_length_(0), indexed_(false), row_limit_(*params.get<mapnik::value_integer>("row_limit",0)), desc_(shape_datasource::name(), *params.get<std::string>("encoding","utf-8")) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::init"); #endif boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw datasource_exception("Shape Plugin: missing <file> parameter"); boost::optional<std::string> base = params.get<std::string>("base"); if (base) shape_name_ = *base + "/" + *file; else shape_name_ = *file; boost::algorithm::ireplace_last(shape_name_,".shp",""); if (!mapnik::util::exists(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' does not exist"); } if (mapnik::util::is_directory(shape_name_ + ".shp")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".shp' appears to be a directory not a file"); } if (!mapnik::util::exists(shape_name_ + ".dbf")) { throw datasource_exception("Shape Plugin: shapefile '" + shape_name_ + ".dbf' does not exist"); } try { #ifdef MAPNIK_STATS mapnik::progress_timer __stats2__(std::clog, "shape_datasource::init(get_column_description)"); #endif shape_io shape(shape_name_); init(shape); for (int i = 0; i < shape.dbf().num_fields(); ++i) { field_descriptor const& fd = shape.dbf().descriptor(i); std::string fld_name=fd.name_; switch (fd.type_) { case 'C': // character case 'D': // date desc_.add_descriptor(attribute_descriptor(fld_name, String)); break; case 'L': // logical desc_.add_descriptor(attribute_descriptor(fld_name, Boolean)); break; case 'N': // numeric case 'O': // double case 'F': // float { if (fd.dec_>0) { desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8)); } else { desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4)); } break; } default: // I - long // G - ole // + - autoincrement // @ - timestamp // B - binary // l - long // M - memo MAPNIK_LOG_ERROR(shape) << "shape_datasource: Unknown type=" << fd.type_; break; } } } catch (datasource_exception const& ex) { MAPNIK_LOG_ERROR(shape) << "Shape Plugin: error processing field attributes, " << ex.what(); throw; } catch (const std::exception& ex) { MAPNIK_LOG_ERROR(shape) << "Shape Plugin: error processing field attributes, " << ex.what(); throw; } catch (...) // exception: pipe_select_interrupter: Too many open files { MAPNIK_LOG_ERROR(shape) << "Shape Plugin: error processing field attributes"; throw; } } void shape_datasource::init(shape_io& shape) { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::init"); #endif //first read header from *.shp shape_file::record_type header(100); shape.shp().read_record(header); int file_code = header.read_xdr_integer(); if (file_code != 9994) { std::ostringstream s; s << "Shape Plugin: wrong file code " << file_code; throw datasource_exception(s.str()); } header.skip(5 * 4); file_length_ = header.read_xdr_integer(); int version = header.read_ndr_integer(); if (version != 1000) { std::ostringstream s; s << "Shape Plugin: nvalid version number " << version; throw datasource_exception(s.str()); } shape_type_ = static_cast<shape_io::shapeType>(header.read_ndr_integer()); if (shape_type_ == shape_io::shape_multipatch) throw datasource_exception("Shape Plugin: shapefile multipatch type is not supported"); const double lox = header.read_double(); const double loy = header.read_double(); const double hix = header.read_double(); const double hiy = header.read_double(); extent_.init(lox, loy, hix, hiy); #ifdef MAPNIK_LOG const double zmin = header.read_double(); const double zmax = header.read_double(); const double mmin = header.read_double(); const double mmax = header.read_double(); MAPNIK_LOG_DEBUG(shape) << "shape_datasource: Z min/max=" << zmin << "," << zmax; MAPNIK_LOG_DEBUG(shape) << "shape_datasource: M min/max=" << mmin << "," << mmax; #endif // check if we have an index file around indexed_ = shape.has_index(); MAPNIK_LOG_DEBUG(shape) << "shape_datasource: Extent=" << extent_; MAPNIK_LOG_DEBUG(shape) << "shape_datasource: File length=" << file_length_; MAPNIK_LOG_DEBUG(shape) << "shape_datasource: Shape type=" << shape_type_; } shape_datasource::~shape_datasource() {} const char * shape_datasource::name() { return "shape"; } datasource::datasource_t shape_datasource::type() const { return type_; } layer_descriptor shape_datasource::get_descriptor() const { return desc_; } featureset_ptr shape_datasource::features(query const& q) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::features"); #endif filter_in_box filter(q.get_bbox()); if (indexed_) { std::unique_ptr<shape_io> shape_ptr = std::make_unique<shape_io>(shape_name_); return featureset_ptr (new shape_index_featureset<filter_in_box>(filter, std::move(shape_ptr), q.property_names(), desc_.get_encoding(), shape_name_, row_limit_)); } else { return std::make_shared<shape_featureset<filter_in_box> >(filter, shape_name_, q.property_names(), desc_.get_encoding(), row_limit_); } } featureset_ptr shape_datasource::features_at_point(coord2d const& pt, double tol) const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::features_at_point"); #endif filter_at_point filter(pt,tol); // collect all attribute names auto const& desc = desc_.get_descriptors(); std::set<std::string> names; for (auto const& attr_info : desc) { names.insert(attr_info.get_name()); } if (indexed_) { std::unique_ptr<shape_io> shape_ptr = std::make_unique<shape_io>(shape_name_); return featureset_ptr (new shape_index_featureset<filter_at_point>(filter, std::move(shape_ptr), names, desc_.get_encoding(), shape_name_, row_limit_)); } else { return std::make_shared<shape_featureset<filter_at_point> >(filter, shape_name_, names, desc_.get_encoding(), row_limit_); } } box2d<double> shape_datasource::envelope() const { return extent_; } boost::optional<mapnik::datasource_geometry_t> shape_datasource::get_geometry_type() const { #ifdef MAPNIK_STATS mapnik::progress_timer __stats__(std::clog, "shape_datasource::get_geometry_type"); #endif boost::optional<mapnik::datasource_geometry_t> result; switch (shape_type_) { case shape_io::shape_point: case shape_io::shape_pointm: case shape_io::shape_pointz: case shape_io::shape_multipoint: case shape_io::shape_multipointm: case shape_io::shape_multipointz: { result.reset(mapnik::datasource_geometry_t::Point); break; } case shape_io::shape_polyline: case shape_io::shape_polylinem: case shape_io::shape_polylinez: { result.reset(mapnik::datasource_geometry_t::LineString); break; } case shape_io::shape_polygon: case shape_io::shape_polygonm: case shape_io::shape_polygonz: { result.reset(mapnik::datasource_geometry_t::Polygon); break; } default: break; } return result; } <|endoftext|>
<commit_before> #include "cssysdef.h" #include "cloth.h" #include "igeom/polymesh.h" #include "csgeom/math2d.h" #include "csgeom/math3d.h" #include "csgeom/tesselat.h" #include "csutil/bitarray.h" #include "imesh/object.h" #include "imesh/clothmesh.h" #include "iutil/eventh.h" #include "iutil/comp.h" #include "igeom/objmodel.h" #include "ivideo/vbufmgr.h" /* bool Cloth::AddConstraint( int v0, int v1 , Constraint** edge ) { if (v0==v1) { *edge=NULL; return false; }; Constraint* first; Constraint* p; p=first=(Constraint*)Edges->GetFirstItem(); do { if ((p->v0==v0) || (p->v0==v1)) { if ((p->v1==v0) || (p->v1==v1)) { *edge=p; return false; }; }; p=(Constraint*)Edges->GetNextItem(); } while (p!=first); p=new Constraint( v0 , v1 ); Edges->AddItem( (void*) p ); *edge=p; return true; };*/ bool Cloth::AddConstraint ( int v0 , int v1 , Constraint** edge ) { if (v0==v1) { *edge=NULL; return false; }; Constraint* p; int size = Edges->Length(); for (int i=0; i < size ; i++ ) { p = (Constraint*) Edges -> Get( i ); if ((p->v0==v0) || (p->v0==v1)) { if ((p->v1==v0) || (p->v1==v1)) { *edge=p; return false; }; }; }; p=new Constraint( v0 , v1 ); Edges -> Push ( (void*) p ); *edge = p; return true; }; Cloth::Cloth( iClothFactoryState* mesh, csVector3& Sh, csBox3& box, csVector3 grav ) { shift = &Sh; object_bbox = &box; gravity = grav; printf( " CREATING the cloth... \n"); uint i; vertices = NULL; triangles = NULL; printf( " CREATING the clothA... \n"); csVector3* verts = mesh->GetVertices (); printf( " CREATING the clothB... \n"); nverts = mesh->GetVertexCount (); csTriangle* tris = mesh->GetTriangles (); uint tri_count = mesh->GetTriangleCount(); //for (i = 0; i < polycnt ; i++) { tri_count += polygons[i].num_vertices - 2; }; printf( " CREATING the cloth2... \n"); Edges = new csBasicVector( nverts , 16 ); nedges = 0; vertices = new csVector3[ nverts ]; for (i = 0; i < nverts ; i++) { vertices[i].Set( verts[i].x , verts[i].y , verts[i].z ); }; ntris = 2*tri_count; //here we care about double-facing the mesh triangles = new csTriangle [ ntris ]; //memcpy ( triangles , tris , sizeof(csTriangle)*ntris ); //Triangle2EdgeRef = new Constraint** [ tri_count ]; this will be needed // when 2nd neighbours are // considered //int* vidx; printf( " CREATING the cloth3... \n"); int index=0; int tri; int v; Constraint* a; Constraint* b; Constraint* c; bool isNew; for (i=0; i<tri_count; i++) { triangles[ 2*i ].a = tris[i].a; triangles[ 2*i ].b = tris[i].b; triangles[ 2*i ].c = tris[i].c; triangles[ 2*i + 1 ].a = tris[i].a; triangles[ 2*i + 1 ].b = tris[i].c; triangles[ 2*i + 1 ].c = tris[i].b; isNew = AddConstraint( tris[i].a , tris[i].b , &a ); if (isNew) { a -> L0 =( verts[ tris[i].a ] - verts[ tris[i].b ] ).Norm(); nedges++; }; isNew = AddConstraint( tris[i].b , tris[i].c , &b ); if (isNew) { b -> L0 = ( verts[ tris[i].b ] - verts[ tris[i].c ] ).Norm(); nedges++; }; isNew = AddConstraint( tris[i].c , tris[i].a , &c ); if (isNew) { c -> L0 = ( verts[ tris[i].c ] - verts[ tris[i].a ] ).Norm(); nedges++; }; }; printf( " CREATING the cloth4... \n"); /* for (i = 0; i<count ; i ++) { vidx = p.vertices; tri = 0; isNew = AddEdgeConstraint( vidx[0] , vidx[1] , &a ); if (isNew) { a -> L0 =( verts[ vidx[0] ] - verts[ vidx[1] ] ).Norm(); nedges++; }; for (v = 2; v < p.num_vertices; v++ , tri++ ) //triangulation { isNew = AddEdgeConstraint( vidx[v-1] , vidx[v] , &b ); if (isNew) { b -> L0 = ( verts[ vidx[v-1] ] - verts[ vidx[v] ] ).Norm(); nedges++; }; isNew = AddEdgeConstraint( vidx[v] , vidx[0] , &c ); if (isNew) { c -> L0 = ( verts[ vidx[v] ] - verts[ vidx[0] ] ).Norm(); nedges++; }; no need to consider 2nd neighbours or dynamic refinement yet Triangle2EdgeRef[ index + tri ] = new Constraint*[ 3 ]; Triangle2EdgeRef[ index + tri ][0] = a; Triangle2EdgeRef[ index + tri ][1] = b; Triangle2EdgeRef[ index + tri ][2] = c; triangles[ index + tri ].a = vidx[0]; triangles[ index + tri ].b = vidx[v-1]; triangles[ index + tri ].c = vidx[v]; a = c; }; index += (p.num_vertices - 2); };*/ }; // END Cloth::Cloth Cloth::~Cloth() { if (vertices) { delete[] vertices; }; if (triangles) { delete[] triangles; }; Constraint* p; //p=(Constraint*)Edges->GetFirstItem(); p=(Constraint*)Edges->Pop(); do { //Edges->RemoveItem( (void*) p ); delete p; p=(Constraint*)Edges->Pop(); } while (p!=NULL); delete Edges; }; <commit_msg>small fix<commit_after> #include "cssysdef.h" #include "cloth.h" #include "igeom/polymesh.h" #include "csgeom/math2d.h" #include "csgeom/math3d.h" #include "csgeom/tesselat.h" #include "csutil/bitarray.h" #include "imesh/object.h" #include "imesh/clothmesh.h" #include "iutil/eventh.h" #include "iutil/comp.h" #include "igeom/objmodel.h" #include "ivideo/vbufmgr.h" /* bool Cloth::AddConstraint( int v0, int v1 , Constraint** edge ) { if (v0==v1) { *edge=NULL; return false; }; Constraint* first; Constraint* p; p=first=(Constraint*)Edges->GetFirstItem(); do { if ((p->v0==v0) || (p->v0==v1)) { if ((p->v1==v0) || (p->v1==v1)) { *edge=p; return false; }; }; p=(Constraint*)Edges->GetNextItem(); } while (p!=first); p=new Constraint( v0 , v1 ); Edges->AddItem( (void*) p ); *edge=p; return true; };*/ bool Cloth::AddConstraint ( int v0 , int v1 , Constraint** edge ) { if (v0==v1) { *edge=NULL; return false; }; Constraint* p; int size = Edges->Length(); for (int i=0; i < size ; i++ ) { p = (Constraint*) Edges -> Get( i ); if ((p->v0==v0) || (p->v0==v1)) { if ((p->v1==v0) || (p->v1==v1)) { *edge=p; return false; }; }; }; p=new Constraint( v0 , v1 ); Edges -> Push ( (void*) p ); *edge = p; return true; }; Cloth::Cloth( iClothFactoryState* mesh, csVector3& Sh, csBox3& box, csVector3 grav ) { shift = &Sh; object_bbox = &box; gravity = grav; printf( " CREATING the cloth... \n"); uint i; vertices = NULL; triangles = NULL; printf( " CREATING the clothA... \n"); csVector3* verts = mesh->GetVertices (); printf( " CREATING the clothB... \n"); nverts = mesh->GetVertexCount (); csTriangle* tris = mesh->GetTriangles (); uint tri_count = mesh->GetTriangleCount(); //for (i = 0; i < polycnt ; i++) { tri_count += polygons[i].num_vertices - 2; }; printf( " CREATING the cloth2... \n"); Edges = new csBasicVector( nverts , 16 ); nedges = 0; vertices = new csVector3[ nverts ]; for (i = 0; i < nverts ; i++) { vertices[i].Set( verts[i].x , verts[i].y , verts[i].z ); }; ntris = 2*tri_count; //here we care about double-facing the mesh triangles = new csTriangle [ ntris ]; //memcpy ( triangles , tris , sizeof(csTriangle)*ntris ); //Triangle2EdgeRef = new Constraint** [ tri_count ]; this will be needed // when 2nd neighbours are // considered //int* vidx; printf( " CREATING the cloth3... \n"); int index=0; int tri; int v; Constraint* a; Constraint* b; Constraint* c; bool isNew; for (i=0; i<tri_count; i++) { triangles[ 2*i ].a = tris[i].a; triangles[ 2*i ].b = tris[i].b; triangles[ 2*i ].c = tris[i].c; triangles[ 2*i + 1 ].a = tris[i].a; triangles[ 2*i + 1 ].b = tris[i].c; triangles[ 2*i + 1 ].c = tris[i].b; isNew = AddConstraint( tris[i].a , tris[i].b , &a ); if (isNew) { a -> L0 =( verts[ tris[i].a ] - verts[ tris[i].b ] ).Norm(); nedges++; }; isNew = AddConstraint( tris[i].b , tris[i].c , &b ); if (isNew) { b -> L0 = ( verts[ tris[i].b ] - verts[ tris[i].c ] ).Norm(); nedges++; }; isNew = AddConstraint( tris[i].c , tris[i].a , &c ); if (isNew) { c -> L0 = ( verts[ tris[i].c ] - verts[ tris[i].a ] ).Norm(); nedges++; }; }; printf( " CREATING the cloth4... \n"); /* for (i = 0; i<count ; i ++) { vidx = p.vertices; tri = 0; isNew = AddEdgeConstraint( vidx[0] , vidx[1] , &a ); if (isNew) { a -> L0 =( verts[ vidx[0] ] - verts[ vidx[1] ] ).Norm(); nedges++; }; for (v = 2; v < p.num_vertices; v++ , tri++ ) //triangulation { isNew = AddEdgeConstraint( vidx[v-1] , vidx[v] , &b ); if (isNew) { b -> L0 = ( verts[ vidx[v-1] ] - verts[ vidx[v] ] ).Norm(); nedges++; }; isNew = AddEdgeConstraint( vidx[v] , vidx[0] , &c ); if (isNew) { c -> L0 = ( verts[ vidx[v] ] - verts[ vidx[0] ] ).Norm(); nedges++; }; no need to consider 2nd neighbours or dynamic refinement yet Triangle2EdgeRef[ index + tri ] = new Constraint*[ 3 ]; Triangle2EdgeRef[ index + tri ][0] = a; Triangle2EdgeRef[ index + tri ][1] = b; Triangle2EdgeRef[ index + tri ][2] = c; triangles[ index + tri ].a = vidx[0]; triangles[ index + tri ].b = vidx[v-1]; triangles[ index + tri ].c = vidx[v]; a = c; }; index += (p.num_vertices - 2); };*/ }; // END Cloth::Cloth Cloth::~Cloth() { if (vertices) { delete[] vertices; }; if (triangles) { delete[] triangles; }; Constraint* p; //p=(Constraint*)Edges->GetFirstItem(); p=(Constraint*)Edges->Pop(); do { //Edges->RemoveItem( (void*) p ); delete p; p=(Constraint*)Edges->Pop(); } while (p!=NULL); delete Edges; }; <|endoftext|>
<commit_before>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Debugger.h> #include <DebuggerIO.h> #include <LocalIO.h> #include <SerialIO.h> #include <utilities/StaticString.h> #include <processor/Processor.h> #include <machine/Machine.h> #include <Log.h> #include <utilities/utility.h> #include <graphics/GraphicsService.h> static size_t newlineCount(const char *pString) { size_t nNewlines = 0; while (*pString != '\0') if (*pString++ == '\n') ++nNewlines; return nNewlines; } // TODO: We might want a separate parameter for a stacktrace/register dump void _panic( const char* msg, DebuggerIO* pScreen ) { static HugeStaticString panic_output; panic_output.clear(); panic_output.append( "PANIC: " ); panic_output.append( msg ); // write the final string to the screen pScreen->drawString( panic_output, 0, 0, DebuggerIO::Red, DebuggerIO::Black ); size_t nLines = newlineCount(panic_output) + 2; Log &log = Log::instance(); Log::SeverityLevel level; static NormalStaticString Line; size_t iEntry = 0, iUsedEntries = 0; if ((pScreen->getHeight() - nLines) < (log.getStaticEntryCount() + log.getDynamicEntryCount())) iEntry = log.getStaticEntryCount() + log.getDynamicEntryCount() - (pScreen->getHeight() - nLines) + 1; bool bPrintThisLine = false; for( ; iEntry < (log.getStaticEntryCount() + log.getDynamicEntryCount()); iEntry++ ) { if( iEntry < log.getStaticEntryCount() ) { const Log::StaticLogEntry &entry = log.getStaticEntry(iEntry); level = entry.type; // if( level == Log::Fatal || level == Log::Error ) // { Line.clear(); Line.append("["); Line.append(entry.timestamp, 10, 8, '0'); Line.append("] "); Line.append(entry.str); Line.append( "\n" ); bPrintThisLine = true; // } } else { const Log::DynamicLogEntry &entry = log.getDynamicEntry(iEntry); level = entry.type; // if( level == Log::Fatal || level == Log::Error ) // { Line.clear(); Line.append("["); Line.append(entry.timestamp, 10, 8, '0'); Line.append("] "); Line.append(entry.str); Line.append( "\n" ); bPrintThisLine = true; // } } // print the line if( bPrintThisLine == true ) { ++iUsedEntries; pScreen->drawString( Line, nLines + iUsedEntries, 0, DebuggerIO::White, DebuggerIO::Black ); bPrintThisLine = false; } } } void panic( const char* msg ) { // Drop out of whatever graphics mode we were in GraphicsService::GraphicsProvider provider; memset(&provider, 0, sizeof(provider)); provider.bTextModes = true; ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("graphics")); Service *pService = ServiceManager::instance().getService(String("graphics")); bool bSuccess = false; if(pFeatures->provides(ServiceFeatures::probe)) if(pService) bSuccess = pService->serve(ServiceFeatures::probe, reinterpret_cast<void*>(&provider), sizeof(provider)); if(bSuccess && !provider.bTextModes) provider.pDisplay->setScreenMode(0); #ifdef MULTIPROCESSOR Machine::instance().stopAllOtherProcessors(); #endif /* * I/O implementations. */ SerialIO serialIO(Machine::instance().getSerial(0)); DebuggerIO *pInterfaces[2] = {0}; int nInterfaces = 0; if(Machine::instance().getNumVga()) // Not all machines have "VGA", so handle that { static LocalIO localIO(Machine::instance().getVga(0), Machine::instance().getKeyboard()); #ifdef DONT_LOG_TO_SERIAL pInterfaces[0] = &localIO; nInterfaces = 1; #else pInterfaces[0] = &localIO; pInterfaces[1] = &serialIO; nInterfaces = 2; #endif } #ifndef DONT_LOG_TO_SERIAL else { pInterfaces[0] = &serialIO; nInterfaces = 1; } #endif for( int nIFace = 0; nIFace < nInterfaces; nIFace++ ) _panic( msg, pInterfaces[nIFace] ); // Halt the processor Processor::halt(); } <commit_msg>kernel: fix panic() so it doesn't break halt() due to an interrupt arriving and return.<commit_after>/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <Debugger.h> #include <DebuggerIO.h> #include <LocalIO.h> #include <SerialIO.h> #include <utilities/StaticString.h> #include <processor/Processor.h> #include <machine/Machine.h> #include <Log.h> #include <utilities/utility.h> #include <graphics/GraphicsService.h> static size_t newlineCount(const char *pString) { size_t nNewlines = 0; while (*pString != '\0') if (*pString++ == '\n') ++nNewlines; return nNewlines; } // TODO: We might want a separate parameter for a stacktrace/register dump void _panic( const char* msg, DebuggerIO* pScreen ) { static HugeStaticString panic_output; panic_output.clear(); panic_output.append( "PANIC: " ); panic_output.append( msg ); // write the final string to the screen pScreen->drawString( panic_output, 0, 0, DebuggerIO::Red, DebuggerIO::Black ); size_t nLines = newlineCount(panic_output) + 2; Log &log = Log::instance(); Log::SeverityLevel level; static NormalStaticString Line; size_t iEntry = 0, iUsedEntries = 0; if ((pScreen->getHeight() - nLines) < (log.getStaticEntryCount() + log.getDynamicEntryCount())) iEntry = log.getStaticEntryCount() + log.getDynamicEntryCount() - (pScreen->getHeight() - nLines) + 1; bool bPrintThisLine = false; for( ; iEntry < (log.getStaticEntryCount() + log.getDynamicEntryCount()); iEntry++ ) { if( iEntry < log.getStaticEntryCount() ) { const Log::StaticLogEntry &entry = log.getStaticEntry(iEntry); level = entry.type; // if( level == Log::Fatal || level == Log::Error ) // { Line.clear(); Line.append("["); Line.append(entry.timestamp, 10, 8, '0'); Line.append("] "); Line.append(entry.str); Line.append( "\n" ); bPrintThisLine = true; // } } else { const Log::DynamicLogEntry &entry = log.getDynamicEntry(iEntry); level = entry.type; // if( level == Log::Fatal || level == Log::Error ) // { Line.clear(); Line.append("["); Line.append(entry.timestamp, 10, 8, '0'); Line.append("] "); Line.append(entry.str); Line.append( "\n" ); bPrintThisLine = true; // } } // print the line if( bPrintThisLine == true ) { ++iUsedEntries; pScreen->drawString( Line, nLines + iUsedEntries, 0, DebuggerIO::White, DebuggerIO::Black ); bPrintThisLine = false; } } } void panic( const char* msg ) { Processor::setInterrupts(false); // Drop out of whatever graphics mode we were in GraphicsService::GraphicsProvider provider; memset(&provider, 0, sizeof(provider)); provider.bTextModes = true; ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("graphics")); Service *pService = ServiceManager::instance().getService(String("graphics")); bool bSuccess = false; if(pFeatures->provides(ServiceFeatures::probe)) if(pService) bSuccess = pService->serve(ServiceFeatures::probe, reinterpret_cast<void*>(&provider), sizeof(provider)); if(bSuccess && !provider.bTextModes) provider.pDisplay->setScreenMode(0); #ifdef MULTIPROCESSOR Machine::instance().stopAllOtherProcessors(); #endif /* * I/O implementations. */ SerialIO serialIO(Machine::instance().getSerial(0)); DebuggerIO *pInterfaces[2] = {0}; int nInterfaces = 0; if(Machine::instance().getNumVga()) // Not all machines have "VGA", so handle that { static LocalIO localIO(Machine::instance().getVga(0), Machine::instance().getKeyboard()); #ifdef DONT_LOG_TO_SERIAL pInterfaces[0] = &localIO; nInterfaces = 1; #else pInterfaces[0] = &localIO; pInterfaces[1] = &serialIO; nInterfaces = 2; #endif } #ifndef DONT_LOG_TO_SERIAL else { pInterfaces[0] = &serialIO; nInterfaces = 1; } #endif for( int nIFace = 0; nIFace < nInterfaces; nIFace++ ) _panic( msg, pInterfaces[nIFace] ); // Halt the processor while(1) Processor::halt(); } <|endoftext|>
<commit_before><commit_msg>:( didnt include it in last commit<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/system_key_event_listener.h" // TODO(saintlou): should we handle this define in gyp even if only used once? #define XK_MISCELLANY 1 #include <X11/keysymdef.h> #include <X11/XF86keysym.h> #include <X11/XKBlib.h> #include "chrome/browser/accessibility_events.h" #include "chrome/browser/chromeos/audio_handler.h" #include "chrome/browser/chromeos/brightness_bubble.h" #include "chrome/browser/chromeos/dbus/dbus_thread_manager.h" #include "chrome/browser/chromeos/dbus/power_manager_client.h" #include "chrome/browser/chromeos/input_method/hotkey_manager.h" #include "chrome/browser/chromeos/input_method/input_method_manager.h" #include "chrome/browser/chromeos/input_method/xkeyboard.h" #include "chrome/browser/chromeos/volume_bubble.h" #include "content/browser/user_metrics.h" #include "third_party/cros_system_api/window_manager/chromeos_wm_ipc_enums.h" #include "ui/base/x/x11_util.h" #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) #include "base/message_pump_x.h" #endif namespace chromeos { namespace { // Percent by which the volume should be changed when a volume key is pressed. const double kStepPercentage = 4.0; // Percent to which the volume should be set when the "volume up" key is pressed // while we're muted and have the volume set to 0. See // http://crosbug.com/13618. const double kVolumePercentOnVolumeUpWhileMuted = 25.0; static SystemKeyEventListener* g_system_key_event_listener = NULL; } // namespace // static void SystemKeyEventListener::Initialize() { CHECK(!g_system_key_event_listener); g_system_key_event_listener = new SystemKeyEventListener(); } // static void SystemKeyEventListener::Shutdown() { // We may call Shutdown without calling Initialize, e.g. if we exit early. if (g_system_key_event_listener) { delete g_system_key_event_listener; g_system_key_event_listener = NULL; } } // static SystemKeyEventListener* SystemKeyEventListener::GetInstance() { VLOG_IF(1, !g_system_key_event_listener) << "SystemKeyEventListener::GetInstance() with NULL global instance."; return g_system_key_event_listener; } SystemKeyEventListener::SystemKeyEventListener() : stopped_(false), caps_lock_is_on_(input_method::XKeyboard::CapsLockIsEnabled()), xkb_event_base_(0) { Display* display = ui::GetXDisplay(); key_brightness_down_ = XKeysymToKeycode(display, XF86XK_MonBrightnessDown); key_brightness_up_ = XKeysymToKeycode(display, XF86XK_MonBrightnessUp); key_volume_mute_ = XKeysymToKeycode(display, XF86XK_AudioMute); key_volume_down_ = XKeysymToKeycode(display, XF86XK_AudioLowerVolume); key_volume_up_ = XKeysymToKeycode(display, XF86XK_AudioRaiseVolume); key_f6_ = XKeysymToKeycode(display, XK_F6); key_f7_ = XKeysymToKeycode(display, XK_F7); key_f8_ = XKeysymToKeycode(display, XK_F8); key_f9_ = XKeysymToKeycode(display, XK_F9); key_f10_ = XKeysymToKeycode(display, XK_F10); key_left_shift_ = XKeysymToKeycode(display, XK_Shift_L); key_right_shift_ = XKeysymToKeycode(display, XK_Shift_R); if (key_brightness_down_) GrabKey(key_brightness_down_, 0); if (key_brightness_up_) GrabKey(key_brightness_up_, 0); if (key_volume_mute_) GrabKey(key_volume_mute_, 0); if (key_volume_down_) GrabKey(key_volume_down_, 0); if (key_volume_up_) GrabKey(key_volume_up_, 0); GrabKey(key_f6_, 0); GrabKey(key_f7_, 0); GrabKey(key_f8_, 0); GrabKey(key_f9_, 0); GrabKey(key_f10_, 0); int xkb_major_version = XkbMajorVersion; int xkb_minor_version = XkbMinorVersion; if (!XkbQueryExtension(display, NULL, // opcode_return &xkb_event_base_, NULL, // error_return &xkb_major_version, &xkb_minor_version)) { LOG(WARNING) << "Could not query Xkb extension"; } if (!XkbSelectEvents(display, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) { LOG(WARNING) << "Could not install Xkb Indicator observer"; } #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) MessageLoopForUI::current()->AddObserver(this); #else gdk_window_add_filter(NULL, GdkEventFilter, this); #endif } SystemKeyEventListener::~SystemKeyEventListener() { Stop(); } void SystemKeyEventListener::Stop() { if (stopped_) return; #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) MessageLoopForUI::current()->RemoveObserver(this); #else gdk_window_remove_filter(NULL, GdkEventFilter, this); #endif stopped_ = true; } AudioHandler* SystemKeyEventListener::GetAudioHandler() const { AudioHandler* audio_handler = AudioHandler::GetInstance(); if (!audio_handler || !audio_handler->IsInitialized()) return NULL; return audio_handler; } void SystemKeyEventListener::AddCapsLockObserver(CapsLockObserver* observer) { caps_lock_observers_.AddObserver(observer); } void SystemKeyEventListener::RemoveCapsLockObserver( CapsLockObserver* observer) { caps_lock_observers_.RemoveObserver(observer); } #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) base::EventStatus SystemKeyEventListener::WillProcessEvent( const base::NativeEvent& event) { return ProcessedXEvent(event) ? base::EVENT_HANDLED : base::EVENT_CONTINUE; } void SystemKeyEventListener::DidProcessEvent(const base::NativeEvent& event) { } #else // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) // static GdkFilterReturn SystemKeyEventListener::GdkEventFilter(GdkXEvent* gxevent, GdkEvent* gevent, gpointer data) { SystemKeyEventListener* listener = static_cast<SystemKeyEventListener*>(data); XEvent* xevent = static_cast<XEvent*>(gxevent); return listener->ProcessedXEvent(xevent) ? GDK_FILTER_REMOVE : GDK_FILTER_CONTINUE; } #endif // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) void SystemKeyEventListener::GrabKey(int32 key, uint32 mask) { uint32 num_lock_mask = Mod2Mask; uint32 caps_lock_mask = LockMask; Display* display = ui::GetXDisplay(); Window root = DefaultRootWindow(display); XGrabKey(display, key, mask, root, True, GrabModeAsync, GrabModeAsync); XGrabKey(display, key, mask | caps_lock_mask, root, True, GrabModeAsync, GrabModeAsync); XGrabKey(display, key, mask | num_lock_mask, root, True, GrabModeAsync, GrabModeAsync); XGrabKey(display, key, mask | caps_lock_mask | num_lock_mask, root, True, GrabModeAsync, GrabModeAsync); } void SystemKeyEventListener::OnBrightnessDown() { DBusThreadManager::Get()->power_manager_client()-> DecreaseScreenBrightness(true); } void SystemKeyEventListener::OnBrightnessUp() { DBusThreadManager::Get()->power_manager_client()-> IncreaseScreenBrightness(); } void SystemKeyEventListener::OnVolumeMute() { AudioHandler* audio_handler = GetAudioHandler(); if (!audio_handler) return; // Always muting (and not toggling) as per final decision on // http://crosbug.com/3751 audio_handler->SetMuted(true); SendAccessibilityVolumeNotification( audio_handler->GetVolumePercent(), audio_handler->IsMuted()); ShowVolumeBubble(); } void SystemKeyEventListener::OnVolumeDown() { AudioHandler* audio_handler = GetAudioHandler(); if (!audio_handler) return; if (audio_handler->IsMuted()) audio_handler->SetVolumePercent(0.0); else audio_handler->AdjustVolumeByPercent(-kStepPercentage); SendAccessibilityVolumeNotification( audio_handler->GetVolumePercent(), audio_handler->IsMuted()); ShowVolumeBubble(); } void SystemKeyEventListener::OnVolumeUp() { AudioHandler* audio_handler = GetAudioHandler(); if (!audio_handler) return; if (audio_handler->IsMuted()) { audio_handler->SetMuted(false); if (audio_handler->GetVolumePercent() <= 0.1) // float comparison audio_handler->SetVolumePercent(kVolumePercentOnVolumeUpWhileMuted); } else { audio_handler->AdjustVolumeByPercent(kStepPercentage); } SendAccessibilityVolumeNotification( audio_handler->GetVolumePercent(), audio_handler->IsMuted()); ShowVolumeBubble(); } void SystemKeyEventListener::OnCapsLock(bool enabled) { FOR_EACH_OBSERVER( CapsLockObserver, caps_lock_observers_, OnCapsLockChange(enabled)); } void SystemKeyEventListener::ShowVolumeBubble() { AudioHandler* audio_handler = GetAudioHandler(); if (audio_handler) { VolumeBubble::GetInstance()->ShowBubble( audio_handler->GetVolumePercent(), !audio_handler->IsMuted()); } BrightnessBubble::GetInstance()->HideBubble(); } bool SystemKeyEventListener::ProcessedXEvent(XEvent* xevent) { if (xevent->type == KeyPress || xevent->type == KeyRelease) { // Change the current keyboard layout (or input method) if xevent is one of // the input method hotkeys. input_method::HotkeyManager* hotkey_manager = input_method::InputMethodManager::GetInstance()->GetHotkeyManager(); if (hotkey_manager->FilterKeyEvent(*xevent)) { return true; } } if (xevent->type == xkb_event_base_) { XkbEvent* xkey_event = reinterpret_cast<XkbEvent*>(xevent); if (xkey_event->any.xkb_type == XkbStateNotify) { caps_lock_is_on_ = (xkey_event->state.locked_mods) & LockMask; OnCapsLock(caps_lock_is_on_); return true; } } else if (xevent->type == KeyPress) { const int32 keycode = xevent->xkey.keycode; if (keycode) { // Toggle Caps Lock if both Shift keys are pressed simultaneously. if (keycode == key_left_shift_ || keycode == key_right_shift_) { const bool other_shift_is_held = (xevent->xkey.state & ShiftMask); const bool other_mods_are_held = (xevent->xkey.state & ~(ShiftMask | LockMask)); if (other_shift_is_held && !other_mods_are_held) input_method::XKeyboard::SetCapsLockEnabled(!caps_lock_is_on_); } // Only doing non-Alt/Shift/Ctrl modified keys if (!(xevent->xkey.state & (Mod1Mask | ShiftMask | ControlMask))) { if (keycode == key_f6_ || keycode == key_brightness_down_) { if (keycode == key_f6_) UserMetrics::RecordAction( UserMetricsAction("Accel_BrightnessDown_F6")); OnBrightnessDown(); return true; } else if (keycode == key_f7_ || keycode == key_brightness_up_) { if (keycode == key_f7_) UserMetrics::RecordAction( UserMetricsAction("Accel_BrightnessUp_F7")); OnBrightnessUp(); return true; } else if (keycode == key_f8_ || keycode == key_volume_mute_) { if (keycode == key_f8_) UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeMute_F8")); OnVolumeMute(); return true; } else if (keycode == key_f9_ || keycode == key_volume_down_) { if (keycode == key_f9_) UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeDown_F9")); OnVolumeDown(); return true; } else if (keycode == key_f10_ || keycode == key_volume_up_) { if (keycode == key_f10_) UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeUp_F10")); OnVolumeUp(); return true; } } } } return false; } } // namespace chromeos <commit_msg>Implement the final UI for the CAPS LOCK indicator (part 2 of 3)<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/system_key_event_listener.h" // TODO(saintlou): should we handle this define in gyp even if only used once? #define XK_MISCELLANY 1 #include <X11/keysymdef.h> #include <X11/XF86keysym.h> #include <X11/XKBlib.h> #include "chrome/browser/accessibility_events.h" #include "chrome/browser/chromeos/audio_handler.h" #include "chrome/browser/chromeos/brightness_bubble.h" #include "chrome/browser/chromeos/dbus/dbus_thread_manager.h" #include "chrome/browser/chromeos/dbus/power_manager_client.h" #include "chrome/browser/chromeos/input_method/hotkey_manager.h" #include "chrome/browser/chromeos/input_method/input_method_manager.h" #include "chrome/browser/chromeos/input_method/xkeyboard.h" #include "chrome/browser/chromeos/volume_bubble.h" #include "content/browser/user_metrics.h" #include "third_party/cros_system_api/window_manager/chromeos_wm_ipc_enums.h" #include "ui/base/x/x11_util.h" #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) #include "base/message_pump_x.h" #endif namespace chromeos { namespace { // Percent by which the volume should be changed when a volume key is pressed. const double kStepPercentage = 4.0; // Percent to which the volume should be set when the "volume up" key is pressed // while we're muted and have the volume set to 0. See // http://crosbug.com/13618. const double kVolumePercentOnVolumeUpWhileMuted = 25.0; static SystemKeyEventListener* g_system_key_event_listener = NULL; } // namespace // static void SystemKeyEventListener::Initialize() { CHECK(!g_system_key_event_listener); g_system_key_event_listener = new SystemKeyEventListener(); } // static void SystemKeyEventListener::Shutdown() { // We may call Shutdown without calling Initialize, e.g. if we exit early. if (g_system_key_event_listener) { delete g_system_key_event_listener; g_system_key_event_listener = NULL; } } // static SystemKeyEventListener* SystemKeyEventListener::GetInstance() { VLOG_IF(1, !g_system_key_event_listener) << "SystemKeyEventListener::GetInstance() with NULL global instance."; return g_system_key_event_listener; } SystemKeyEventListener::SystemKeyEventListener() : stopped_(false), caps_lock_is_on_(input_method::XKeyboard::CapsLockIsEnabled()), xkb_event_base_(0) { Display* display = ui::GetXDisplay(); key_brightness_down_ = XKeysymToKeycode(display, XF86XK_MonBrightnessDown); key_brightness_up_ = XKeysymToKeycode(display, XF86XK_MonBrightnessUp); key_volume_mute_ = XKeysymToKeycode(display, XF86XK_AudioMute); key_volume_down_ = XKeysymToKeycode(display, XF86XK_AudioLowerVolume); key_volume_up_ = XKeysymToKeycode(display, XF86XK_AudioRaiseVolume); key_f6_ = XKeysymToKeycode(display, XK_F6); key_f7_ = XKeysymToKeycode(display, XK_F7); key_f8_ = XKeysymToKeycode(display, XK_F8); key_f9_ = XKeysymToKeycode(display, XK_F9); key_f10_ = XKeysymToKeycode(display, XK_F10); key_left_shift_ = XKeysymToKeycode(display, XK_Shift_L); key_right_shift_ = XKeysymToKeycode(display, XK_Shift_R); if (key_brightness_down_) GrabKey(key_brightness_down_, 0); if (key_brightness_up_) GrabKey(key_brightness_up_, 0); if (key_volume_mute_) GrabKey(key_volume_mute_, 0); if (key_volume_down_) GrabKey(key_volume_down_, 0); if (key_volume_up_) GrabKey(key_volume_up_, 0); GrabKey(key_f6_, 0); GrabKey(key_f7_, 0); GrabKey(key_f8_, 0); GrabKey(key_f9_, 0); GrabKey(key_f10_, 0); int xkb_major_version = XkbMajorVersion; int xkb_minor_version = XkbMinorVersion; if (!XkbQueryExtension(display, NULL, // opcode_return &xkb_event_base_, NULL, // error_return &xkb_major_version, &xkb_minor_version)) { LOG(WARNING) << "Could not query Xkb extension"; } if (!XkbSelectEvents(display, XkbUseCoreKbd, XkbStateNotifyMask, XkbStateNotifyMask)) { LOG(WARNING) << "Could not install Xkb Indicator observer"; } #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) MessageLoopForUI::current()->AddObserver(this); #else gdk_window_add_filter(NULL, GdkEventFilter, this); #endif } SystemKeyEventListener::~SystemKeyEventListener() { Stop(); } void SystemKeyEventListener::Stop() { if (stopped_) return; #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) MessageLoopForUI::current()->RemoveObserver(this); #else gdk_window_remove_filter(NULL, GdkEventFilter, this); #endif stopped_ = true; } AudioHandler* SystemKeyEventListener::GetAudioHandler() const { AudioHandler* audio_handler = AudioHandler::GetInstance(); if (!audio_handler || !audio_handler->IsInitialized()) return NULL; return audio_handler; } void SystemKeyEventListener::AddCapsLockObserver(CapsLockObserver* observer) { caps_lock_observers_.AddObserver(observer); } void SystemKeyEventListener::RemoveCapsLockObserver( CapsLockObserver* observer) { caps_lock_observers_.RemoveObserver(observer); } #if defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) base::EventStatus SystemKeyEventListener::WillProcessEvent( const base::NativeEvent& event) { return ProcessedXEvent(event) ? base::EVENT_HANDLED : base::EVENT_CONTINUE; } void SystemKeyEventListener::DidProcessEvent(const base::NativeEvent& event) { } #else // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) // static GdkFilterReturn SystemKeyEventListener::GdkEventFilter(GdkXEvent* gxevent, GdkEvent* gevent, gpointer data) { SystemKeyEventListener* listener = static_cast<SystemKeyEventListener*>(data); XEvent* xevent = static_cast<XEvent*>(gxevent); return listener->ProcessedXEvent(xevent) ? GDK_FILTER_REMOVE : GDK_FILTER_CONTINUE; } #endif // defined(TOUCH_UI) || !defined(TOOLKIT_USES_GTK) void SystemKeyEventListener::GrabKey(int32 key, uint32 mask) { uint32 num_lock_mask = Mod2Mask; uint32 caps_lock_mask = LockMask; Display* display = ui::GetXDisplay(); Window root = DefaultRootWindow(display); XGrabKey(display, key, mask, root, True, GrabModeAsync, GrabModeAsync); XGrabKey(display, key, mask | caps_lock_mask, root, True, GrabModeAsync, GrabModeAsync); XGrabKey(display, key, mask | num_lock_mask, root, True, GrabModeAsync, GrabModeAsync); XGrabKey(display, key, mask | caps_lock_mask | num_lock_mask, root, True, GrabModeAsync, GrabModeAsync); } void SystemKeyEventListener::OnBrightnessDown() { DBusThreadManager::Get()->power_manager_client()-> DecreaseScreenBrightness(true); } void SystemKeyEventListener::OnBrightnessUp() { DBusThreadManager::Get()->power_manager_client()-> IncreaseScreenBrightness(); } void SystemKeyEventListener::OnVolumeMute() { AudioHandler* audio_handler = GetAudioHandler(); if (!audio_handler) return; // Always muting (and not toggling) as per final decision on // http://crosbug.com/3751 audio_handler->SetMuted(true); SendAccessibilityVolumeNotification( audio_handler->GetVolumePercent(), audio_handler->IsMuted()); ShowVolumeBubble(); } void SystemKeyEventListener::OnVolumeDown() { AudioHandler* audio_handler = GetAudioHandler(); if (!audio_handler) return; if (audio_handler->IsMuted()) audio_handler->SetVolumePercent(0.0); else audio_handler->AdjustVolumeByPercent(-kStepPercentage); SendAccessibilityVolumeNotification( audio_handler->GetVolumePercent(), audio_handler->IsMuted()); ShowVolumeBubble(); } void SystemKeyEventListener::OnVolumeUp() { AudioHandler* audio_handler = GetAudioHandler(); if (!audio_handler) return; if (audio_handler->IsMuted()) { audio_handler->SetMuted(false); if (audio_handler->GetVolumePercent() <= 0.1) // float comparison audio_handler->SetVolumePercent(kVolumePercentOnVolumeUpWhileMuted); } else { audio_handler->AdjustVolumeByPercent(kStepPercentage); } SendAccessibilityVolumeNotification( audio_handler->GetVolumePercent(), audio_handler->IsMuted()); ShowVolumeBubble(); } void SystemKeyEventListener::OnCapsLock(bool enabled) { FOR_EACH_OBSERVER( CapsLockObserver, caps_lock_observers_, OnCapsLockChange(enabled)); } void SystemKeyEventListener::ShowVolumeBubble() { AudioHandler* audio_handler = GetAudioHandler(); if (audio_handler) { VolumeBubble::GetInstance()->ShowBubble( audio_handler->GetVolumePercent(), !audio_handler->IsMuted()); } BrightnessBubble::GetInstance()->HideBubble(); } bool SystemKeyEventListener::ProcessedXEvent(XEvent* xevent) { if (xevent->type == KeyPress || xevent->type == KeyRelease) { // Change the current keyboard layout (or input method) if xevent is one of // the input method hotkeys. input_method::HotkeyManager* hotkey_manager = input_method::InputMethodManager::GetInstance()->GetHotkeyManager(); if (hotkey_manager->FilterKeyEvent(*xevent)) { return true; } } if (xevent->type == xkb_event_base_) { XkbEvent* xkey_event = reinterpret_cast<XkbEvent*>(xevent); if (xkey_event->any.xkb_type == XkbStateNotify) { const bool new_lock_state = (xkey_event->state.locked_mods) & LockMask; if (caps_lock_is_on_ != new_lock_state) { caps_lock_is_on_ = new_lock_state; OnCapsLock(caps_lock_is_on_); } return true; } } else if (xevent->type == KeyPress) { const int32 keycode = xevent->xkey.keycode; if (keycode) { // Toggle Caps Lock if both Shift keys are pressed simultaneously. if (keycode == key_left_shift_ || keycode == key_right_shift_) { const bool other_shift_is_held = (xevent->xkey.state & ShiftMask); const bool other_mods_are_held = (xevent->xkey.state & ~(ShiftMask | LockMask)); if (other_shift_is_held && !other_mods_are_held) input_method::XKeyboard::SetCapsLockEnabled(!caps_lock_is_on_); } // Only doing non-Alt/Shift/Ctrl modified keys if (!(xevent->xkey.state & (Mod1Mask | ShiftMask | ControlMask))) { if (keycode == key_f6_ || keycode == key_brightness_down_) { if (keycode == key_f6_) UserMetrics::RecordAction( UserMetricsAction("Accel_BrightnessDown_F6")); OnBrightnessDown(); return true; } else if (keycode == key_f7_ || keycode == key_brightness_up_) { if (keycode == key_f7_) UserMetrics::RecordAction( UserMetricsAction("Accel_BrightnessUp_F7")); OnBrightnessUp(); return true; } else if (keycode == key_f8_ || keycode == key_volume_mute_) { if (keycode == key_f8_) UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeMute_F8")); OnVolumeMute(); return true; } else if (keycode == key_f9_ || keycode == key_volume_down_) { if (keycode == key_f9_) UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeDown_F9")); OnVolumeDown(); return true; } else if (keycode == key_f10_ || keycode == key_volume_up_) { if (keycode == key_f10_) UserMetrics::RecordAction(UserMetricsAction("Accel_VolumeUp_F10")); OnVolumeUp(); return true; } } } } return false; } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/clear_browsing_data_dialog_gtk.h" #include <string> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "chrome/browser/browser.h" #include "chrome/browser/browsing_data_remover.h" #include "chrome/browser/gtk/accessible_widget_helper_gtk.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/gtk/gtk_chrome_link_button.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" namespace { // Returns true if the checkbox is checked. gboolean IsChecked(GtkWidget* widget) { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); } } // namespace // static void ClearBrowsingDataDialogGtk::Show(GtkWindow* parent, Profile* profile) { new ClearBrowsingDataDialogGtk(parent, profile); } ClearBrowsingDataDialogGtk::ClearBrowsingDataDialogGtk(GtkWindow* parent, Profile* profile) : profile_(profile), remover_(NULL) { // Build the dialog. std::string dialog_name = l10n_util::GetStringUTF8( IDS_CLEAR_BROWSING_DATA_TITLE); dialog_ = gtk_dialog_new_with_buttons( dialog_name.c_str(), parent, (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), GTK_STOCK_CLOSE, GTK_RESPONSE_REJECT, NULL); accessible_widget_helper_.reset(new AccessibleWidgetHelper(dialog_, profile)); accessible_widget_helper_->SendOpenWindowNotification(dialog_name); gtk_util::AddButtonToDialog(dialog_, l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(), GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT); GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox; gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); gtk_container_add(GTK_CONTAINER(content_area), vbox); // Label on top of the checkboxes. GtkWidget* description = gtk_label_new( l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_LABEL).c_str()); gtk_misc_set_alignment(GTK_MISC(description), 0, 0); gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0); // History checkbox. del_history_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_BROWSING_HISTORY_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_history_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_history_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteBrowsingHistory)); g_signal_connect(del_history_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Downloads checkbox. del_downloads_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_downloads_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_downloads_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteDownloadHistory)); g_signal_connect(del_downloads_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Cache checkbox. del_cache_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_CACHE_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_cache_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteCache)); g_signal_connect(del_cache_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Cookies checkbox. del_cookies_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_COOKIES_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_cookies_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteCookies)); g_signal_connect(del_cookies_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Passwords checkbox. del_passwords_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_PASSWORDS_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_passwords_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_passwords_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeletePasswords)); g_signal_connect(del_passwords_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Form data checkbox. del_form_data_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_FORM_DATA_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_form_data_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_form_data_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteFormData)); g_signal_connect(del_form_data_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Create a horizontal layout for the combo box and label. GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing); GtkWidget* time_period_label_ = gtk_label_new( l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TIME_LABEL).c_str()); gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_label_, FALSE, FALSE, 0); // Time period combo box items. time_period_combobox_ = gtk_combo_box_new_text(); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_HOUR).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_DAY).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_WEEK).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_4WEEKS).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_EVERYTHING).c_str()); gtk_combo_box_set_active(GTK_COMBO_BOX(time_period_combobox_), profile_->GetPrefs()->GetInteger(prefs::kDeleteTimePeriod)); gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_combobox_, FALSE, FALSE, 0); g_signal_connect(time_period_combobox_, "changed", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Add the combo/label time period box to the vertical layout. gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0); // Add widgets for the area below the accept buttons. GtkWidget* flash_link = gtk_chrome_link_button_new( l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_SETTINGS).c_str()); g_signal_connect(G_OBJECT(flash_link), "clicked", G_CALLBACK(OnFlashLinkClickedThunk), this); GtkWidget* flash_link_hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(flash_link_hbox), flash_link, FALSE, FALSE, 0); gtk_box_pack_end(GTK_BOX(content_area), flash_link_hbox, FALSE, FALSE, 0); GtkWidget* separator = gtk_hseparator_new(); gtk_box_pack_end(GTK_BOX(content_area), separator, FALSE, FALSE, 0); // Make sure we can move things around. DCHECK_EQ(GTK_DIALOG(dialog_)->action_area->parent, content_area); // Now rearrange those because they're *above* the accept buttons...there's // no way to place them in the correct position with gtk_box_pack_end() so // manually move things into the correct order. gtk_box_reorder_child(GTK_BOX(content_area), flash_link_hbox, -1); gtk_box_reorder_child(GTK_BOX(content_area), separator, -1); gtk_box_reorder_child(GTK_BOX(content_area), GTK_DIALOG(dialog_)->action_area, -1); g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponseThunk), this); UpdateDialogButtons(); gtk_util::ShowDialogWithLocalizedSize(dialog_, IDS_CLEARDATA_DIALOG_WIDTH_CHARS, -1, false); } ClearBrowsingDataDialogGtk::~ClearBrowsingDataDialogGtk() { } void ClearBrowsingDataDialogGtk::OnDialogResponse(GtkWidget* widget, int response) { if (response == GTK_RESPONSE_ACCEPT) { int period_selected = gtk_combo_box_get_active( GTK_COMBO_BOX(time_period_combobox_)); // BrowsingDataRemover deletes itself when done. remover_ = new BrowsingDataRemover(profile_, static_cast<BrowsingDataRemover::TimePeriod>(period_selected), base::Time()); remover_->Remove(GetCheckedItems()); } delete this; gtk_widget_destroy(GTK_WIDGET(widget)); } void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) { if (widget == del_history_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory, IsChecked(widget)); } else if (widget == del_downloads_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory, IsChecked(widget)); } else if (widget == del_cache_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache, IsChecked(widget)); } else if (widget == del_cookies_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies, IsChecked(widget)); } else if (widget == del_passwords_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords, IsChecked(widget)); } else if (widget == del_form_data_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData, IsChecked(widget)); } else if (widget == time_period_combobox_) { profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod, gtk_combo_box_get_active(GTK_COMBO_BOX(widget))); } UpdateDialogButtons(); } void ClearBrowsingDataDialogGtk::OnFlashLinkClicked(GtkWidget* button) { // We open a new browser window so the Options dialog doesn't get lost // behind other windows. Browser* browser = Browser::Create(profile_); browser->OpenURL(GURL(l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_URL)), GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK); browser->window()->Show(); } void ClearBrowsingDataDialogGtk::UpdateDialogButtons() { gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT, GetCheckedItems() != 0); } int ClearBrowsingDataDialogGtk::GetCheckedItems() { int items = 0; if (IsChecked(del_history_checkbox_)) items |= BrowsingDataRemover::REMOVE_HISTORY; if (IsChecked(del_downloads_checkbox_)) items |= BrowsingDataRemover::REMOVE_DOWNLOADS; if (IsChecked(del_cookies_checkbox_)) items |= BrowsingDataRemover::REMOVE_COOKIES; if (IsChecked(del_passwords_checkbox_)) items |= BrowsingDataRemover::REMOVE_PASSWORDS; if (IsChecked(del_form_data_checkbox_)) items |= BrowsingDataRemover::REMOVE_FORM_DATA; if (IsChecked(del_cache_checkbox_)) items |= BrowsingDataRemover::REMOVE_CACHE; return items; } <commit_msg>Make "Clear Browser Data" dialog wider for ja.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/clear_browsing_data_dialog_gtk.h" #include <string> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "chrome/browser/browser.h" #include "chrome/browser/browsing_data_remover.h" #include "chrome/browser/gtk/accessible_widget_helper_gtk.h" #include "chrome/browser/gtk/browser_window_gtk.h" #include "chrome/browser/gtk/gtk_chrome_link_button.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" namespace { // Returns true if the checkbox is checked. gboolean IsChecked(GtkWidget* widget) { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); } } // namespace // static void ClearBrowsingDataDialogGtk::Show(GtkWindow* parent, Profile* profile) { new ClearBrowsingDataDialogGtk(parent, profile); } ClearBrowsingDataDialogGtk::ClearBrowsingDataDialogGtk(GtkWindow* parent, Profile* profile) : profile_(profile), remover_(NULL) { // Build the dialog. std::string dialog_name = l10n_util::GetStringUTF8( IDS_CLEAR_BROWSING_DATA_TITLE); dialog_ = gtk_dialog_new_with_buttons( dialog_name.c_str(), parent, (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), GTK_STOCK_CLOSE, GTK_RESPONSE_REJECT, NULL); accessible_widget_helper_.reset(new AccessibleWidgetHelper(dialog_, profile)); accessible_widget_helper_->SendOpenWindowNotification(dialog_name); gtk_util::AddButtonToDialog(dialog_, l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_COMMIT).c_str(), GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT); GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox; gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); gtk_container_add(GTK_CONTAINER(content_area), vbox); // Label on top of the checkboxes. GtkWidget* description = gtk_label_new( l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_LABEL).c_str()); gtk_misc_set_alignment(GTK_MISC(description), 0, 0); gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0); // History checkbox. del_history_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_BROWSING_HISTORY_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_history_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_history_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteBrowsingHistory)); g_signal_connect(del_history_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Downloads checkbox. del_downloads_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_DOWNLOAD_HISTORY_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_downloads_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_downloads_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteDownloadHistory)); g_signal_connect(del_downloads_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Cache checkbox. del_cache_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_CACHE_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_cache_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cache_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteCache)); g_signal_connect(del_cache_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Cookies checkbox. del_cookies_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_COOKIES_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_cookies_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_cookies_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteCookies)); g_signal_connect(del_cookies_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Passwords checkbox. del_passwords_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_PASSWORDS_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_passwords_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_passwords_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeletePasswords)); g_signal_connect(del_passwords_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Form data checkbox. del_form_data_checkbox_ = gtk_check_button_new_with_label( l10n_util::GetStringUTF8(IDS_DEL_FORM_DATA_CHKBOX).c_str()); gtk_box_pack_start(GTK_BOX(vbox), del_form_data_checkbox_, FALSE, FALSE, 0); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(del_form_data_checkbox_), profile_->GetPrefs()->GetBoolean(prefs::kDeleteFormData)); g_signal_connect(del_form_data_checkbox_, "toggled", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Create a horizontal layout for the combo box and label. GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing); GtkWidget* time_period_label_ = gtk_label_new( l10n_util::GetStringUTF8(IDS_CLEAR_BROWSING_DATA_TIME_LABEL).c_str()); gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_label_, FALSE, FALSE, 0); // Time period combo box items. time_period_combobox_ = gtk_combo_box_new_text(); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_HOUR).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_DAY).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_WEEK).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_4WEEKS).c_str()); gtk_combo_box_append_text(GTK_COMBO_BOX(time_period_combobox_), l10n_util::GetStringUTF8(IDS_CLEAR_DATA_EVERYTHING).c_str()); gtk_combo_box_set_active(GTK_COMBO_BOX(time_period_combobox_), profile_->GetPrefs()->GetInteger(prefs::kDeleteTimePeriod)); gtk_box_pack_start(GTK_BOX(combo_hbox), time_period_combobox_, FALSE, FALSE, 0); g_signal_connect(time_period_combobox_, "changed", G_CALLBACK(OnDialogWidgetClickedThunk), this); // Add the combo/label time period box to the vertical layout. gtk_box_pack_start(GTK_BOX(vbox), combo_hbox, FALSE, FALSE, 0); // Add widgets for the area below the accept buttons. GtkWidget* flash_link = gtk_chrome_link_button_new( l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_SETTINGS).c_str()); g_signal_connect(G_OBJECT(flash_link), "clicked", G_CALLBACK(OnFlashLinkClickedThunk), this); GtkWidget* flash_link_hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(flash_link_hbox), flash_link, FALSE, FALSE, 0); gtk_box_pack_end(GTK_BOX(content_area), flash_link_hbox, FALSE, FALSE, 0); GtkWidget* separator = gtk_hseparator_new(); gtk_box_pack_end(GTK_BOX(content_area), separator, FALSE, FALSE, 0); // Make sure we can move things around. DCHECK_EQ(GTK_DIALOG(dialog_)->action_area->parent, content_area); // Now rearrange those because they're *above* the accept buttons...there's // no way to place them in the correct position with gtk_box_pack_end() so // manually move things into the correct order. gtk_box_reorder_child(GTK_BOX(content_area), flash_link_hbox, -1); gtk_box_reorder_child(GTK_BOX(content_area), separator, -1); gtk_box_reorder_child(GTK_BOX(content_area), GTK_DIALOG(dialog_)->action_area, -1); g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponseThunk), this); UpdateDialogButtons(); gtk_util::ShowModalDialogWithMinLocalizedWidth(dialog_, IDS_CLEARDATA_DIALOG_WIDTH_CHARS); } ClearBrowsingDataDialogGtk::~ClearBrowsingDataDialogGtk() { } void ClearBrowsingDataDialogGtk::OnDialogResponse(GtkWidget* widget, int response) { if (response == GTK_RESPONSE_ACCEPT) { int period_selected = gtk_combo_box_get_active( GTK_COMBO_BOX(time_period_combobox_)); // BrowsingDataRemover deletes itself when done. remover_ = new BrowsingDataRemover(profile_, static_cast<BrowsingDataRemover::TimePeriod>(period_selected), base::Time()); remover_->Remove(GetCheckedItems()); } delete this; gtk_widget_destroy(GTK_WIDGET(widget)); } void ClearBrowsingDataDialogGtk::OnDialogWidgetClicked(GtkWidget* widget) { if (widget == del_history_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteBrowsingHistory, IsChecked(widget)); } else if (widget == del_downloads_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteDownloadHistory, IsChecked(widget)); } else if (widget == del_cache_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteCache, IsChecked(widget)); } else if (widget == del_cookies_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteCookies, IsChecked(widget)); } else if (widget == del_passwords_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeletePasswords, IsChecked(widget)); } else if (widget == del_form_data_checkbox_) { profile_->GetPrefs()->SetBoolean(prefs::kDeleteFormData, IsChecked(widget)); } else if (widget == time_period_combobox_) { profile_->GetPrefs()->SetInteger(prefs::kDeleteTimePeriod, gtk_combo_box_get_active(GTK_COMBO_BOX(widget))); } UpdateDialogButtons(); } void ClearBrowsingDataDialogGtk::OnFlashLinkClicked(GtkWidget* button) { // We open a new browser window so the Options dialog doesn't get lost // behind other windows. Browser* browser = Browser::Create(profile_); browser->OpenURL(GURL(l10n_util::GetStringUTF8(IDS_FLASH_STORAGE_URL)), GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK); browser->window()->Show(); } void ClearBrowsingDataDialogGtk::UpdateDialogButtons() { gtk_dialog_set_response_sensitive(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT, GetCheckedItems() != 0); } int ClearBrowsingDataDialogGtk::GetCheckedItems() { int items = 0; if (IsChecked(del_history_checkbox_)) items |= BrowsingDataRemover::REMOVE_HISTORY; if (IsChecked(del_downloads_checkbox_)) items |= BrowsingDataRemover::REMOVE_DOWNLOADS; if (IsChecked(del_cookies_checkbox_)) items |= BrowsingDataRemover::REMOVE_COOKIES; if (IsChecked(del_passwords_checkbox_)) items |= BrowsingDataRemover::REMOVE_PASSWORDS; if (IsChecked(del_form_data_checkbox_)) items |= BrowsingDataRemover::REMOVE_FORM_DATA; if (IsChecked(del_cache_checkbox_)) items |= BrowsingDataRemover::REMOVE_CACHE; return items; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/extension_error_reporter.h" #include "build/build_config.h" #if defined(OS_WIN) #include "app/win_util.h" #elif defined(OS_MACOSX) #include "base/scoped_cftyperef.h" #include "base/sys_string_conversions.h" #include <CoreFoundation/CFUserNotification.h> #endif #include "base/logging.h" #include "base/message_loop.h" #include "base/string_util.h" // No AddRef required when using ExtensionErrorReporter with RunnableMethod. // This is okay since the ExtensionErrorReporter is a singleton that lives until // the end of the process. template <> struct RunnableMethodTraits<ExtensionErrorReporter> { static void RetainCallee(ExtensionErrorReporter*) {} static void ReleaseCallee(ExtensionErrorReporter*) {} }; ExtensionErrorReporter* ExtensionErrorReporter::instance_ = NULL; // static void ExtensionErrorReporter::Init(bool enable_noisy_errors) { if (!instance_) { instance_ = new ExtensionErrorReporter(enable_noisy_errors); } } // static ExtensionErrorReporter* ExtensionErrorReporter::GetInstance() { CHECK(instance_) << "Init() was never called"; return instance_; } ExtensionErrorReporter::ExtensionErrorReporter(bool enable_noisy_errors) : ui_loop_(MessageLoop::current()), enable_noisy_errors_(enable_noisy_errors) { } void ExtensionErrorReporter::ReportError(const std::string& message, bool be_noisy) { // NOTE: There won't be a ui_loop_ in the unit test environment. if (ui_loop_ && MessageLoop::current() != ui_loop_) { ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &ExtensionErrorReporter::ReportError, message, be_noisy)); return; } errors_.push_back(message); // TODO(aa): Print the error message out somewhere better. I think we are // going to need some sort of 'extension inspector'. LOG(WARNING) << message; if (enable_noisy_errors_ && be_noisy) { #if defined(OS_WIN) win_util::MessageBox(NULL, UTF8ToWide(message), L"Extension error", MB_OK | MB_SETFOREGROUND); #elif defined(OS_MACOSX) // There must be a better way to do this, for all platforms. scoped_cftyperef<CFStringRef> message_cf( base::SysUTF8ToCFStringRef(message)); CFOptionFlags response; CFUserNotificationDisplayAlert( 0, kCFUserNotificationCautionAlertLevel, NULL, NULL, NULL, CFSTR("Extension error"), message_cf, NULL, NULL, NULL, &response); #else // TODO(port) #endif } } const std::vector<std::string>* ExtensionErrorReporter::GetErrors() { return &errors_; } void ExtensionErrorReporter::ClearErrors() { errors_.clear(); } <commit_msg>Increase the severity of the warning that is logged on extension load failure. This doesn't fix the bug, but might help with debugging until we have an alert box.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/extension_error_reporter.h" #include "build/build_config.h" #if defined(OS_WIN) #include "app/win_util.h" #elif defined(OS_MACOSX) #include "base/scoped_cftyperef.h" #include "base/sys_string_conversions.h" #include <CoreFoundation/CFUserNotification.h> #endif #include "base/logging.h" #include "base/message_loop.h" #include "base/string_util.h" // No AddRef required when using ExtensionErrorReporter with RunnableMethod. // This is okay since the ExtensionErrorReporter is a singleton that lives until // the end of the process. template <> struct RunnableMethodTraits<ExtensionErrorReporter> { static void RetainCallee(ExtensionErrorReporter*) {} static void ReleaseCallee(ExtensionErrorReporter*) {} }; ExtensionErrorReporter* ExtensionErrorReporter::instance_ = NULL; // static void ExtensionErrorReporter::Init(bool enable_noisy_errors) { if (!instance_) { instance_ = new ExtensionErrorReporter(enable_noisy_errors); } } // static ExtensionErrorReporter* ExtensionErrorReporter::GetInstance() { CHECK(instance_) << "Init() was never called"; return instance_; } ExtensionErrorReporter::ExtensionErrorReporter(bool enable_noisy_errors) : ui_loop_(MessageLoop::current()), enable_noisy_errors_(enable_noisy_errors) { } void ExtensionErrorReporter::ReportError(const std::string& message, bool be_noisy) { // NOTE: There won't be a ui_loop_ in the unit test environment. if (ui_loop_ && MessageLoop::current() != ui_loop_) { ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &ExtensionErrorReporter::ReportError, message, be_noisy)); return; } errors_.push_back(message); // TODO(aa): Print the error message out somewhere better. I think we are // going to need some sort of 'extension inspector'. LOG(ERROR) << "Extension error: " << message; if (enable_noisy_errors_ && be_noisy) { #if defined(OS_WIN) win_util::MessageBox(NULL, UTF8ToWide(message), L"Extension error", MB_OK | MB_SETFOREGROUND); #elif defined(OS_MACOSX) // There must be a better way to do this, for all platforms. scoped_cftyperef<CFStringRef> message_cf( base::SysUTF8ToCFStringRef(message)); CFOptionFlags response; CFUserNotificationDisplayAlert( 0, kCFUserNotificationCautionAlertLevel, NULL, NULL, NULL, CFSTR("Extension error"), message_cf, NULL, NULL, NULL, &response); #else // TODO(port) #endif } } const std::vector<std::string>* ExtensionErrorReporter::GetErrors() { return &errors_; } void ExtensionErrorReporter::ClearErrors() { errors_.clear(); } <|endoftext|>
<commit_before>/* * Copyright 2006 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // Most of this was borrowed (with minor modifications) from V8's and Chromium's // src/base/logging.cc. #include <cstdarg> #include <cstdio> #include <cstdlib> #if defined(WEBRTC_ANDROID) #define RTC_LOG_TAG_ANDROID "rtc" #include <android/log.h> // NOLINT #endif #if defined(WEBRTC_WIN) #include <windows.h> #endif #if defined(WEBRTC_WIN) #define LAST_SYSTEM_ERROR (::GetLastError()) #elif defined(__native_client__) && __native_client__ #define LAST_SYSTEM_ERROR (0) #elif defined(WEBRTC_POSIX) #define LAST_SYSTEM_ERROR (errno) #endif // WEBRTC_WIN #include "rtc_base/checks.h" #if defined(_MSC_VER) // Warning C4722: destructor never returns, potential memory leak. // FatalMessage's dtor very intentionally aborts. #pragma warning(disable:4722) #endif namespace rtc { namespace { void VPrintError(const char* format, va_list args) { #if defined(WEBRTC_ANDROID) __android_log_vprint(ANDROID_LOG_ERROR, RTC_LOG_TAG_ANDROID, format, args); #else vfprintf(stderr, format, args); #endif } #if defined(__GNUC__) void PrintError(const char* format, ...) __attribute__((__format__(__printf__, 1, 2))); #endif void PrintError(const char* format, ...) { va_list args; va_start(args, format); VPrintError(format, args); va_end(args); } } // namespace FatalMessage::FatalMessage(const char* file, int line) { Init(file, line); } FatalMessage::FatalMessage(const char* file, int line, std::string* result) { Init(file, line); stream_ << "Check failed: " << *result << std::endl << "# "; delete result; } NO_RETURN FatalMessage::~FatalMessage() { fflush(stdout); fflush(stderr); stream_ << std::endl << "#" << std::endl; PrintError("%s", stream_.str().c_str()); fflush(stderr); abort(); } void FatalMessage::Init(const char* file, int line) { stream_ << std::endl << std::endl << "#" << std::endl << "# Fatal error in " << file << ", line " << line << std::endl << "# last system error: " << LAST_SYSTEM_ERROR << std::endl << "# "; } // MSVC doesn't like complex extern templates and DLLs. #if !defined(COMPILER_MSVC) // Explicit instantiations for commonly used comparisons. template std::string* MakeCheckOpString<int, int>( const int&, const int&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned long>( const unsigned long&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned int>( const unsigned long&, const unsigned int&, const char* names); template std::string* MakeCheckOpString<unsigned int, unsigned long>( const unsigned int&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<std::string, std::string>( const std::string&, const std::string&, const char* name); #endif } // namespace rtc // Function to call from the C version of the RTC_CHECK and RTC_DCHECK macros. NO_RETURN void rtc_FatalMessage(const char* file, int line, const char* msg) { rtc::FatalMessage(file, line).stream() << msg; } <commit_msg>Add the missing header for `errno` variable in `checks.cc`<commit_after>/* * Copyright 2006 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // Most of this was borrowed (with minor modifications) from V8's and Chromium's // src/base/logging.cc. #include <cstdarg> #include <cstdio> #include <cstdlib> #if defined(WEBRTC_ANDROID) #define RTC_LOG_TAG_ANDROID "rtc" #include <android/log.h> // NOLINT #endif #if defined(WEBRTC_WIN) #include <windows.h> #endif #if defined(WEBRTC_WIN) #define LAST_SYSTEM_ERROR (::GetLastError()) #elif defined(__native_client__) && __native_client__ #define LAST_SYSTEM_ERROR (0) #elif defined(WEBRTC_POSIX) #include <errno.h> #define LAST_SYSTEM_ERROR (errno) #endif // WEBRTC_WIN #include "rtc_base/checks.h" #if defined(_MSC_VER) // Warning C4722: destructor never returns, potential memory leak. // FatalMessage's dtor very intentionally aborts. #pragma warning(disable:4722) #endif namespace rtc { namespace { void VPrintError(const char* format, va_list args) { #if defined(WEBRTC_ANDROID) __android_log_vprint(ANDROID_LOG_ERROR, RTC_LOG_TAG_ANDROID, format, args); #else vfprintf(stderr, format, args); #endif } #if defined(__GNUC__) void PrintError(const char* format, ...) __attribute__((__format__(__printf__, 1, 2))); #endif void PrintError(const char* format, ...) { va_list args; va_start(args, format); VPrintError(format, args); va_end(args); } } // namespace FatalMessage::FatalMessage(const char* file, int line) { Init(file, line); } FatalMessage::FatalMessage(const char* file, int line, std::string* result) { Init(file, line); stream_ << "Check failed: " << *result << std::endl << "# "; delete result; } NO_RETURN FatalMessage::~FatalMessage() { fflush(stdout); fflush(stderr); stream_ << std::endl << "#" << std::endl; PrintError("%s", stream_.str().c_str()); fflush(stderr); abort(); } void FatalMessage::Init(const char* file, int line) { stream_ << std::endl << std::endl << "#" << std::endl << "# Fatal error in " << file << ", line " << line << std::endl << "# last system error: " << LAST_SYSTEM_ERROR << std::endl << "# "; } // MSVC doesn't like complex extern templates and DLLs. #if !defined(COMPILER_MSVC) // Explicit instantiations for commonly used comparisons. template std::string* MakeCheckOpString<int, int>( const int&, const int&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned long>( const unsigned long&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned int>( const unsigned long&, const unsigned int&, const char* names); template std::string* MakeCheckOpString<unsigned int, unsigned long>( const unsigned int&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<std::string, std::string>( const std::string&, const std::string&, const char* name); #endif } // namespace rtc // Function to call from the C version of the RTC_CHECK and RTC_DCHECK macros. NO_RETURN void rtc_FatalMessage(const char* file, int line, const char* msg) { rtc::FatalMessage(file, line).stream() << msg; } <|endoftext|>
<commit_before>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-06-30 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/scheduler/RoundRobinQuantum.hpp" #include "distortos/scheduler/ThreadControlBlockList-types.hpp" #include "distortos/scheduler/MutexControlBlockList.hpp" #include "distortos/architecture/Stack.hpp" #include "distortos/SchedulingPolicy.hpp" #include "distortos/estd/TypeErasedFunctor.hpp" namespace distortos { class SignalsReceiver; namespace synchronization { class SignalsReceiverControlBlock; } // namespace synchronization namespace scheduler { class ThreadControlBlockList; class ThreadGroupControlBlock; /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, /// thread is terminated Terminated, /// thread is sleeping Sleeping, /// thread is blocked on Semaphore BlockedOnSemaphore, /// thread is suspended Suspended, /// thread is blocked on Mutex BlockedOnMutex, /// thread is blocked on ConditionVariable BlockedOnConditionVariable, /// thread is waiting for signal WaitingForSignal, }; /// reason of thread unblocking enum class UnblockReason : uint8_t { /// explicit request to unblock the thread - normal unblock UnblockRequest, /// timeout - unblock via software timer Timeout, /// signal handler - unblock to deliver unmasked signal Signal, }; /// type of object used as storage for ThreadControlBlockList elements - 3 pointers using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>; /// UnblockFunctor is a functor executed when unblocking the thread, it receives two parameter - a reference to /// ThreadControlBlock that is being unblocked and the reason of thread unblocking class UnblockFunctor : public estd::TypeErasedFunctor<void(ThreadControlBlock&, UnblockReason)> { }; /** * \brief ThreadControlBlock constructor. * * \param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will * be added, nullptr to inherit thread group from currently running thread * \param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception * of signals for this thread * \param [in] owner is a reference to ThreadBase object that owns this ThreadControlBlock */ ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy, ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver, ThreadBase& owner); /** * \brief ThreadControlBlock's destructor */ ~ThreadControlBlock(); /** * \brief Hook function executed when thread is added to scheduler. * * If threadGroupControlBlock_ is nullptr, it is inherited from currently running thread. Then this object is added * to the thread group (if it is valid). * * \attention This function should be called only by Scheduler::addInternal(). * * \return 0 on success, error code otherwise: * - EINVAL - inherited thread group is invalid; */ int addHook(); /** * \brief Block hook function of thread * * Saves pointer to UnblockFunctor. * * \attention This function should be called only by Scheduler::blockInternal(). * * \param [in] unblockFunctor is a pointer to UnblockFunctor which will be executed in unblockHook() */ void blockHook(const UnblockFunctor* const unblockFunctor) { unblockFunctor_ = unblockFunctor; } /** * \return effective priority of ThreadControlBlock */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return iterator to the element on the list, valid only when list_ != nullptr */ ThreadControlBlockListIterator getIterator() const { return iterator_; } /** * \return reference to internal storage for list link */ Link& getLink() { return link_; } /** * \return pointer to list that has this object */ ThreadControlBlockList* getList() const { return list_; } /** * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread */ MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() { return ownedProtocolMutexControlBlocksList_; } /** * \return reference to ThreadBase object that owns this ThreadControlBlock */ ThreadBase& getOwner() const { return owner_; } /** * \return priority of ThreadControlBlock */ uint8_t getPriority() const { return priority_; } /** * \return reference to internal RoundRobinQuantum object */ RoundRobinQuantum& getRoundRobinQuantum() { return roundRobinQuantum_; } /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const { return schedulingPolicy_; } /** * \return pointer to synchronization::SignalsReceiverControlBlock object for this thread, nullptr if this thread * cannot receive signals */ synchronization::SignalsReceiverControlBlock* getSignalsReceiverControlBlock() const { return signalsReceiverControlBlock_; } /** * \return reference to internal Stack object */ architecture::Stack& getStack() { return stack_; } /** * \return current state of object */ State getState() const { return state_; } /** * \return reference to internal storage for thread group list link */ Link& getThreadGroupLink() { return threadGroupLink_; } /** * \brief Sets the iterator to the element on the list. * * \param [in] iterator is an iterator to the element on the list */ void setIterator(const ThreadControlBlockListIterator iterator) { iterator_ = iterator; } /** * \brief Sets the list that has this object. * * \param [in] list is a pointer to list that has this object */ void setList(ThreadControlBlockList* const list) { list_ = list; } /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}); /** * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance * protocol) that blocks this thread */ void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const priorityInheritanceMutexControlBlock) { priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock; } /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy); /** * \param [in] state is the new state of object */ void setState(const State state) { state_ = state; } /** * \brief Hook function called when context is switched to this thread. * * Sets global _impure_ptr (from newlib) to thread's \a reent_ member variable. * * \attention This function should be called only by Scheduler::switchContext(). */ void switchedToHook() { _impure_ptr = &reent_; } /** * \brief Unblock hook function of thread * * Resets round-robin's quantum and executes unblock functor saved in blockHook(). * * \attention This function should be called only by Scheduler::unblockInternal(). * * \param [in] unblockReason is the new reason of unblocking of the thread */ void unblockHook(UnblockReason unblockReason); /** * \brief Updates boosted priority of the thread. * * This function should be called after all operations involving this thread and a mutex with enabled priority * protocol. * * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that * is about to be blocked on a mutex owned by this thread, default - 0 */ void updateBoostedPriority(uint8_t boostedPriority = {}); ThreadControlBlock(const ThreadControlBlock&) = delete; ThreadControlBlock(ThreadControlBlock&&) = default; const ThreadControlBlock& operator=(const ThreadControlBlock&) = delete; ThreadControlBlock& operator=(ThreadControlBlock&&) = delete; private: /** * \brief Repositions the thread on the list it's currently on. * * This function should be called when thread's effective priority changes. * * \attention list_ must not be nullptr * * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the * priority is raised!): * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by * temporarily boosting effective priority by 1, * - false - the thread is moved to the tail of the group of threads with the new priority. */ void reposition(bool loweringBefore); /// internal stack object architecture::Stack stack_; /// storage for list link Link link_; /// storage for thread group list link Link threadGroupLink_; /// reference to ThreadBase object that owns this ThreadControlBlock ThreadBase& owner_; /// list of mutex control blocks with enabled priority protocol owned by this thread MutexControlBlockList ownedProtocolMutexControlBlocksList_; /// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_; /// pointer to list that has this object ThreadControlBlockList* list_; /// iterator to the element on the list, valid only when list_ != nullptr ThreadControlBlockListIterator iterator_; /// pointer to ThreadGroupControlBlock with which this object is associated ThreadGroupControlBlock* threadGroupControlBlock_; /// pointer to ThreadGroupControlBlock's list that has this object ThreadControlBlockUnsortedList* threadGroupList_; /// iterator to the element on the ThreadGroupControlBlock's list, valid only when threadGroupList_ != nullptr ThreadControlBlockListIterator threadGroupIterator_; /// functor executed in unblockHook() const UnblockFunctor* unblockFunctor_; /// pointer to synchronization::SignalsReceiverControlBlock object for this thread, nullptr if this thread cannot /// receive signals synchronization::SignalsReceiverControlBlock* signalsReceiverControlBlock_; /// newlib's _reent structure with thread-specific data _reent reent_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; /// round-robin quantum RoundRobinQuantum roundRobinQuantum_; /// scheduling policy of the thread SchedulingPolicy schedulingPolicy_; /// current state of object State state_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <commit_msg>ThreadControlBlock::State: add new value - ThreadControlBlock::State::BlockedOnOnceFlag<commit_after>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-07-09 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/scheduler/RoundRobinQuantum.hpp" #include "distortos/scheduler/ThreadControlBlockList-types.hpp" #include "distortos/scheduler/MutexControlBlockList.hpp" #include "distortos/architecture/Stack.hpp" #include "distortos/SchedulingPolicy.hpp" #include "distortos/estd/TypeErasedFunctor.hpp" namespace distortos { class SignalsReceiver; namespace synchronization { class SignalsReceiverControlBlock; } // namespace synchronization namespace scheduler { class ThreadControlBlockList; class ThreadGroupControlBlock; /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, /// thread is terminated Terminated, /// thread is sleeping Sleeping, /// thread is blocked on Semaphore BlockedOnSemaphore, /// thread is suspended Suspended, /// thread is blocked on Mutex BlockedOnMutex, /// thread is blocked on ConditionVariable BlockedOnConditionVariable, /// thread is waiting for signal WaitingForSignal, /// thread is blocked on OnceFlag BlockedOnOnceFlag }; /// reason of thread unblocking enum class UnblockReason : uint8_t { /// explicit request to unblock the thread - normal unblock UnblockRequest, /// timeout - unblock via software timer Timeout, /// signal handler - unblock to deliver unmasked signal Signal, }; /// type of object used as storage for ThreadControlBlockList elements - 3 pointers using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>; /// UnblockFunctor is a functor executed when unblocking the thread, it receives two parameter - a reference to /// ThreadControlBlock that is being unblocked and the reason of thread unblocking class UnblockFunctor : public estd::TypeErasedFunctor<void(ThreadControlBlock&, UnblockReason)> { }; /** * \brief ThreadControlBlock constructor. * * \param [in] stack is an rvalue reference to architecture::Stack object which will be adopted for this thread * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread * \param [in] threadGroupControlBlock is a pointer to scheduler::ThreadGroupControlBlock to which this object will * be added, nullptr to inherit thread group from currently running thread * \param [in] signalsReceiver is a pointer to SignalsReceiver object for this thread, nullptr to disable reception * of signals for this thread * \param [in] owner is a reference to ThreadBase object that owns this ThreadControlBlock */ ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy, ThreadGroupControlBlock* threadGroupControlBlock, SignalsReceiver* signalsReceiver, ThreadBase& owner); /** * \brief ThreadControlBlock's destructor */ ~ThreadControlBlock(); /** * \brief Hook function executed when thread is added to scheduler. * * If threadGroupControlBlock_ is nullptr, it is inherited from currently running thread. Then this object is added * to the thread group (if it is valid). * * \attention This function should be called only by Scheduler::addInternal(). * * \return 0 on success, error code otherwise: * - EINVAL - inherited thread group is invalid; */ int addHook(); /** * \brief Block hook function of thread * * Saves pointer to UnblockFunctor. * * \attention This function should be called only by Scheduler::blockInternal(). * * \param [in] unblockFunctor is a pointer to UnblockFunctor which will be executed in unblockHook() */ void blockHook(const UnblockFunctor* const unblockFunctor) { unblockFunctor_ = unblockFunctor; } /** * \return effective priority of ThreadControlBlock */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return iterator to the element on the list, valid only when list_ != nullptr */ ThreadControlBlockListIterator getIterator() const { return iterator_; } /** * \return reference to internal storage for list link */ Link& getLink() { return link_; } /** * \return pointer to list that has this object */ ThreadControlBlockList* getList() const { return list_; } /** * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread */ MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() { return ownedProtocolMutexControlBlocksList_; } /** * \return reference to ThreadBase object that owns this ThreadControlBlock */ ThreadBase& getOwner() const { return owner_; } /** * \return priority of ThreadControlBlock */ uint8_t getPriority() const { return priority_; } /** * \return reference to internal RoundRobinQuantum object */ RoundRobinQuantum& getRoundRobinQuantum() { return roundRobinQuantum_; } /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const { return schedulingPolicy_; } /** * \return pointer to synchronization::SignalsReceiverControlBlock object for this thread, nullptr if this thread * cannot receive signals */ synchronization::SignalsReceiverControlBlock* getSignalsReceiverControlBlock() const { return signalsReceiverControlBlock_; } /** * \return reference to internal Stack object */ architecture::Stack& getStack() { return stack_; } /** * \return current state of object */ State getState() const { return state_; } /** * \return reference to internal storage for thread group list link */ Link& getThreadGroupLink() { return threadGroupLink_; } /** * \brief Sets the iterator to the element on the list. * * \param [in] iterator is an iterator to the element on the list */ void setIterator(const ThreadControlBlockListIterator iterator) { iterator_ = iterator; } /** * \brief Sets the list that has this object. * * \param [in] list is a pointer to list that has this object */ void setList(ThreadControlBlockList* const list) { list_ = list; } /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}); /** * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance * protocol) that blocks this thread */ void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const priorityInheritanceMutexControlBlock) { priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock; } /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy); /** * \param [in] state is the new state of object */ void setState(const State state) { state_ = state; } /** * \brief Hook function called when context is switched to this thread. * * Sets global _impure_ptr (from newlib) to thread's \a reent_ member variable. * * \attention This function should be called only by Scheduler::switchContext(). */ void switchedToHook() { _impure_ptr = &reent_; } /** * \brief Unblock hook function of thread * * Resets round-robin's quantum and executes unblock functor saved in blockHook(). * * \attention This function should be called only by Scheduler::unblockInternal(). * * \param [in] unblockReason is the new reason of unblocking of the thread */ void unblockHook(UnblockReason unblockReason); /** * \brief Updates boosted priority of the thread. * * This function should be called after all operations involving this thread and a mutex with enabled priority * protocol. * * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that * is about to be blocked on a mutex owned by this thread, default - 0 */ void updateBoostedPriority(uint8_t boostedPriority = {}); ThreadControlBlock(const ThreadControlBlock&) = delete; ThreadControlBlock(ThreadControlBlock&&) = default; const ThreadControlBlock& operator=(const ThreadControlBlock&) = delete; ThreadControlBlock& operator=(ThreadControlBlock&&) = delete; private: /** * \brief Repositions the thread on the list it's currently on. * * This function should be called when thread's effective priority changes. * * \attention list_ must not be nullptr * * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the * priority is raised!): * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by * temporarily boosting effective priority by 1, * - false - the thread is moved to the tail of the group of threads with the new priority. */ void reposition(bool loweringBefore); /// internal stack object architecture::Stack stack_; /// storage for list link Link link_; /// storage for thread group list link Link threadGroupLink_; /// reference to ThreadBase object that owns this ThreadControlBlock ThreadBase& owner_; /// list of mutex control blocks with enabled priority protocol owned by this thread MutexControlBlockList ownedProtocolMutexControlBlocksList_; /// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_; /// pointer to list that has this object ThreadControlBlockList* list_; /// iterator to the element on the list, valid only when list_ != nullptr ThreadControlBlockListIterator iterator_; /// pointer to ThreadGroupControlBlock with which this object is associated ThreadGroupControlBlock* threadGroupControlBlock_; /// pointer to ThreadGroupControlBlock's list that has this object ThreadControlBlockUnsortedList* threadGroupList_; /// iterator to the element on the ThreadGroupControlBlock's list, valid only when threadGroupList_ != nullptr ThreadControlBlockListIterator threadGroupIterator_; /// functor executed in unblockHook() const UnblockFunctor* unblockFunctor_; /// pointer to synchronization::SignalsReceiverControlBlock object for this thread, nullptr if this thread cannot /// receive signals synchronization::SignalsReceiverControlBlock* signalsReceiverControlBlock_; /// newlib's _reent structure with thread-specific data _reent reent_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; /// round-robin quantum RoundRobinQuantum roundRobinQuantum_; /// scheduling policy of the thread SchedulingPolicy schedulingPolicy_; /// current state of object State state_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_ukf.hpp * \date October 2014 * \author Jan Issac (jan.issac@gmail.com) */ #ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_UKF_HPP #define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_UKF_HPP #include <map> #include <tuple> #include <memory> #include <fl/util/meta.hpp> #include <fl/util/traits.hpp> #include <fl/exception/exception.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/filter/gaussian/point_set.hpp> namespace fl { // Forward declarations template <typename...> class GaussianFilter; /** * GaussianFilter Traits */ template <typename ProcessModel, typename ObservationModel, typename PointSetTransform> struct Traits<GaussianFilter<ProcessModel, ObservationModel, PointSetTransform>> { typedef GaussianFilter< ProcessModel, ObservationModel, PointSetTransform > Filter; /* * Required concept (interface) types * * - Ptr * - State * - Input * - Observation * - StateDistribution */ typedef std::shared_ptr<Filter> Ptr; typedef typename Traits<ProcessModel>::State State; typedef typename Traits<ProcessModel>::Input Input; typedef typename Traits<ObservationModel>::Observation Observation; /** * Represents the underlying distribution of the estimated state. In * case of a Point Based Kalman filter, the distribution is a simple * Gaussian with the dimension of the \c State. */ typedef Gaussian<State> StateDistribution; /** \cond INTERNAL */ typedef typename Traits<ProcessModel>::Noise StateNoise; typedef typename Traits<ObservationModel>::Noise ObsrvNoise; enum { /** * Represents the total number of points required by the point set * transform. * * The number of points is a function of the joint Gaussian of which we * compute the transform. In this case the joint Gaussian consists of * the Gaussian of the state, the state noise Gaussian and the * observation noise Gaussian. The latter two are needed since we assume * models with non-additive noise. * * The resulting number of points determined by the employed transform * passed via \c PointSetTransform. If on or more of the marginal * Gaussian sizes is dynamic, the number of points is dynamic as well. * That is, the number of points cannot be known at compile time and * will be allocated dynamically on run time. */ NumberOfPoints = PointSetTransform::number_of_points( JoinSizes< State::RowsAtCompileTime, StateNoise::RowsAtCompileTime, ObsrvNoise::RowsAtCompileTime >::Size) }; typedef PointSet<State, NumberOfPoints> StatePointSet; typedef PointSet<Observation, NumberOfPoints> ObsrvPointSet; typedef PointSet<StateNoise, NumberOfPoints> StateNoisePointSet; typedef PointSet<ObsrvNoise, NumberOfPoints> ObsrvNoisePointSet; /** * \brief KalmanGain Matrix */ typedef Eigen::Matrix< typename StateDistribution::Scalar, State::RowsAtCompileTime, Observation::RowsAtCompileTime > KalmanGain; /** \endcond */ }; /** * GaussianFilter represents all filters based on Gaussian distributed systems. * This includes the Kalman Filter and filters using non-linear models such as * Sigma Point Kalman Filter family. * * \tparam ProcessModel * \tparam ObservationModel * * \ingroup filters * \ingroup sigma_point_kalman_filters */ template< typename ProcessModel, typename ObservationModel, typename PointSetTransform > class GaussianFilter<ProcessModel, ObservationModel, PointSetTransform> : /* Implement the conceptual filter interface */ public FilterInterface< GaussianFilter<ProcessModel, ObservationModel, PointSetTransform>> { protected: /** \cond INTERNAL */ typedef GaussianFilter<ProcessModel, ObservationModel, PointSetTransform> This; typedef typename Traits<This>::KalmanGain KalmanGain; typedef typename Traits<This>::StateNoise StateNoise; typedef typename Traits<This>::ObsrvNoise ObsrvNoise; typedef typename Traits<This>::StatePointSet StatePointSet; typedef typename Traits<This>::ObsrvPointSet ObsrvPointSet; typedef typename Traits<This>::StateNoisePointSet StateNoisePointSet; typedef typename Traits<This>::ObsrvNoisePointSet ObsrvNoisePointSet; /** \endcond */ public: /* public concept interface types */ typedef typename Traits<This>::State State; typedef typename Traits<This>::Input Input; typedef typename Traits<This>::Observation Obsrv; typedef typename Traits<This>::StateDistribution StateDistribution; public: /** * Creates a Gaussian filter * * \param process_model Process model instance * \param Obsrv_model Obsrv model instance * \param point_set_transform Point set tranfrom such as the unscented * transform */ GaussianFilter(const std::shared_ptr<ProcessModel>& process_model, const std::shared_ptr<ObservationModel>& Obsrv_model, const std::shared_ptr<PointSetTransform>& point_set_transform) : process_model_(process_model), obsrv_model_(Obsrv_model), point_set_transform_(point_set_transform), /* * Set the augmented Gaussian dimension. * * The global dimension is dimension of the augmented Gaussian which * consists of state Gaussian, state noise Gaussian and the * observation noise Gaussian. */ global_dimension_(process_model_->state_dimension() + process_model_->noise_dimension() + obsrv_model_->noise_dimension()), /* * Initialize the points-set Gaussian (e.g. sigma points) of the * \em state noise. The number of points is determined by the * augmented Gaussian with the dimension global_dimension_ */ X_Q(process_model_->noise_dimension(), PointSetTransform::number_of_points(global_dimension_)), /* * Initialize the points-set Gaussian (e.g. sigma points) of the * \em observation noise. The number of points is determined by the * augmented Gaussian with the dimension global_dimension_ */ X_R(obsrv_model_->noise_dimension(), PointSetTransform::number_of_points(global_dimension_)) { /* * pre-compute the state noise points from the standard Gaussian * distribution with the dimension of the state noise and store the * points in the X_Q PointSet * * The points are computet for the marginal Q of the global Gaussian * with the dimension global_dimension_ as depecited below * * [ P 0 0 ] * -> [ 0 Q 0 ] -> [X_Q[1] X_Q[2] ... X_Q[p]] * [ 0 0 R ] * * p is the number of points determined be the transform type * * The transform takes the global dimension (dim(P) + dim(Q) + dim(R)) * and the dimension offset dim(P) as parameters. */ point_set_transform_->forward( Gaussian<StateNoise>(process_model_->noise_dimension()), global_dimension_, process_model_->state_dimension(), X_Q); /* * pre-compute the observation noise points from the standard Gaussian * distribution with the dimension of the observation noise and store * the points in the X_R PointSet * * The points are computet for the marginal R of the global Gaussian * with the dimension global_dimension_ as depecited below * * [ P 0 0 ] * [ 0 Q 0 ] * -> [ 0 0 R ] -> [X_R[1] X_R[2] ... X_R[p]] * * again p is the number of points determined be the transform type * * The transform takes the global dimension (dim(P) + dim(Q) + dim(R)) * and the dimension offset dim(P) + dim(Q) as parameters. */ point_set_transform_->forward( Gaussian<ObsrvNoise>(obsrv_model_->noise_dimension()), global_dimension_, process_model_->state_dimension() + process_model_->noise_dimension(), X_R); /* * Setup the point set of the observation predictions */ const size_t point_count = PointSetTransform::number_of_points(global_dimension_); X_y.resize(point_count); X_y.dimension(obsrv_model_->obsrv_dimension()); } /** * \copydoc FilterInterface::predict */ virtual void predict(double delta_time, const Input& input, const StateDistribution& prior_dist, StateDistribution& predicted_dist) { /* * Compute the state points from the given prior state Gaussian * distribution and store the points in the X_r PointSet * * The points are computet for the marginal R of the global Gaussian * with the dimension global_dimension_ as depecited below * * -> [ P 0 0 ] -> [X_r[1] X_r[2] ... X_r[p]] * [ 0 Q 0 ] * [ 0 0 R ] * * The transform takes the global dimension (dim(P) + dim(Q) + dim(R)) * and the dimension offset 0 as parameters. */ point_set_transform_->forward(prior_dist, global_dimension_, 0, X_r); /* * Predict each point X_r[i] and store the prediction back in X_r[i] * * X_r[i] = f(X_r[i], X_Q[i], u) */ const size_t point_count = X_r.count_points(); for (size_t i = 0; i < point_count; ++i) { X_r.point(i, process_model_->predict_state(delta_time, X_r.point(i), X_Q.point(i), input)); } /* * Obtain the centered points matrix of the prediction. The columns of * this matrix are the predicted points with zero mean. That is, the * sum of the columns in P is zero. * * P = [X_r[1]-mu_r X_r[2]-mu_r ... X_r[n]-mu_r] * * with weighted mean * * mu_r = Sum w_mean[i] X_r[i] */ auto&& X = X_r.centered_points(); /* * Obtain the weights of point as a vector * * W = [w_cov[1] w_cov[2] ... w_cov[n]] * * Note that the covariance weights are used. */ auto&& W = X_r.covariance_weights_vector(); /* * Compute and set the moments * * The first moment is simply the weighted mean of points. * The second centered moment is determined by * * C = Sum W[i,i] * (X_r[i]-mu_r)(X_r[i]-mu_r)^T * = P * W * P^T * * given that W is the diagonal matrix */ predicted_dist.mean(X_r.mean()); predicted_dist.covariance(X * W.asDiagonal() * X.transpose()); } /** * \copydoc FilterInterface::update */ virtual void update(const Obsrv& y, const StateDistribution& predicted_dist, StateDistribution& posterior_dist) { point_set_transform_->forward(predicted_dist, global_dimension_, 0, X_r); const size_t point_count = X_r.count_points(); for (size_t i = 0; i < point_count; ++i) { X_y.point(i, obsrv_model_->predict_observation(X_r.point(i), X_R.point(i))); } auto W = X_r.covariance_weights_vector(); auto X = X_r.centered_points(); auto Y = X_y.centered_points(); auto cov_xx = X * W.asDiagonal() * X.transpose(); auto cov_yy = Y * W.asDiagonal() * Y.transpose(); auto cov_xy = X * W.asDiagonal() * Y.transpose(); const KalmanGain& K = cov_xy * cov_yy.inverse(); posterior_dist.mean(X_r.mean() + K * (y - X_y.mean())); posterior_dist.covariance(cov_xx - K * cov_yy * K.transpose()); } /** * \copydoc FilterInterface::predict_and_update */ virtual void predict_and_update(double delta_time, const Input& input, const Obsrv& observation, const StateDistribution& prior_dist, StateDistribution& posterior_dist) { predict(delta_time, input, prior_dist, posterior_dist); update(observation, posterior_dist, posterior_dist); } protected: std::shared_ptr<ProcessModel> process_model_; std::shared_ptr<ObservationModel> obsrv_model_; std::shared_ptr<PointSetTransform> point_set_transform_; /** \cond INTERNAL */ /** * \brief The global dimension is dimension of the augmented Gaussian which * consists of state Gaussian, state noise Gaussian and the * observation noise Gaussian. */ const size_t global_dimension_; /** * \brief Represents the point-set of the state */ StatePointSet X_r; /** * \brief Represents the point-set of the observation */ ObsrvPointSet X_y; /** * \brief Represents the points-set Gaussian (e.g. sigma points) of the * \em state noise. The number of points is determined by the augmented * Gaussian with the dimension #global_dimension_ */ StateNoisePointSet X_Q; /** * \brief Represents the points-set Gaussian (e.g. sigma points) of the * \em observation noise. The number of points is determined by the * augmented Gaussian with the dimension #global_dimension_ */ ObsrvNoisePointSet X_R; /** \endcond */ }; } #endif <commit_msg>fixed predict_observation call<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com) * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_ukf.hpp * \date October 2014 * \author Jan Issac (jan.issac@gmail.com) */ #ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_UKF_HPP #define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_UKF_HPP #include <map> #include <tuple> #include <memory> #include <fl/util/meta.hpp> #include <fl/util/traits.hpp> #include <fl/exception/exception.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/filter/gaussian/point_set.hpp> namespace fl { // Forward declarations template <typename...> class GaussianFilter; /** * GaussianFilter Traits */ template <typename ProcessModel, typename ObservationModel, typename PointSetTransform> struct Traits<GaussianFilter<ProcessModel, ObservationModel, PointSetTransform>> { typedef GaussianFilter< ProcessModel, ObservationModel, PointSetTransform > Filter; /* * Required concept (interface) types * * - Ptr * - State * - Input * - Observation * - StateDistribution */ typedef std::shared_ptr<Filter> Ptr; typedef typename Traits<ProcessModel>::State State; typedef typename Traits<ProcessModel>::Input Input; typedef typename Traits<ObservationModel>::Observation Observation; /** * Represents the underlying distribution of the estimated state. In * case of a Point Based Kalman filter, the distribution is a simple * Gaussian with the dimension of the \c State. */ typedef Gaussian<State> StateDistribution; /** \cond INTERNAL */ typedef typename Traits<ProcessModel>::Noise StateNoise; typedef typename Traits<ObservationModel>::Noise ObsrvNoise; enum { /** * Represents the total number of points required by the point set * transform. * * The number of points is a function of the joint Gaussian of which we * compute the transform. In this case the joint Gaussian consists of * the Gaussian of the state, the state noise Gaussian and the * observation noise Gaussian. The latter two are needed since we assume * models with non-additive noise. * * The resulting number of points determined by the employed transform * passed via \c PointSetTransform. If on or more of the marginal * Gaussian sizes is dynamic, the number of points is dynamic as well. * That is, the number of points cannot be known at compile time and * will be allocated dynamically on run time. */ NumberOfPoints = PointSetTransform::number_of_points( JoinSizes< State::RowsAtCompileTime, StateNoise::RowsAtCompileTime, ObsrvNoise::RowsAtCompileTime >::Size) }; typedef PointSet<State, NumberOfPoints> StatePointSet; typedef PointSet<Observation, NumberOfPoints> ObsrvPointSet; typedef PointSet<StateNoise, NumberOfPoints> StateNoisePointSet; typedef PointSet<ObsrvNoise, NumberOfPoints> ObsrvNoisePointSet; /** * \brief KalmanGain Matrix */ typedef Eigen::Matrix< typename StateDistribution::Scalar, State::RowsAtCompileTime, Observation::RowsAtCompileTime > KalmanGain; /** \endcond */ }; /** * GaussianFilter represents all filters based on Gaussian distributed systems. * This includes the Kalman Filter and filters using non-linear models such as * Sigma Point Kalman Filter family. * * \tparam ProcessModel * \tparam ObservationModel * * \ingroup filters * \ingroup sigma_point_kalman_filters */ template< typename ProcessModel, typename ObservationModel, typename PointSetTransform > class GaussianFilter<ProcessModel, ObservationModel, PointSetTransform> : /* Implement the conceptual filter interface */ public FilterInterface< GaussianFilter<ProcessModel, ObservationModel, PointSetTransform>> { protected: /** \cond INTERNAL */ typedef GaussianFilter<ProcessModel, ObservationModel, PointSetTransform> This; typedef typename Traits<This>::KalmanGain KalmanGain; typedef typename Traits<This>::StateNoise StateNoise; typedef typename Traits<This>::ObsrvNoise ObsrvNoise; typedef typename Traits<This>::StatePointSet StatePointSet; typedef typename Traits<This>::ObsrvPointSet ObsrvPointSet; typedef typename Traits<This>::StateNoisePointSet StateNoisePointSet; typedef typename Traits<This>::ObsrvNoisePointSet ObsrvNoisePointSet; /** \endcond */ public: /* public concept interface types */ typedef typename Traits<This>::State State; typedef typename Traits<This>::Input Input; typedef typename Traits<This>::Observation Obsrv; typedef typename Traits<This>::StateDistribution StateDistribution; public: /** * Creates a Gaussian filter * * \param process_model Process model instance * \param Obsrv_model Obsrv model instance * \param point_set_transform Point set tranfrom such as the unscented * transform */ GaussianFilter(const std::shared_ptr<ProcessModel>& process_model, const std::shared_ptr<ObservationModel>& Obsrv_model, const std::shared_ptr<PointSetTransform>& point_set_transform) : process_model_(process_model), obsrv_model_(Obsrv_model), point_set_transform_(point_set_transform), /* * Set the augmented Gaussian dimension. * * The global dimension is dimension of the augmented Gaussian which * consists of state Gaussian, state noise Gaussian and the * observation noise Gaussian. */ global_dimension_(process_model_->state_dimension() + process_model_->noise_dimension() + obsrv_model_->noise_dimension()), /* * Initialize the points-set Gaussian (e.g. sigma points) of the * \em state noise. The number of points is determined by the * augmented Gaussian with the dimension global_dimension_ */ X_Q(process_model_->noise_dimension(), PointSetTransform::number_of_points(global_dimension_)), /* * Initialize the points-set Gaussian (e.g. sigma points) of the * \em observation noise. The number of points is determined by the * augmented Gaussian with the dimension global_dimension_ */ X_R(obsrv_model_->noise_dimension(), PointSetTransform::number_of_points(global_dimension_)) { /* * pre-compute the state noise points from the standard Gaussian * distribution with the dimension of the state noise and store the * points in the X_Q PointSet * * The points are computet for the marginal Q of the global Gaussian * with the dimension global_dimension_ as depecited below * * [ P 0 0 ] * -> [ 0 Q 0 ] -> [X_Q[1] X_Q[2] ... X_Q[p]] * [ 0 0 R ] * * p is the number of points determined be the transform type * * The transform takes the global dimension (dim(P) + dim(Q) + dim(R)) * and the dimension offset dim(P) as parameters. */ point_set_transform_->forward( Gaussian<StateNoise>(process_model_->noise_dimension()), global_dimension_, process_model_->state_dimension(), X_Q); /* * pre-compute the observation noise points from the standard Gaussian * distribution with the dimension of the observation noise and store * the points in the X_R PointSet * * The points are computet for the marginal R of the global Gaussian * with the dimension global_dimension_ as depecited below * * [ P 0 0 ] * [ 0 Q 0 ] * -> [ 0 0 R ] -> [X_R[1] X_R[2] ... X_R[p]] * * again p is the number of points determined be the transform type * * The transform takes the global dimension (dim(P) + dim(Q) + dim(R)) * and the dimension offset dim(P) + dim(Q) as parameters. */ point_set_transform_->forward( Gaussian<ObsrvNoise>(obsrv_model_->noise_dimension()), global_dimension_, process_model_->state_dimension() + process_model_->noise_dimension(), X_R); /* * Setup the point set of the observation predictions */ const size_t point_count = PointSetTransform::number_of_points(global_dimension_); X_y.resize(point_count); X_y.dimension(obsrv_model_->obsrv_dimension()); } /** * \copydoc FilterInterface::predict */ virtual void predict(double delta_time, const Input& input, const StateDistribution& prior_dist, StateDistribution& predicted_dist) { /* * Compute the state points from the given prior state Gaussian * distribution and store the points in the X_r PointSet * * The points are computet for the marginal R of the global Gaussian * with the dimension global_dimension_ as depecited below * * -> [ P 0 0 ] -> [X_r[1] X_r[2] ... X_r[p]] * [ 0 Q 0 ] * [ 0 0 R ] * * The transform takes the global dimension (dim(P) + dim(Q) + dim(R)) * and the dimension offset 0 as parameters. */ point_set_transform_->forward(prior_dist, global_dimension_, 0, X_r); /* * Predict each point X_r[i] and store the prediction back in X_r[i] * * X_r[i] = f(X_r[i], X_Q[i], u) */ const size_t point_count = X_r.count_points(); for (size_t i = 0; i < point_count; ++i) { X_r.point(i, process_model_->predict_state(delta_time, X_r.point(i), X_Q.point(i), input)); } /* * Obtain the centered points matrix of the prediction. The columns of * this matrix are the predicted points with zero mean. That is, the * sum of the columns in P is zero. * * P = [X_r[1]-mu_r X_r[2]-mu_r ... X_r[n]-mu_r] * * with weighted mean * * mu_r = Sum w_mean[i] X_r[i] */ auto&& X = X_r.centered_points(); /* * Obtain the weights of point as a vector * * W = [w_cov[1] w_cov[2] ... w_cov[n]] * * Note that the covariance weights are used. */ auto&& W = X_r.covariance_weights_vector(); /* * Compute and set the moments * * The first moment is simply the weighted mean of points. * The second centered moment is determined by * * C = Sum W[i,i] * (X_r[i]-mu_r)(X_r[i]-mu_r)^T * = P * W * P^T * * given that W is the diagonal matrix */ predicted_dist.mean(X_r.mean()); predicted_dist.covariance(X * W.asDiagonal() * X.transpose()); } /** * \copydoc FilterInterface::update */ virtual void update(const Obsrv& y, const StateDistribution& predicted_dist, StateDistribution& posterior_dist) { point_set_transform_->forward(predicted_dist, global_dimension_, 0, X_r); const size_t point_count = X_r.count_points(); for (size_t i = 0; i < point_count; ++i) { X_y.point(i, obsrv_model_->predict_observation(X_r.point(i), X_R.point(i), 0 /* delta time */)); } auto W = X_r.covariance_weights_vector(); auto X = X_r.centered_points(); auto Y = X_y.centered_points(); auto cov_xx = X * W.asDiagonal() * X.transpose(); auto cov_yy = Y * W.asDiagonal() * Y.transpose(); auto cov_xy = X * W.asDiagonal() * Y.transpose(); const KalmanGain& K = cov_xy * cov_yy.inverse(); posterior_dist.mean(X_r.mean() + K * (y - X_y.mean())); posterior_dist.covariance(cov_xx - K * cov_yy * K.transpose()); } /** * \copydoc FilterInterface::predict_and_update */ virtual void predict_and_update(double delta_time, const Input& input, const Obsrv& observation, const StateDistribution& prior_dist, StateDistribution& posterior_dist) { predict(delta_time, input, prior_dist, posterior_dist); update(observation, posterior_dist, posterior_dist); } protected: std::shared_ptr<ProcessModel> process_model_; std::shared_ptr<ObservationModel> obsrv_model_; std::shared_ptr<PointSetTransform> point_set_transform_; /** \cond INTERNAL */ /** * \brief The global dimension is dimension of the augmented Gaussian which * consists of state Gaussian, state noise Gaussian and the * observation noise Gaussian. */ const size_t global_dimension_; /** * \brief Represents the point-set of the state */ StatePointSet X_r; /** * \brief Represents the point-set of the observation */ ObsrvPointSet X_y; /** * \brief Represents the points-set Gaussian (e.g. sigma points) of the * \em state noise. The number of points is determined by the augmented * Gaussian with the dimension #global_dimension_ */ StateNoisePointSet X_Q; /** * \brief Represents the points-set Gaussian (e.g. sigma points) of the * \em observation noise. The number of points is determined by the * augmented Gaussian with the dimension #global_dimension_ */ ObsrvNoisePointSet X_R; /** \endcond */ }; } #endif <|endoftext|>
<commit_before>/****************************************************************************** * plane_bind.cpp - bindings for Ogre::Plane ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * 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 "ogre_interface.h" #include <OgreRoot.h> #include <OgrePlane.h> <commit_msg>create/delete methods<commit_after>/****************************************************************************** * plane_bind.cpp - bindings for Ogre::Plane ****************************************************************************** * This file is part of * __ __ _ * / // /_____ ____ (_) * / // // ___// __ \ / / * / // // /__ / /_/ // / * /_//_/ \___/ \____//_/ * * Low Level C Ogre Interface (llcoi) * * See http://code.google.com/p/llcoi/ for more information. * * Copyright (c) 2011, Llcoi Team * * License: MIT * * 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 "ogre_interface.h" #include <OgreRoot.h> #include <OgrePlane.h> PlaneHandle create_plane() { Ogre::Plane* plane = new Ogre::Plane; return reinterpret_cast<PlaneHandle>(plane); } void destroy_plane(PlaneHandle handle) { Ogre::Plane* plane = reinterpret_cast<Ogre::Plane*>(handle); delete plane; } <|endoftext|>
<commit_before>// Copyright 2015 The Enquery 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. See the AUTHORS file for names of // contributors. #include <errno.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include "enquery/execution.h" #include "enquery/executive.h" #include "enquery/status.h" #include "enquery/testing.h" using ::enquery::Execution; using ::enquery::Executive; using ::enquery::Future; using ::enquery::Status; namespace enquery { // Execution implementation that always fails. The constructor accepts a // a pointer-to-bool, which is set to 'false' on construction, and set to // 'true' on destruction; this can be used by the test to determine the // correct behavior of Executive's optional mechanism for taking ownership // of the Execution instance that's passed during creation. class Task; class FailingExecution : public Execution { public: explicit FailingExecution(bool* set_when_destroyed) : set_when_destroyed_(set_when_destroyed) { *set_when_destroyed_ = false; } virtual ~FailingExecution() { *set_when_destroyed_ = true; } virtual Status Execute(Task*) { // NOLINT return Status::MakeError("test", "failed to execute"); } private: bool* set_when_destroyed_; }; } // namespace enquery // Sample function for unit test (simply negates integer that's passed.) int negate(int x) { return -x; } void test_default_use() { const int input_value = 42; // Create an Executive with default options; pass NULL to use execute // everything on the curren thread. The boolean parameter indicates // that Executive should own the 'Execution' object, however when // NULL is passed, the current thread executive is used, and the // Executive *always* owns that. Executive* executive = Executive::Create(NULL, true); // Create an empty future, to be populated later via Submit() Future<int> future_result; ASSERT_FALSE(future_result.Valid()); // Submit a task; in this case, we're making a call to the 'negate' // type, passing input_value as the argument; if successful, // 'future_result' is populated with a future that will eventually // hold the result of the calculation. Status status = executive->Submit(negate, input_value, &future_result); // We should succeed ASSERT_TRUE(status.IsSuccess()); // We should get the correct answer ASSERT_EQUALS(future_result.GetValue(), negate(input_value)); delete executive; } // Test failing execution while simultaneously testing that the executive // properly cleans up its "execution method" when so configured. void test_failing_use_with_ownership() { const int input_value = 42; // First, create an execution method that always fails. bool destroyed = false; Execution* exm = new enquery::FailingExecution(&destroyed); // Create an executive that's configured to take ownership of // the execution method that's passed in. Executive* executive = Executive::Create(exm, true); // Create an empty future to hold the result. Future<int> future_result; ASSERT_FALSE(future_result.Valid()); // Submit the task for execution, which should fail fail. Status status = executive->Submit(negate, input_value, &future_result); ASSERT_FALSE(status.IsSuccess()); ASSERT_FALSE(future_result.Valid()); // Delete the executive. delete executive; // Assert that Execution owned by Executive was actually destroyed. ASSERT_TRUE(destroyed); } // Test that the executive does not delete the "execution method" when // so configured. void test_not_taking_ownership() { bool destroyed = false; Execution* exm = new enquery::FailingExecution(&destroyed); Executive* executive = Executive::Create(exm, false); delete executive; ASSERT_FALSE(destroyed); delete exm; } int main(int argc, char* argv[]) { test_default_use(); test_failing_use_with_ownership(); test_not_taking_ownership(); return EXIT_SUCCESS; } <commit_msg>fix typo in comment<commit_after>// Copyright 2015 The Enquery 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. See the AUTHORS file for names of // contributors. #include <errno.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include "enquery/execution.h" #include "enquery/executive.h" #include "enquery/status.h" #include "enquery/testing.h" using ::enquery::Execution; using ::enquery::Executive; using ::enquery::Future; using ::enquery::Status; namespace enquery { // Execution implementation that always fails. The constructor accepts a // a pointer-to-bool, which is set to 'false' on construction, and set to // 'true' on destruction; this can be used by the test to determine the // correct behavior of Executive's optional mechanism for taking ownership // of the Execution instance that's passed during creation. class Task; class FailingExecution : public Execution { public: explicit FailingExecution(bool* set_when_destroyed) : set_when_destroyed_(set_when_destroyed) { *set_when_destroyed_ = false; } virtual ~FailingExecution() { *set_when_destroyed_ = true; } virtual Status Execute(Task*) { // NOLINT return Status::MakeError("test", "failed to execute"); } private: bool* set_when_destroyed_; }; } // namespace enquery // Sample function for unit test (simply negates integer that's passed.) int negate(int x) { return -x; } void test_default_use() { const int input_value = 42; // Create an Executive with default options; pass NULL to use execute // everything on the current thread. The boolean parameter indicates // that Executive should own the 'Execution' object, however when // NULL is passed, the current thread executive is used, and the // Executive *always* owns that. Executive* executive = Executive::Create(NULL, true); // Create an empty future, to be populated later via Submit() Future<int> future_result; ASSERT_FALSE(future_result.Valid()); // Submit a task; in this case, we're making a call to the 'negate' // type, passing input_value as the argument; if successful, // 'future_result' is populated with a future that will eventually // hold the result of the calculation. Status status = executive->Submit(negate, input_value, &future_result); // We should succeed ASSERT_TRUE(status.IsSuccess()); // We should get the correct answer ASSERT_EQUALS(future_result.GetValue(), negate(input_value)); delete executive; } // Test failing execution while simultaneously testing that the executive // properly cleans up its "execution method" when so configured. void test_failing_use_with_ownership() { const int input_value = 42; // First, create an execution method that always fails. bool destroyed = false; Execution* exm = new enquery::FailingExecution(&destroyed); // Create an executive that's configured to take ownership of // the execution method that's passed in. Executive* executive = Executive::Create(exm, true); // Create an empty future to hold the result. Future<int> future_result; ASSERT_FALSE(future_result.Valid()); // Submit the task for execution, which should fail fail. Status status = executive->Submit(negate, input_value, &future_result); ASSERT_FALSE(status.IsSuccess()); ASSERT_FALSE(future_result.Valid()); // Delete the executive. delete executive; // Assert that Execution owned by Executive was actually destroyed. ASSERT_TRUE(destroyed); } // Test that the executive does not delete the "execution method" when // so configured. void test_not_taking_ownership() { bool destroyed = false; Execution* exm = new enquery::FailingExecution(&destroyed); Executive* executive = Executive::Create(exm, false); delete executive; ASSERT_FALSE(destroyed); delete exm; } int main(int argc, char* argv[]) { test_default_use(); test_failing_use_with_ownership(); test_not_taking_ownership(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>just a test...<commit_after><|endoftext|>
<commit_before>// // Created by Bradley Austin Davis on 2016/03/19 // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #pragma once #include "common.hpp" namespace vkx { // Version information for Vulkan is stored in a single 32 bit integer // with individual bits representing the major, minor and patch versions. // The maximum possible major and minor version is 512 (look out nVidia) // while the maximum possible patch version is 2048 struct Version { Version() : major(0), minor(0), patch(0) { } Version(uint32_t version) : Version() { *this = version; } Version& operator =(uint32_t version) { memcpy(this, &version, sizeof(uint32_t)); return *this; } operator uint32_t() const { uint32_t result; memcpy(&result, this, sizeof(uint32_t)); } std::string toString() const { std::stringstream buffer; buffer << major << "." << minor << "." << patch; return buffer.str(); } const uint32_t patch : 12; const uint32_t minor : 10; const uint32_t major : 10; }; }<commit_msg>fix name clash with gcc macro<commit_after>// // Created by Bradley Austin Davis on 2016/03/19 // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #pragma once #include "common.hpp" namespace vkx { // Version information for Vulkan is stored in a single 32 bit integer // with individual bits representing the major, minor and patch versions. // The maximum possible major and minor version is 512 (look out nVidia) // while the maximum possible patch version is 2048 struct Version { Version() : vulkan_major(0), vulkan_minor(0), vulkan_patch(0) { } Version(uint32_t version) : Version() { *this = version; } Version& operator =(uint32_t version) { memcpy(this, &version, sizeof(uint32_t)); return *this; } operator uint32_t() const { uint32_t result; memcpy(&result, this, sizeof(uint32_t)); } std::string toString() const { std::stringstream buffer; buffer << vulkan_major << "." << vulkan_minor << "." << vulkan_patch; return buffer.str(); } const uint32_t vulkan_patch : 12; const uint32_t vulkan_minor : 10; const uint32_t vulkan_major : 10; }; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: chaptercollator.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2003-03-26 10:54:38 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <assert.h> // prevent internal compiler error with MSVC6SP3 #include <stl/utility> #include <chaptercollator.hxx> #include <com/sun/star/i18n/KCharacterType.hpp> #ifndef _COM_SUN_STAR_I18N_PARSERESULT_HPP_ #include <com/sun/star/i18n/ParseResult.hpp> #endif using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::i18n; using namespace ::rtl; ChapterCollator::ChapterCollator( const Reference < XMultiServiceFactory >& rxMSF ) : CollatorImpl(rxMSF) { if ( rxMSF.is()) { Reference < XInterface > xI = rxMSF->createInstance( OUString::createFromAscii("com.sun.star.i18n.CharacterClassification")); if ( xI.is() ) xI->queryInterface(::getCppuType((const Reference< XCharacterClassification>*)0)) >>= cclass; } } ChapterCollator::~ChapterCollator() { } sal_Int32 SAL_CALL ChapterCollator::compareString( const OUString& s1, const OUString& s2) throw(RuntimeException) { return compareSubstring(s1, 0, s1.getLength(), s2, 0, s2.getLength()); } #define DIGIT KCharacterType::DIGIT sal_Int32 SAL_CALL ChapterCollator::compareSubstring( const OUString& str1, sal_Int32 off1, sal_Int32 len1, const OUString& str2, sal_Int32 off2, sal_Int32 len2) throw(RuntimeException) { if( len1 <= 1 || len2 <= 1 || ! cclass.is() ) return CollatorImpl::compareSubstring( str1, off1, len1, str2, off2, len2 ); sal_Int32 i1, i2; for (i1 = len1; i1 && (cclass->getCharacterType(str1, off1+i1-1, nLocale) & DIGIT); i1--); for (i2 = len2; i2 && (cclass->getCharacterType(str2, off2+i2-1, nLocale) & DIGIT); i2--); sal_Int32 ans = CollatorImpl::compareSubstring(str1, off1, i1, str2, off2, i2); if( ans != 0 ) return ans; OUString &aAddAllowed = OUString::createFromAscii("?"); ParseResult res1, res2; // Bug #100323#, since parseAnyToken does not take length as parameter, we have to copy // it to a temp. string. OUString s1 = str1.copy(off1+i1, len1-i1), s2 = str2.copy(off2+i2, len2-i2); res1 = cclass->parseAnyToken( s1, 0, nLocale, DIGIT, aAddAllowed, DIGIT, aAddAllowed ); res2 = cclass->parseAnyToken( s2, 0, nLocale, DIGIT, aAddAllowed, DIGIT, aAddAllowed ); return res1.Value == res2.Value ? 0 : res1.Value > res2.Value ? 1 : -1; } const sal_Char *cChapCollator = "com.sun.star.i18n.ChapterCollator"; OUString SAL_CALL ChapterCollator::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii(cChapCollator); } sal_Bool SAL_CALL ChapterCollator::supportsService(const rtl::OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cChapCollator); } Sequence< OUString > SAL_CALL ChapterCollator::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cChapCollator); return aRet; } <commit_msg>INTEGRATION: CWS dbgmacros1 (1.3.46); FILE MERGED 2003/04/09 11:54:43 kso 1.3.46.1: #108413# - debug macro unification.<commit_after>/************************************************************************* * * $RCSfile: chaptercollator.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-15 17:07:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // prevent internal compiler error with MSVC6SP3 #include <stl/utility> #include <chaptercollator.hxx> #include <com/sun/star/i18n/KCharacterType.hpp> #ifndef _COM_SUN_STAR_I18N_PARSERESULT_HPP_ #include <com/sun/star/i18n/ParseResult.hpp> #endif using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::i18n; using namespace ::rtl; ChapterCollator::ChapterCollator( const Reference < XMultiServiceFactory >& rxMSF ) : CollatorImpl(rxMSF) { if ( rxMSF.is()) { Reference < XInterface > xI = rxMSF->createInstance( OUString::createFromAscii("com.sun.star.i18n.CharacterClassification")); if ( xI.is() ) xI->queryInterface(::getCppuType((const Reference< XCharacterClassification>*)0)) >>= cclass; } } ChapterCollator::~ChapterCollator() { } sal_Int32 SAL_CALL ChapterCollator::compareString( const OUString& s1, const OUString& s2) throw(RuntimeException) { return compareSubstring(s1, 0, s1.getLength(), s2, 0, s2.getLength()); } #define DIGIT KCharacterType::DIGIT sal_Int32 SAL_CALL ChapterCollator::compareSubstring( const OUString& str1, sal_Int32 off1, sal_Int32 len1, const OUString& str2, sal_Int32 off2, sal_Int32 len2) throw(RuntimeException) { if( len1 <= 1 || len2 <= 1 || ! cclass.is() ) return CollatorImpl::compareSubstring( str1, off1, len1, str2, off2, len2 ); sal_Int32 i1, i2; for (i1 = len1; i1 && (cclass->getCharacterType(str1, off1+i1-1, nLocale) & DIGIT); i1--); for (i2 = len2; i2 && (cclass->getCharacterType(str2, off2+i2-1, nLocale) & DIGIT); i2--); sal_Int32 ans = CollatorImpl::compareSubstring(str1, off1, i1, str2, off2, i2); if( ans != 0 ) return ans; OUString &aAddAllowed = OUString::createFromAscii("?"); ParseResult res1, res2; // Bug #100323#, since parseAnyToken does not take length as parameter, we have to copy // it to a temp. string. OUString s1 = str1.copy(off1+i1, len1-i1), s2 = str2.copy(off2+i2, len2-i2); res1 = cclass->parseAnyToken( s1, 0, nLocale, DIGIT, aAddAllowed, DIGIT, aAddAllowed ); res2 = cclass->parseAnyToken( s2, 0, nLocale, DIGIT, aAddAllowed, DIGIT, aAddAllowed ); return res1.Value == res2.Value ? 0 : res1.Value > res2.Value ? 1 : -1; } const sal_Char *cChapCollator = "com.sun.star.i18n.ChapterCollator"; OUString SAL_CALL ChapterCollator::getImplementationName() throw( RuntimeException ) { return OUString::createFromAscii(cChapCollator); } sal_Bool SAL_CALL ChapterCollator::supportsService(const rtl::OUString& rServiceName) throw( RuntimeException ) { return !rServiceName.compareToAscii(cChapCollator); } Sequence< OUString > SAL_CALL ChapterCollator::getSupportedServiceNames() throw( RuntimeException ) { Sequence< OUString > aRet(1); aRet[0] = OUString::createFromAscii(cChapCollator); return aRet; } <|endoftext|>
<commit_before>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * 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 General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Chat.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptMgr.h" #include "Transmogrification.h" #include "Tokenize.h" using namespace Acore::ChatCommands; class transmog_commandscript : public CommandScript { public: transmog_commandscript() : CommandScript("transmog_commandscript") { } ChatCommandTable GetCommands() const override { static ChatCommandTable addCollectionTable = { { "set", HandleAddTransmogItemSet, SEC_MODERATOR, Console::Yes }, { "", HandleAddTransmogItem, SEC_MODERATOR, Console::Yes }, }; static ChatCommandTable transmogTable = { { "add", addCollectionTable }, { "", HandleDisableTransMogVisual, SEC_PLAYER, Console::No }, { "sync", HandleSyncTransMogCommand, SEC_PLAYER, Console::No }, }; static ChatCommandTable commandTable = { { "transmog", transmogTable }, }; return commandTable; } static bool HandleSyncTransMogCommand(ChatHandler* handler, char const* /*args*/) { Player* player = handler->GetPlayer(); uint32 accountId = player->GetSession()->GetAccountId(); handler->SendSysMessage(LANG_CMD_TRANSMOG_BEGIN_SYNC); for (uint32 itemId : sTransmogrification->collectionCache[accountId]) { handler->PSendSysMessage("TRANSMOG_SYNC:%u", itemId); } handler->SendSysMessage(LANG_CMD_TRANSMOG_COMPLETE_SYNC); return true; } static bool HandleDisableTransMogVisual(ChatHandler* handler, bool hide) { Player* player = handler->GetPlayer(); if (hide) { player->UpdatePlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG, 0); handler->SendSysMessage(LANG_CMD_TRANSMOG_SHOW); } else { player->UpdatePlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG, 1); handler->SendSysMessage(LANG_CMD_TRANSMOG_HIDE); } player->UpdateObjectVisibility(); return true; } static bool HandleAddTransmogItem(ChatHandler* handler, Optional<PlayerIdentifier> player, ItemTemplate const* itemTemplate) { if (!sTransmogrification->GetUseCollectionSystem()) return true; if (!sObjectMgr->GetItemTemplate(itemTemplate->ItemId)) { handler->PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, itemTemplate->ItemId); handler->SetSentErrorMessage(true); return false; } if (!player) { player = PlayerIdentifier::FromTargetOrSelf(handler); } if (!player) { return false; } Player* target = player->GetConnectedPlayer(); bool isNotConsole = handler->GetSession(); bool suitableForTransmog; if (target) { suitableForTransmog = sTransmogrification->SuitableForTransmogrification(target, itemTemplate); } else { suitableForTransmog = sTransmogrification->SuitableForTransmogrification(player->GetGUID(), itemTemplate); } if (!sTransmogrification->GetTrackUnusableItems() && !suitableForTransmog) { handler->SendSysMessage(LANG_CMD_TRANSMOG_ADD_UNSUITABLE); handler->SetSentErrorMessage(true); return true; } if (itemTemplate->Class != ITEM_CLASS_ARMOR && itemTemplate->Class != ITEM_CLASS_WEAPON) { handler->SendSysMessage(LANG_CMD_TRANSMOG_ADD_FORBIDDEN); handler->SetSentErrorMessage(true); return true; } auto guid = player->GetGUID(); uint32 accountId = sCharacterCache->GetCharacterAccountIdByGuid(guid); uint32 itemId = itemTemplate->ItemId; std::stringstream tempStream; tempStream << std::hex << ItemQualityColors[itemTemplate->Quality]; std::string itemQuality = tempStream.str(); std::string itemName = itemTemplate->Name1; std::string playerName = player->GetName(); std::string nameLink = handler->playerLink(playerName); if (sTransmogrification->AddCollectedAppearance(accountId, itemId)) { // Notify target of new item in appearance collection if (target && !(target->GetPlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG).value) && !sTransmogrification->CanNeverTransmog(itemTemplate)) { ChatHandler(target->GetSession()).PSendSysMessage(R"(|c%s|Hitem:%u:0:0:0:0:0:0:0:0|h[%s]|h|r has been added to your appearance collection.)", itemQuality.c_str(), itemId, itemName.c_str()); } // Feedback of successful command execution to GM if (isNotConsole && target != handler->GetPlayer()) { handler->PSendSysMessage(R"(|c%s|Hitem:%u:0:0:0:0:0:0:0:0|h[%s]|h|r has been added to the appearance collection of Player %s.)", itemQuality.c_str(), itemId, itemName.c_str(), nameLink); } CharacterDatabase.Execute("INSERT INTO custom_unlocked_appearances (account_id, item_template_id) VALUES ({}, {})", accountId, itemId); } else { // Feedback of failed command execution to GM if (isNotConsole) { handler->PSendSysMessage(R"(Player %s already has item |c%s|Hitem:%u:0:0:0:0:0:0:0:0|h[%s]|h|r in the appearance collection.)", nameLink, itemQuality.c_str(), itemId, itemName.c_str()); handler->SetSentErrorMessage(true); } } return true; } static bool HandleAddTransmogItemSet(ChatHandler* handler, Optional<PlayerIdentifier> player, Variant<Hyperlink<itemset>, uint32> itemSetId) { if (!sTransmogrification->GetUseCollectionSystem()) return true; if (!*itemSetId) { handler->PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, uint32(itemSetId)); handler->SetSentErrorMessage(true); return false; } if (!player) { player = PlayerIdentifier::FromTargetOrSelf(handler); } if (!player) { return false; } Player* target = player->GetConnectedPlayer(); ItemSetEntry const* set = sItemSetStore.LookupEntry(uint32(itemSetId)); bool isNotConsole = handler->GetSession(); if (!set) { handler->PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, uint32(itemSetId)); handler->SetSentErrorMessage(true); return false; } auto guid = player->GetGUID(); CharacterCacheEntry const* playerData = sCharacterCache->GetCharacterCacheByGuid(guid); if (!playerData) return false; bool added = false; uint32 error = 0; uint32 itemId; uint32 accountId = playerData->AccountId; for (uint32 i = 0; i < MAX_ITEM_SET_ITEMS; ++i) { itemId = set->itemId[i]; if (itemId) { ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId); if (itemTemplate) { if (!sTransmogrification->GetTrackUnusableItems() && ( (target && !sTransmogrification->SuitableForTransmogrification(target, itemTemplate)) || !sTransmogrification->SuitableForTransmogrification(guid, itemTemplate) )) { error = LANG_CMD_TRANSMOG_ADD_UNSUITABLE; continue; } if (itemTemplate->Class != ITEM_CLASS_ARMOR && itemTemplate->Class != ITEM_CLASS_WEAPON) { error = LANG_CMD_TRANSMOG_ADD_FORBIDDEN; continue; } if (sTransmogrification->AddCollectedAppearance(accountId, itemId)) { CharacterDatabase.Execute("INSERT INTO custom_unlocked_appearances (account_id, item_template_id) VALUES ({}, {})", accountId, itemId); added = true; } } } } if (!added && error > 0) { handler->SendSysMessage(error); handler->SetSentErrorMessage(true); return true; } int locale = handler->GetSessionDbcLocale(); std::string setName = set->name[locale]; std::string nameLink = handler->playerLink(player->GetName()); // Feedback of command execution to GM if (isNotConsole) { // Failed command execution if (!added) { handler->PSendSysMessage("Player %s already has ItemSet |cffffffff|Hitemset:%d|h[%s %s]|h|r in the appearance collection.", nameLink, uint32(itemSetId), setName.c_str(), localeNames[locale]); handler->SetSentErrorMessage(true); return true; } // Successful command execution if (target != handler->GetPlayer()) { handler->PSendSysMessage("ItemSet |cffffffff|Hitemset:%d|h[%s %s]|h|r has been added to the appearance collection of Player %s.", uint32(itemSetId), setName.c_str(), localeNames[locale], nameLink); } } // Notify target of new item in appearance collection if (target && !(target->GetPlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG).value)) { ChatHandler(target->GetSession()).PSendSysMessage("ItemSet |cffffffff|Hitemset:%d|h[%s %s]|h|r has been added to your appearance collection.", uint32(itemSetId), setName.c_str(), localeNames[locale]); } return true; } }; void AddSC_transmog_commandscript() { new transmog_commandscript(); } <commit_msg>fix: Fix sync command params to avoid deprecated build warning (#99)<commit_after>/* * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information * * 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 General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Chat.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptMgr.h" #include "Transmogrification.h" #include "Tokenize.h" using namespace Acore::ChatCommands; class transmog_commandscript : public CommandScript { public: transmog_commandscript() : CommandScript("transmog_commandscript") { } ChatCommandTable GetCommands() const override { static ChatCommandTable addCollectionTable = { { "set", HandleAddTransmogItemSet, SEC_MODERATOR, Console::Yes }, { "", HandleAddTransmogItem, SEC_MODERATOR, Console::Yes }, }; static ChatCommandTable transmogTable = { { "add", addCollectionTable }, { "", HandleDisableTransMogVisual, SEC_PLAYER, Console::No }, { "sync", HandleSyncTransMogCommand, SEC_PLAYER, Console::No }, }; static ChatCommandTable commandTable = { { "transmog", transmogTable }, }; return commandTable; } static bool HandleSyncTransMogCommand(ChatHandler* handler) { Player* player = handler->GetPlayer(); uint32 accountId = player->GetSession()->GetAccountId(); handler->SendSysMessage(LANG_CMD_TRANSMOG_BEGIN_SYNC); for (uint32 itemId : sTransmogrification->collectionCache[accountId]) { handler->PSendSysMessage("TRANSMOG_SYNC:%u", itemId); } handler->SendSysMessage(LANG_CMD_TRANSMOG_COMPLETE_SYNC); return true; } static bool HandleDisableTransMogVisual(ChatHandler* handler, bool hide) { Player* player = handler->GetPlayer(); if (hide) { player->UpdatePlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG, 0); handler->SendSysMessage(LANG_CMD_TRANSMOG_SHOW); } else { player->UpdatePlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG, 1); handler->SendSysMessage(LANG_CMD_TRANSMOG_HIDE); } player->UpdateObjectVisibility(); return true; } static bool HandleAddTransmogItem(ChatHandler* handler, Optional<PlayerIdentifier> player, ItemTemplate const* itemTemplate) { if (!sTransmogrification->GetUseCollectionSystem()) return true; if (!sObjectMgr->GetItemTemplate(itemTemplate->ItemId)) { handler->PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, itemTemplate->ItemId); handler->SetSentErrorMessage(true); return false; } if (!player) { player = PlayerIdentifier::FromTargetOrSelf(handler); } if (!player) { return false; } Player* target = player->GetConnectedPlayer(); bool isNotConsole = handler->GetSession(); bool suitableForTransmog; if (target) { suitableForTransmog = sTransmogrification->SuitableForTransmogrification(target, itemTemplate); } else { suitableForTransmog = sTransmogrification->SuitableForTransmogrification(player->GetGUID(), itemTemplate); } if (!sTransmogrification->GetTrackUnusableItems() && !suitableForTransmog) { handler->SendSysMessage(LANG_CMD_TRANSMOG_ADD_UNSUITABLE); handler->SetSentErrorMessage(true); return true; } if (itemTemplate->Class != ITEM_CLASS_ARMOR && itemTemplate->Class != ITEM_CLASS_WEAPON) { handler->SendSysMessage(LANG_CMD_TRANSMOG_ADD_FORBIDDEN); handler->SetSentErrorMessage(true); return true; } auto guid = player->GetGUID(); uint32 accountId = sCharacterCache->GetCharacterAccountIdByGuid(guid); uint32 itemId = itemTemplate->ItemId; std::stringstream tempStream; tempStream << std::hex << ItemQualityColors[itemTemplate->Quality]; std::string itemQuality = tempStream.str(); std::string itemName = itemTemplate->Name1; std::string playerName = player->GetName(); std::string nameLink = handler->playerLink(playerName); if (sTransmogrification->AddCollectedAppearance(accountId, itemId)) { // Notify target of new item in appearance collection if (target && !(target->GetPlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG).value) && !sTransmogrification->CanNeverTransmog(itemTemplate)) { ChatHandler(target->GetSession()).PSendSysMessage(R"(|c%s|Hitem:%u:0:0:0:0:0:0:0:0|h[%s]|h|r has been added to your appearance collection.)", itemQuality.c_str(), itemId, itemName.c_str()); } // Feedback of successful command execution to GM if (isNotConsole && target != handler->GetPlayer()) { handler->PSendSysMessage(R"(|c%s|Hitem:%u:0:0:0:0:0:0:0:0|h[%s]|h|r has been added to the appearance collection of Player %s.)", itemQuality.c_str(), itemId, itemName.c_str(), nameLink); } CharacterDatabase.Execute("INSERT INTO custom_unlocked_appearances (account_id, item_template_id) VALUES ({}, {})", accountId, itemId); } else { // Feedback of failed command execution to GM if (isNotConsole) { handler->PSendSysMessage(R"(Player %s already has item |c%s|Hitem:%u:0:0:0:0:0:0:0:0|h[%s]|h|r in the appearance collection.)", nameLink, itemQuality.c_str(), itemId, itemName.c_str()); handler->SetSentErrorMessage(true); } } return true; } static bool HandleAddTransmogItemSet(ChatHandler* handler, Optional<PlayerIdentifier> player, Variant<Hyperlink<itemset>, uint32> itemSetId) { if (!sTransmogrification->GetUseCollectionSystem()) return true; if (!*itemSetId) { handler->PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, uint32(itemSetId)); handler->SetSentErrorMessage(true); return false; } if (!player) { player = PlayerIdentifier::FromTargetOrSelf(handler); } if (!player) { return false; } Player* target = player->GetConnectedPlayer(); ItemSetEntry const* set = sItemSetStore.LookupEntry(uint32(itemSetId)); bool isNotConsole = handler->GetSession(); if (!set) { handler->PSendSysMessage(LANG_NO_ITEMS_FROM_ITEMSET_FOUND, uint32(itemSetId)); handler->SetSentErrorMessage(true); return false; } auto guid = player->GetGUID(); CharacterCacheEntry const* playerData = sCharacterCache->GetCharacterCacheByGuid(guid); if (!playerData) return false; bool added = false; uint32 error = 0; uint32 itemId; uint32 accountId = playerData->AccountId; for (uint32 i = 0; i < MAX_ITEM_SET_ITEMS; ++i) { itemId = set->itemId[i]; if (itemId) { ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(itemId); if (itemTemplate) { if (!sTransmogrification->GetTrackUnusableItems() && ( (target && !sTransmogrification->SuitableForTransmogrification(target, itemTemplate)) || !sTransmogrification->SuitableForTransmogrification(guid, itemTemplate) )) { error = LANG_CMD_TRANSMOG_ADD_UNSUITABLE; continue; } if (itemTemplate->Class != ITEM_CLASS_ARMOR && itemTemplate->Class != ITEM_CLASS_WEAPON) { error = LANG_CMD_TRANSMOG_ADD_FORBIDDEN; continue; } if (sTransmogrification->AddCollectedAppearance(accountId, itemId)) { CharacterDatabase.Execute("INSERT INTO custom_unlocked_appearances (account_id, item_template_id) VALUES ({}, {})", accountId, itemId); added = true; } } } } if (!added && error > 0) { handler->SendSysMessage(error); handler->SetSentErrorMessage(true); return true; } int locale = handler->GetSessionDbcLocale(); std::string setName = set->name[locale]; std::string nameLink = handler->playerLink(player->GetName()); // Feedback of command execution to GM if (isNotConsole) { // Failed command execution if (!added) { handler->PSendSysMessage("Player %s already has ItemSet |cffffffff|Hitemset:%d|h[%s %s]|h|r in the appearance collection.", nameLink, uint32(itemSetId), setName.c_str(), localeNames[locale]); handler->SetSentErrorMessage(true); return true; } // Successful command execution if (target != handler->GetPlayer()) { handler->PSendSysMessage("ItemSet |cffffffff|Hitemset:%d|h[%s %s]|h|r has been added to the appearance collection of Player %s.", uint32(itemSetId), setName.c_str(), localeNames[locale], nameLink); } } // Notify target of new item in appearance collection if (target && !(target->GetPlayerSetting("mod-transmog", SETTING_HIDE_TRANSMOG).value)) { ChatHandler(target->GetSession()).PSendSysMessage("ItemSet |cffffffff|Hitemset:%d|h[%s %s]|h|r has been added to your appearance collection.", uint32(itemSetId), setName.c_str(), localeNames[locale]); } return true; } }; void AddSC_transmog_commandscript() { new transmog_commandscript(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // MSVC++ requires this to be set before any other includes to get M_PI. #define _USE_MATH_DEFINES #include "ui/gfx/transform.h" #include <cmath> #include "ui/gfx/point.h" #include "ui/gfx/point3_f.h" #include "ui/gfx/vector3d_f.h" #include "ui/gfx/rect.h" #include "ui/gfx/safe_integer_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/transform_util.h" namespace gfx { namespace { // Taken from SkMatrix44. const double kTooSmallForDeterminant = 1e-8; double TanDegrees(double degrees) { double radians = degrees * M_PI / 180; return std::tan(radians); } } // namespace Transform::Transform() { matrix_.reset(); } Transform::~Transform() {} bool Transform::operator==(const Transform& rhs) const { return matrix_ == rhs.matrix_; } bool Transform::operator!=(const Transform& rhs) const { return !(*this == rhs); } void Transform::MakeIdentity() { matrix_.setIdentity(); } void Transform::RotateAboutXAxis(double degrees) { double radians = degrees * M_PI / 180; double cosTheta = std::cos(radians); double sinTheta = std::sin(radians); if (matrix_.isIdentity()) { matrix_.set3x3(1, 0, 0, 0, cosTheta, sinTheta, 0, -sinTheta, cosTheta); } else { SkMatrix44 rot; rot.set3x3(1, 0, 0, 0, cosTheta, sinTheta, 0, -sinTheta, cosTheta); matrix_.preConcat(rot); } } void Transform::RotateAboutYAxis(double degrees) { double radians = degrees * M_PI / 180; double cosTheta = std::cos(radians); double sinTheta = std::sin(radians); if (matrix_.isIdentity()) { // Note carefully the placement of the -sinTheta for rotation about // y-axis is different than rotation about x-axis or z-axis. matrix_.set3x3(cosTheta, 0, -sinTheta, 0, 1, 0, sinTheta, 0, cosTheta); } else { SkMatrix44 rot; rot.set3x3(cosTheta, 0, -sinTheta, 0, 1, 0, sinTheta, 0, cosTheta); matrix_.preConcat(rot); } } void Transform::RotateAboutZAxis(double degrees) { double radians = degrees * M_PI / 180; double cosTheta = std::cos(radians); double sinTheta = std::sin(radians); if (matrix_.isIdentity()) { matrix_.set3x3(cosTheta, sinTheta, 0, -sinTheta, cosTheta, 0, 0, 0, 1); } else { SkMatrix44 rot; rot.set3x3(cosTheta, sinTheta, 0, -sinTheta, cosTheta, 0, 0, 0, 1); matrix_.preConcat(rot); } } void Transform::RotateAbout(const Vector3dF& axis, double degrees) { if (matrix_.isIdentity()) { matrix_.setRotateDegreesAbout(SkDoubleToMScalar(axis.x()), SkDoubleToMScalar(axis.y()), SkDoubleToMScalar(axis.z()), SkDoubleToMScalar(degrees)); } else { SkMatrix44 rot; rot.setRotateDegreesAbout(SkDoubleToMScalar(axis.x()), SkDoubleToMScalar(axis.y()), SkDoubleToMScalar(axis.z()), SkDoubleToMScalar(degrees)); matrix_.preConcat(rot); } } void Transform::Scale(double x, double y) { if (matrix_.isIdentity()) { matrix_.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(1)); } else { SkMatrix44 scale; scale.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(1)); matrix_.preConcat(scale); } } void Transform::Scale3d(double x, double y, double z) { if (matrix_.isIdentity()) { matrix_.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); } else { SkMatrix44 scale; scale.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); matrix_.preConcat(scale); } } void Transform::Translate(double x, double y) { if (matrix_.isIdentity()) { matrix_.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(0)); } else { SkMatrix44 translate; translate.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(0)); matrix_.preConcat(translate); } } void Transform::Translate3d(double x, double y, double z) { if (matrix_.isIdentity()) { matrix_.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); } else { SkMatrix44 translate; translate.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); matrix_.preConcat(translate); } } void Transform::SkewX(double angle_x) { if (matrix_.isIdentity()) matrix_.setDouble(0, 1, TanDegrees(angle_x)); else { SkMatrix44 skew; skew.setDouble(0, 1, TanDegrees(angle_x)); matrix_.preConcat(skew); } } void Transform::SkewY(double angle_y) { if (matrix_.isIdentity()) matrix_.setDouble(1, 0, TanDegrees(angle_y)); else { SkMatrix44 skew; skew.setDouble(1, 0, TanDegrees(angle_y)); matrix_.preConcat(skew); } } void Transform::ApplyPerspectiveDepth(double depth) { if (depth == 0) return; if (matrix_.isIdentity()) matrix_.setDouble(3, 2, -1.0 / depth); else { SkMatrix44 m; m.setDouble(3, 2, -1.0 / depth); matrix_.preConcat(m); } } void Transform::PreconcatTransform(const Transform& transform) { if (!transform.matrix_.isIdentity()) { matrix_.preConcat(transform.matrix_); } } void Transform::ConcatTransform(const Transform& transform) { if (!transform.matrix_.isIdentity()) { matrix_.postConcat(transform.matrix_); } } bool Transform::IsIdentity() const { return matrix_.isIdentity(); } bool Transform::IsIdentityOrTranslation() const { bool has_no_perspective = !matrix_.getDouble(3, 0) && !matrix_.getDouble(3, 1) && !matrix_.getDouble(3, 2) && (matrix_.getDouble(3, 3) == 1); bool has_no_rotation_or_skew = !matrix_.getDouble(0, 1) && !matrix_.getDouble(0, 2) && !matrix_.getDouble(1, 0) && !matrix_.getDouble(1, 2) && !matrix_.getDouble(2, 0) && !matrix_.getDouble(2, 1); bool has_no_scale = matrix_.getDouble(0, 0) == 1 && matrix_.getDouble(1, 1) == 1 && matrix_.getDouble(2, 2) == 1; return has_no_perspective && has_no_rotation_or_skew && has_no_scale; } bool Transform::IsScaleOrTranslation() const { bool has_no_perspective = !matrix_.getDouble(3, 0) && !matrix_.getDouble(3, 1) && !matrix_.getDouble(3, 2) && (matrix_.getDouble(3, 3) == 1); bool has_no_rotation_or_skew = !matrix_.getDouble(0, 1) && !matrix_.getDouble(0, 2) && !matrix_.getDouble(1, 0) && !matrix_.getDouble(1, 2) && !matrix_.getDouble(2, 0) && !matrix_.getDouble(2, 1); return has_no_perspective && has_no_rotation_or_skew; } bool Transform::HasPerspective() const { return matrix_.getDouble(3, 0) || matrix_.getDouble(3, 1) || matrix_.getDouble(3, 2) || (matrix_.getDouble(3, 3) != 1); } bool Transform::IsInvertible() const { return std::abs(matrix_.determinant()) > kTooSmallForDeterminant; } bool Transform::IsBackFaceVisible() const { // Compute whether a layer with a forward-facing normal of (0, 0, 1) would // have its back face visible after applying the transform. // // This is done by transforming the normal and seeing if the resulting z // value is positive or negative. However, note that transforming a normal // actually requires using the inverse-transpose of the original transform. // TODO (shawnsingh) make this perform more efficiently - we do not // actually need to instantiate/invert/transpose any matrices, exploiting the // fact that we only need to transform (0, 0, 1, 0). SkMatrix44 inverse; bool invertible = matrix_.invert(&inverse); // Assume the transform does not apply if it's not invertible, so it's // front face remains visible. if (!invertible) return false; return inverse.getDouble(2, 2) < 0; } bool Transform::GetInverse(Transform* transform) const { return matrix_.invert(&transform->matrix_); } void Transform::Transpose() { matrix_.transpose(); } void Transform::TransformPoint(Point& point) const { TransformPointInternal(matrix_, point); } void Transform::TransformPoint(Point3F& point) const { TransformPointInternal(matrix_, point); } bool Transform::TransformPointReverse(Point& point) const { // TODO(sad): Try to avoid trying to invert the matrix. SkMatrix44 inverse; if (!matrix_.invert(&inverse)) return false; TransformPointInternal(inverse, point); return true; } bool Transform::TransformPointReverse(Point3F& point) const { // TODO(sad): Try to avoid trying to invert the matrix. SkMatrix44 inverse; if (!matrix_.invert(&inverse)) return false; TransformPointInternal(inverse, point); return true; } void Transform::TransformRect(RectF* rect) const { SkRect src = RectFToSkRect(*rect); const SkMatrix& matrix = matrix_; matrix.mapRect(&src); *rect = SkRectToRectF(src); } bool Transform::TransformRectReverse(RectF* rect) const { SkMatrix44 inverse; if (!matrix_.invert(&inverse)) return false; const SkMatrix& matrix = inverse; SkRect src = RectFToSkRect(*rect); matrix.mapRect(&src); *rect = SkRectToRectF(src); return true; } bool Transform::Blend(const Transform& from, double progress) { if (progress <= 0.0) { *this = from; return true; } if (progress >= 1.0) return true; DecomposedTransform to_decomp; DecomposedTransform from_decomp; if (!DecomposeTransform(&to_decomp, *this) || !DecomposeTransform(&from_decomp, from)) return false; if (!BlendDecomposedTransforms(&to_decomp, to_decomp, from_decomp, progress)) return false; matrix_ = ComposeTransform(to_decomp).matrix(); return true; } Transform Transform::operator*(const Transform& other) const { Transform to_return; to_return.matrix_.setConcat(matrix_, other.matrix_); return to_return; } Transform& Transform::operator*=(const Transform& other) { matrix_.preConcat(other.matrix_); return *this; } void Transform::TransformPointInternal(const SkMatrix44& xform, Point3F& point) const { SkMScalar p[4] = { SkDoubleToMScalar(point.x()), SkDoubleToMScalar(point.y()), SkDoubleToMScalar(point.z()), SkDoubleToMScalar(1) }; xform.mapMScalars(p); if (p[3] != 1 && abs(p[3]) > 0) { point.SetPoint(p[0] / p[3], p[1] / p[3], p[2]/ p[3]); } else { point.SetPoint(p[0], p[1], p[2]); } } void Transform::TransformPointInternal(const SkMatrix44& xform, Point& point) const { SkMScalar p[4] = { SkDoubleToMScalar(point.x()), SkDoubleToMScalar(point.y()), SkDoubleToMScalar(0), SkDoubleToMScalar(1) }; xform.mapMScalars(p); point.SetPoint(ToRoundedInt(p[0]), ToRoundedInt(p[1])); } } // namespace gfx <commit_msg>Avoid redundant SkMatrix44::reset() call in gfx::Transform constructor<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // MSVC++ requires this to be set before any other includes to get M_PI. #define _USE_MATH_DEFINES #include "ui/gfx/transform.h" #include <cmath> #include "ui/gfx/point.h" #include "ui/gfx/point3_f.h" #include "ui/gfx/vector3d_f.h" #include "ui/gfx/rect.h" #include "ui/gfx/safe_integer_conversions.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/transform_util.h" namespace gfx { namespace { // Taken from SkMatrix44. const double kTooSmallForDeterminant = 1e-8; double TanDegrees(double degrees) { double radians = degrees * M_PI / 180; return std::tan(radians); } } // namespace Transform::Transform() { } Transform::~Transform() {} bool Transform::operator==(const Transform& rhs) const { return matrix_ == rhs.matrix_; } bool Transform::operator!=(const Transform& rhs) const { return !(*this == rhs); } void Transform::MakeIdentity() { matrix_.setIdentity(); } void Transform::RotateAboutXAxis(double degrees) { double radians = degrees * M_PI / 180; double cosTheta = std::cos(radians); double sinTheta = std::sin(radians); if (matrix_.isIdentity()) { matrix_.set3x3(1, 0, 0, 0, cosTheta, sinTheta, 0, -sinTheta, cosTheta); } else { SkMatrix44 rot; rot.set3x3(1, 0, 0, 0, cosTheta, sinTheta, 0, -sinTheta, cosTheta); matrix_.preConcat(rot); } } void Transform::RotateAboutYAxis(double degrees) { double radians = degrees * M_PI / 180; double cosTheta = std::cos(radians); double sinTheta = std::sin(radians); if (matrix_.isIdentity()) { // Note carefully the placement of the -sinTheta for rotation about // y-axis is different than rotation about x-axis or z-axis. matrix_.set3x3(cosTheta, 0, -sinTheta, 0, 1, 0, sinTheta, 0, cosTheta); } else { SkMatrix44 rot; rot.set3x3(cosTheta, 0, -sinTheta, 0, 1, 0, sinTheta, 0, cosTheta); matrix_.preConcat(rot); } } void Transform::RotateAboutZAxis(double degrees) { double radians = degrees * M_PI / 180; double cosTheta = std::cos(radians); double sinTheta = std::sin(radians); if (matrix_.isIdentity()) { matrix_.set3x3(cosTheta, sinTheta, 0, -sinTheta, cosTheta, 0, 0, 0, 1); } else { SkMatrix44 rot; rot.set3x3(cosTheta, sinTheta, 0, -sinTheta, cosTheta, 0, 0, 0, 1); matrix_.preConcat(rot); } } void Transform::RotateAbout(const Vector3dF& axis, double degrees) { if (matrix_.isIdentity()) { matrix_.setRotateDegreesAbout(SkDoubleToMScalar(axis.x()), SkDoubleToMScalar(axis.y()), SkDoubleToMScalar(axis.z()), SkDoubleToMScalar(degrees)); } else { SkMatrix44 rot; rot.setRotateDegreesAbout(SkDoubleToMScalar(axis.x()), SkDoubleToMScalar(axis.y()), SkDoubleToMScalar(axis.z()), SkDoubleToMScalar(degrees)); matrix_.preConcat(rot); } } void Transform::Scale(double x, double y) { if (matrix_.isIdentity()) { matrix_.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(1)); } else { SkMatrix44 scale; scale.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(1)); matrix_.preConcat(scale); } } void Transform::Scale3d(double x, double y, double z) { if (matrix_.isIdentity()) { matrix_.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); } else { SkMatrix44 scale; scale.setScale(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); matrix_.preConcat(scale); } } void Transform::Translate(double x, double y) { if (matrix_.isIdentity()) { matrix_.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(0)); } else { SkMatrix44 translate; translate.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(0)); matrix_.preConcat(translate); } } void Transform::Translate3d(double x, double y, double z) { if (matrix_.isIdentity()) { matrix_.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); } else { SkMatrix44 translate; translate.setTranslate(SkDoubleToMScalar(x), SkDoubleToMScalar(y), SkDoubleToMScalar(z)); matrix_.preConcat(translate); } } void Transform::SkewX(double angle_x) { if (matrix_.isIdentity()) matrix_.setDouble(0, 1, TanDegrees(angle_x)); else { SkMatrix44 skew; skew.setDouble(0, 1, TanDegrees(angle_x)); matrix_.preConcat(skew); } } void Transform::SkewY(double angle_y) { if (matrix_.isIdentity()) matrix_.setDouble(1, 0, TanDegrees(angle_y)); else { SkMatrix44 skew; skew.setDouble(1, 0, TanDegrees(angle_y)); matrix_.preConcat(skew); } } void Transform::ApplyPerspectiveDepth(double depth) { if (depth == 0) return; if (matrix_.isIdentity()) matrix_.setDouble(3, 2, -1.0 / depth); else { SkMatrix44 m; m.setDouble(3, 2, -1.0 / depth); matrix_.preConcat(m); } } void Transform::PreconcatTransform(const Transform& transform) { if (!transform.matrix_.isIdentity()) { matrix_.preConcat(transform.matrix_); } } void Transform::ConcatTransform(const Transform& transform) { if (!transform.matrix_.isIdentity()) { matrix_.postConcat(transform.matrix_); } } bool Transform::IsIdentity() const { return matrix_.isIdentity(); } bool Transform::IsIdentityOrTranslation() const { bool has_no_perspective = !matrix_.getDouble(3, 0) && !matrix_.getDouble(3, 1) && !matrix_.getDouble(3, 2) && (matrix_.getDouble(3, 3) == 1); bool has_no_rotation_or_skew = !matrix_.getDouble(0, 1) && !matrix_.getDouble(0, 2) && !matrix_.getDouble(1, 0) && !matrix_.getDouble(1, 2) && !matrix_.getDouble(2, 0) && !matrix_.getDouble(2, 1); bool has_no_scale = matrix_.getDouble(0, 0) == 1 && matrix_.getDouble(1, 1) == 1 && matrix_.getDouble(2, 2) == 1; return has_no_perspective && has_no_rotation_or_skew && has_no_scale; } bool Transform::IsScaleOrTranslation() const { bool has_no_perspective = !matrix_.getDouble(3, 0) && !matrix_.getDouble(3, 1) && !matrix_.getDouble(3, 2) && (matrix_.getDouble(3, 3) == 1); bool has_no_rotation_or_skew = !matrix_.getDouble(0, 1) && !matrix_.getDouble(0, 2) && !matrix_.getDouble(1, 0) && !matrix_.getDouble(1, 2) && !matrix_.getDouble(2, 0) && !matrix_.getDouble(2, 1); return has_no_perspective && has_no_rotation_or_skew; } bool Transform::HasPerspective() const { return matrix_.getDouble(3, 0) || matrix_.getDouble(3, 1) || matrix_.getDouble(3, 2) || (matrix_.getDouble(3, 3) != 1); } bool Transform::IsInvertible() const { return std::abs(matrix_.determinant()) > kTooSmallForDeterminant; } bool Transform::IsBackFaceVisible() const { // Compute whether a layer with a forward-facing normal of (0, 0, 1) would // have its back face visible after applying the transform. // // This is done by transforming the normal and seeing if the resulting z // value is positive or negative. However, note that transforming a normal // actually requires using the inverse-transpose of the original transform. // TODO (shawnsingh) make this perform more efficiently - we do not // actually need to instantiate/invert/transpose any matrices, exploiting the // fact that we only need to transform (0, 0, 1, 0). SkMatrix44 inverse; bool invertible = matrix_.invert(&inverse); // Assume the transform does not apply if it's not invertible, so it's // front face remains visible. if (!invertible) return false; return inverse.getDouble(2, 2) < 0; } bool Transform::GetInverse(Transform* transform) const { return matrix_.invert(&transform->matrix_); } void Transform::Transpose() { matrix_.transpose(); } void Transform::TransformPoint(Point& point) const { TransformPointInternal(matrix_, point); } void Transform::TransformPoint(Point3F& point) const { TransformPointInternal(matrix_, point); } bool Transform::TransformPointReverse(Point& point) const { // TODO(sad): Try to avoid trying to invert the matrix. SkMatrix44 inverse; if (!matrix_.invert(&inverse)) return false; TransformPointInternal(inverse, point); return true; } bool Transform::TransformPointReverse(Point3F& point) const { // TODO(sad): Try to avoid trying to invert the matrix. SkMatrix44 inverse; if (!matrix_.invert(&inverse)) return false; TransformPointInternal(inverse, point); return true; } void Transform::TransformRect(RectF* rect) const { SkRect src = RectFToSkRect(*rect); const SkMatrix& matrix = matrix_; matrix.mapRect(&src); *rect = SkRectToRectF(src); } bool Transform::TransformRectReverse(RectF* rect) const { SkMatrix44 inverse; if (!matrix_.invert(&inverse)) return false; const SkMatrix& matrix = inverse; SkRect src = RectFToSkRect(*rect); matrix.mapRect(&src); *rect = SkRectToRectF(src); return true; } bool Transform::Blend(const Transform& from, double progress) { if (progress <= 0.0) { *this = from; return true; } if (progress >= 1.0) return true; DecomposedTransform to_decomp; DecomposedTransform from_decomp; if (!DecomposeTransform(&to_decomp, *this) || !DecomposeTransform(&from_decomp, from)) return false; if (!BlendDecomposedTransforms(&to_decomp, to_decomp, from_decomp, progress)) return false; matrix_ = ComposeTransform(to_decomp).matrix(); return true; } Transform Transform::operator*(const Transform& other) const { Transform to_return; to_return.matrix_.setConcat(matrix_, other.matrix_); return to_return; } Transform& Transform::operator*=(const Transform& other) { matrix_.preConcat(other.matrix_); return *this; } void Transform::TransformPointInternal(const SkMatrix44& xform, Point3F& point) const { SkMScalar p[4] = { SkDoubleToMScalar(point.x()), SkDoubleToMScalar(point.y()), SkDoubleToMScalar(point.z()), SkDoubleToMScalar(1) }; xform.mapMScalars(p); if (p[3] != 1 && abs(p[3]) > 0) { point.SetPoint(p[0] / p[3], p[1] / p[3], p[2]/ p[3]); } else { point.SetPoint(p[0], p[1], p[2]); } } void Transform::TransformPointInternal(const SkMatrix44& xform, Point& point) const { SkMScalar p[4] = { SkDoubleToMScalar(point.x()), SkDoubleToMScalar(point.y()), SkDoubleToMScalar(0), SkDoubleToMScalar(1) }; xform.mapMScalars(p); point.SetPoint(ToRoundedInt(p[0]), ToRoundedInt(p[1])); } } // namespace gfx <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: testC3DFileAdapter.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the 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 "OpenSim/Common/C3DFileAdapter.h" #include "OpenSim/Common/TRCFileAdapter.h" #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <vector> #include <unordered_map> #include <cstdlib> #include <chrono> #include <thread> #include <cmath> template<typename ETY = SimTK::Real> void compare_tables(const OpenSim::TimeSeriesTable_<ETY>& table1, const OpenSim::TimeSeriesTable_<ETY>& table2, const double tolerance = SimTK::SignificantReal) { using namespace OpenSim; try { OPENSIM_THROW_IF(table1.getColumnLabels() != table2.getColumnLabels(), Exception, "Column labels are not the same for tables."); ASSERT_EQUAL( table1.getIndependentColumn(), table2.getIndependentColumn(), tolerance, __FILE__, __LINE__, "Independent columns are not equivalent."); } catch (const OpenSim::KeyNotFound&) {} const auto& matrix1 = table1.getMatrix(); const auto& matrix2 = table2.getMatrix(); for(int r = 0; r < matrix1.nrow(); ++r) for(int c = 0; c < matrix1.ncol(); ++c) { auto elt1 = matrix1.getElt(r, c); auto elt2 = matrix2.getElt(r, c); ASSERT_EQUAL(elt1, elt2, tolerance, __FILE__, __LINE__, "Element at row, " + std::to_string(r) + " col, " + std::to_string(c) + " failed to have matching value."); } } template<typename ETY = SimTK::Real> void downsample_table(OpenSim::TimeSeriesTable_<ETY>& table, const unsigned int increment) { for (size_t r = table.getNumRows() - 2; r > 0; --r) { if (r%increment) table.removeRowAtIndex(r); } } void test(const std::string filename) { using namespace OpenSim; using namespace std; // The walking C3D files included in this test should not take more // than 40ms on most hardware. We make the max time 100ms to account // for potentially slower CI machines. const double MaximumLoadTimeInMS = 100; std::clock_t startTime = std::clock(); auto tables = C3DFileAdapter::read(filename, C3DFileAdapter::ForceLocation::OriginOfForcePlate); double loadTime = 1.e3*(std::clock() - startTime) / CLOCKS_PER_SEC; cout << "\tC3DFileAdapter '" << filename << "' loaded in " << loadTime << "ms" << endl; #ifdef NDEBUG ASSERT(loadTime < MaximumLoadTimeInMS, __FILE__, __LINE__, "Unable to load '" + filename + "' within " + to_string(MaximumLoadTimeInMS) + "ms."); #endif auto& marker_table = tables.at("markers"); auto& force_table = tables.at("forces"); downsample_table(*marker_table, 10); downsample_table(*force_table, 100); size_t ext = filename.rfind("."); std::string base = filename.substr(0, ext); const std::string marker_file = base + "_markers.trc"; const std::string forces_file = base + "_grfs.sto"; ASSERT(marker_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read marker data from " + filename); marker_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); TRCFileAdapter trc_adapter{}; std::clock_t t0 = std::clock(); trc_adapter.write(*marker_table, marker_file); cout << "\tWrote '" << marker_file << "' in " << 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC << "ms" << endl; ASSERT(force_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read forces data from " + filename); force_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); STOFileAdapter sto_adapter{}; t0 = std::clock(); sto_adapter.write((force_table->flatten()), forces_file); cout << "\tWrote'" << forces_file << "' in " << 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC << "ms" << endl; // Verify that marker data was written out and can be read in t0 = std::clock(); auto markers = trc_adapter.read(marker_file); auto std_markers = trc_adapter.read("std_" + marker_file); cout << "\tRead'" << marker_file << "' and its standard in " << 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC << "ms" << endl; // Compare C3DFileAdapter read-in and written marker data compare_tables<SimTK::Vec3>(markers, *marker_table); // Compare C3DFileAdapter written marker data to standard // Note std exported from Mokka with only 5 decimal places compare_tables<SimTK::Vec3>(markers, std_markers, 1e-4); cout << "\tMarkers " << marker_file << " equivalent to standard." << endl; // Verify that grfs data was written out and can be read in auto forces = sto_adapter.read(forces_file); auto std_forces = sto_adapter.read("std_" + forces_file); // Compare C3DFileAdapter read-in and written forces data compare_tables<SimTK::Vec3>(forces.pack<SimTK::Vec3>(), *force_table, SimTK::SqrtEps); // Compare C3DFileAdapter written forces data to standard // Note std generated using MATLAB C3D processing scripts compare_tables(forces, std_forces, SimTK::SqrtEps); cout << "\tForces " << forces_file << " equivalent to standard." << endl; t0 = std::clock(); // Reread in C3D file with forces resolved to the COP auto tables2 = C3DFileAdapter::read(filename, C3DFileAdapter::ForceLocation::CenterOfPressure); loadTime = 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC; cout << "\tC3DFileAdapter '" << filename << "' read with forces at COP in " << loadTime << "ms" << endl; #ifdef NDEBUG ASSERT(loadTime < MaximumLoadTimeInMS, __FILE__, __LINE__, "Unable to load '" + filename + "' within " + to_string(MaximumLoadTimeInMS) + "ms."); #endif auto& force_table_cop = tables2.at("forces"); downsample_table(*force_table_cop, 100); sto_adapter.write(force_table_cop->flatten(), "cop_"+ forces_file); auto std_forces_cop = sto_adapter.read("std_cop_" + forces_file); // Compare C3DFileAdapter written forces data to standard // Note std generated using MATLAB C3D processing scripts compare_tables<SimTK::Vec3>(*force_table_cop, std_forces_cop.pack<SimTK::Vec3>(), SimTK::SqrtEps); cout << "\tcop_" << forces_file << " is equivalent to its standard."<< endl; cout << "\ttestC3DFileAdapter '" << filename << "' completed in " << 1.e3*(std::clock() - startTime) / CLOCKS_PER_SEC << "ms" << endl; } int main() { std::vector<std::string> filenames{}; filenames.push_back("walking2.c3d"); filenames.push_back("walking5.c3d"); for(const auto& filename : filenames) { std::cout << "\nTest reading '" + filename + "'." << std::endl; try { test(filename); } catch (const std::exception& ex) { std::cout << "testC3DFileAdapter FAILED: " << ex.what() << std::endl; return 1; } } std::cout << "\nAll testC3DFileAdapter cases passed." << std::endl; return 0; } <commit_msg>Disable the load time condition to enable Travis CI to pass consistently.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: testC3DFileAdapter.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the 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 "OpenSim/Common/C3DFileAdapter.h" #include "OpenSim/Common/TRCFileAdapter.h" #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <vector> #include <unordered_map> #include <cstdlib> #include <chrono> #include <thread> #include <cmath> template<typename ETY = SimTK::Real> void compare_tables(const OpenSim::TimeSeriesTable_<ETY>& table1, const OpenSim::TimeSeriesTable_<ETY>& table2, const double tolerance = SimTK::SignificantReal) { using namespace OpenSim; try { OPENSIM_THROW_IF(table1.getColumnLabels() != table2.getColumnLabels(), Exception, "Column labels are not the same for tables."); ASSERT_EQUAL( table1.getIndependentColumn(), table2.getIndependentColumn(), tolerance, __FILE__, __LINE__, "Independent columns are not equivalent."); } catch (const OpenSim::KeyNotFound&) {} const auto& matrix1 = table1.getMatrix(); const auto& matrix2 = table2.getMatrix(); for(int r = 0; r < matrix1.nrow(); ++r) for(int c = 0; c < matrix1.ncol(); ++c) { auto elt1 = matrix1.getElt(r, c); auto elt2 = matrix2.getElt(r, c); ASSERT_EQUAL(elt1, elt2, tolerance, __FILE__, __LINE__, "Element at row, " + std::to_string(r) + " col, " + std::to_string(c) + " failed to have matching value."); } } template<typename ETY = SimTK::Real> void downsample_table(OpenSim::TimeSeriesTable_<ETY>& table, const unsigned int increment) { for (size_t r = table.getNumRows() - 2; r > 0; --r) { if (r%increment) table.removeRowAtIndex(r); } } void test(const std::string filename) { using namespace OpenSim; using namespace std; // The walking C3D files included in this test should not take more // than 40ms on most hardware. We make the max time 100ms to account // for potentially slower CI machines. const double MaximumLoadTimeInMS = 100; std::clock_t startTime = std::clock(); auto tables = C3DFileAdapter::read(filename, C3DFileAdapter::ForceLocation::OriginOfForcePlate); double loadTime = 1.e3*(std::clock() - startTime) / CLOCKS_PER_SEC; cout << "\tC3DFileAdapter '" << filename << "' loaded in " << loadTime << "ms" << endl; /* Disabled performance test because Travis CI is consistently unable to meet this timing requirement. Consider PR#2221 to address this issue longer term. #ifdef NDEBUG ASSERT(loadTime < MaximumLoadTimeInMS, __FILE__, __LINE__, "Unable to load '" + filename + "' within " + to_string(MaximumLoadTimeInMS) + "ms."); #endif */ auto& marker_table = tables.at("markers"); auto& force_table = tables.at("forces"); downsample_table(*marker_table, 10); downsample_table(*force_table, 100); size_t ext = filename.rfind("."); std::string base = filename.substr(0, ext); const std::string marker_file = base + "_markers.trc"; const std::string forces_file = base + "_grfs.sto"; ASSERT(marker_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read marker data from " + filename); marker_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); TRCFileAdapter trc_adapter{}; std::clock_t t0 = std::clock(); trc_adapter.write(*marker_table, marker_file); cout << "\tWrote '" << marker_file << "' in " << 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC << "ms" << endl; ASSERT(force_table->getNumRows() > 0, __FILE__, __LINE__, "Failed to read forces data from " + filename); force_table->updTableMetaData().setValueForKey("Units", std::string{"mm"}); STOFileAdapter sto_adapter{}; t0 = std::clock(); sto_adapter.write((force_table->flatten()), forces_file); cout << "\tWrote'" << forces_file << "' in " << 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC << "ms" << endl; // Verify that marker data was written out and can be read in t0 = std::clock(); auto markers = trc_adapter.read(marker_file); auto std_markers = trc_adapter.read("std_" + marker_file); cout << "\tRead'" << marker_file << "' and its standard in " << 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC << "ms" << endl; // Compare C3DFileAdapter read-in and written marker data compare_tables<SimTK::Vec3>(markers, *marker_table); // Compare C3DFileAdapter written marker data to standard // Note std exported from Mokka with only 5 decimal places compare_tables<SimTK::Vec3>(markers, std_markers, 1e-4); cout << "\tMarkers " << marker_file << " equivalent to standard." << endl; // Verify that grfs data was written out and can be read in auto forces = sto_adapter.read(forces_file); auto std_forces = sto_adapter.read("std_" + forces_file); // Compare C3DFileAdapter read-in and written forces data compare_tables<SimTK::Vec3>(forces.pack<SimTK::Vec3>(), *force_table, SimTK::SqrtEps); // Compare C3DFileAdapter written forces data to standard // Note std generated using MATLAB C3D processing scripts compare_tables(forces, std_forces, SimTK::SqrtEps); cout << "\tForces " << forces_file << " equivalent to standard." << endl; t0 = std::clock(); // Reread in C3D file with forces resolved to the COP auto tables2 = C3DFileAdapter::read(filename, C3DFileAdapter::ForceLocation::CenterOfPressure); loadTime = 1.e3*(std::clock() - t0) / CLOCKS_PER_SEC; cout << "\tC3DFileAdapter '" << filename << "' read with forces at COP in " << loadTime << "ms" << endl; #ifdef NDEBUG ASSERT(loadTime < MaximumLoadTimeInMS, __FILE__, __LINE__, "Unable to load '" + filename + "' within " + to_string(MaximumLoadTimeInMS) + "ms."); #endif auto& force_table_cop = tables2.at("forces"); downsample_table(*force_table_cop, 100); sto_adapter.write(force_table_cop->flatten(), "cop_"+ forces_file); auto std_forces_cop = sto_adapter.read("std_cop_" + forces_file); // Compare C3DFileAdapter written forces data to standard // Note std generated using MATLAB C3D processing scripts compare_tables<SimTK::Vec3>(*force_table_cop, std_forces_cop.pack<SimTK::Vec3>(), SimTK::SqrtEps); cout << "\tcop_" << forces_file << " is equivalent to its standard."<< endl; cout << "\ttestC3DFileAdapter '" << filename << "' completed in " << 1.e3*(std::clock() - startTime) / CLOCKS_PER_SEC << "ms" << endl; } int main() { std::vector<std::string> filenames{}; filenames.push_back("walking2.c3d"); filenames.push_back("walking5.c3d"); for(const auto& filename : filenames) { std::cout << "\nTest reading '" + filename + "'." << std::endl; try { test(filename); } catch (const std::exception& ex) { std::cout << "testC3DFileAdapter FAILED: " << ex.what() << std::endl; return 1; } } std::cout << "\nAll testC3DFileAdapter cases passed." << std::endl; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <chrono> #include "lodepng.h" using std::cout; using std::endl; // Image found at https://pixabay.com/no/bloom-blomstre-bud-gjeng-farge-2518/ const std::string IMG_FNAME = "bloom_small.png"; const std::string IMG_FNAME_MODIFIED = "bloom_new.png"; struct image_data { std::vector<unsigned char> pixels; const unsigned int width; const unsigned int height; image_data(std::vector<unsigned char> pixels, const unsigned int width, const unsigned int height) : width(width), height(height) { this->pixels = pixels; } }; image_data load_image_from_png_file(std::string filename) { std::vector<unsigned char> image; unsigned width, height; unsigned error = lodepng::decode(image, width, height, filename, LCT_RGB); if(error) { cout << "Decoder error " << error << ": " << lodepng_error_text(error) << endl; width = 0; height = 0; } image_data img_data(image, width, height); return img_data; } bool write_image_to_png_file(std::string filename, image_data image) { unsigned error = lodepng::encode(filename, image.pixels, image.width, image.height, LCT_RGB); if(error) { cout << "Encoder error " << error << ": "<< lodepng_error_text(error) << endl; return false; } return true; } void apply_blur_filter( const std::vector<unsigned char>& imageIn, std::vector<unsigned char>& imageOut, const unsigned int width, const unsigned int height, const unsigned int filterSize) { const int start_coordinate = filterSize / 2; const int end_x = width - start_coordinate; const int end_y = height - start_coordinate; std::vector<unsigned int> line_buffer(width * 3); // Fill the line buffer for (int y = 0; y < (int)filterSize - 1; ++y) { for (int x = 0; x < (int)line_buffer.size(); x += 3) { const int i = (y * width + x) * 3; line_buffer[x] += imageIn[i]; line_buffer[x + 1] += imageIn[i + 1]; line_buffer[x + 2] += imageIn[i + 2]; } } // Iterate all pixels, one line of pixels at a time for (int y = start_coordinate; y < end_y; ++y) { for (int x = start_coordinate; x < end_x; ++x) { // Add new row to line buffer for (int lb_index = 0; lb_index < (int)line_buffer.size(); lb_index += 3) { const int i = ((y + filterSize / 2) * width + x) * 3; line_buffer[lb_index] += imageIn[i]; line_buffer[lb_index + 1] += imageIn[i + 1]; line_buffer[lb_index + 2] += imageIn[i + 2]; } unsigned int blur_sum_r = 0; unsigned int blur_sum_g = 0; unsigned int blur_sum_b = 0; const int sum_start_x = x - filterSize / 2; const int sum_end_x = x + filterSize / 2; const int lb_index_start = sum_start_x * 3; const int lb_index_end = sum_end_x * 3; for (int lb_index = lb_index_start; lb_index <= lb_index_end; lb_index += 3) { blur_sum_r += line_buffer[lb_index]; blur_sum_g += line_buffer[lb_index + 1]; blur_sum_b += line_buffer[lb_index + 2]; } const int index = (y * width + x) * 3; imageOut[index] = blur_sum_r / (filterSize * filterSize); imageOut[index + 1] = blur_sum_g / (filterSize * filterSize); imageOut[index + 2] = blur_sum_b / (filterSize * filterSize); // Remove last row from line buffer for (int idx = 0; idx < (int)line_buffer.size(); idx += 3) { const int i = ((y - filterSize / 2) * width + x) * 3; line_buffer[idx] -= imageIn[i]; line_buffer[idx + 1] -= imageIn[i + 1]; line_buffer[idx + 2] -= imageIn[i + 2]; } } } } int main(int argc, char const *argv[]) { image_data image = load_image_from_png_file(IMG_FNAME); if (image.width == 0) return -1; std::vector<unsigned char> image2_pixels(image.pixels.size()); image_data image2(image2_pixels, image.width, image.height); using namespace std::chrono; auto start_time = high_resolution_clock::now(); apply_blur_filter(image.pixels, image2.pixels, image.width, image.height, 11); auto end_time = high_resolution_clock::now(); bool success = write_image_to_png_file(IMG_FNAME_MODIFIED, image2); if (!success) return -1; cout << "Processor time used to process image: " << duration_cast<microseconds>(end_time - start_time).count() << " microseconds" << endl; return 0; } <commit_msg>Optimized version now works correctly<commit_after>#include <iostream> #include <string> #include <chrono> #include "lodepng.h" using std::cout; using std::endl; // Image found at https://pixabay.com/no/bloom-blomstre-bud-gjeng-farge-2518/ const std::string IMG_FNAME = "bloom_small.png"; const std::string IMG_FNAME_MODIFIED = "bloom_new.png"; struct image_data { std::vector<unsigned char> pixels; const unsigned int width; const unsigned int height; image_data(std::vector<unsigned char> pixels, const unsigned int width, const unsigned int height) : width(width), height(height) { this->pixels = pixels; } }; image_data load_image_from_png_file(std::string filename) { std::vector<unsigned char> image; unsigned width, height; unsigned error = lodepng::decode(image, width, height, filename, LCT_RGB); if(error) { cout << "Decoder error " << error << ": " << lodepng_error_text(error) << endl; width = 0; height = 0; } image_data img_data(image, width, height); return img_data; } bool write_image_to_png_file(std::string filename, image_data image) { unsigned error = lodepng::encode(filename, image.pixels, image.width, image.height, LCT_RGB); if(error) { cout << "Encoder error " << error << ": "<< lodepng_error_text(error) << endl; return false; } return true; } void apply_blur_filter( const std::vector<unsigned char>& imageIn, std::vector<unsigned char>& imageOut, const unsigned int width, const unsigned int height, const unsigned int filterSize) { const int start_coordinate = filterSize / 2; const int end_x = width - start_coordinate; const int end_y = height - start_coordinate; std::vector<unsigned int> line_buffer(width * 3); // TODO: Some variables might not have to be calculated for each iteration (e.g. index). Increment instead. // Fill the line buffer for (int y = 0; y < (int)filterSize - 1; ++y) { for (int x = 0; x < (int)width; ++x) { const int index = (y * width + x) * 3; const int lb_index = x * 3; line_buffer[lb_index] += imageIn[index]; line_buffer[lb_index + 1] += imageIn[index + 1]; line_buffer[lb_index + 2] += imageIn[index + 2]; } } // Iterate all pixels, one line of pixels at a time for (int y = start_coordinate; y < end_y; ++y) { // Add new row to line buffer for (int lb_x = 0; lb_x < (int)width; ++lb_x) { const int lb_index = lb_x * 3; const int index = ((y + filterSize / 2) * width + lb_x) * 3; line_buffer[lb_index] += imageIn[index]; line_buffer[lb_index + 1] += imageIn[index + 1]; line_buffer[lb_index + 2] += imageIn[index + 2]; } // Iterate along row of pixels, sum up and calculate averages for (int x = start_coordinate; x < end_x; ++x) { unsigned int blur_sum_r = 0; unsigned int blur_sum_g = 0; unsigned int blur_sum_b = 0; const int sum_start_x = x - filterSize / 2; const int sum_end_x = x + filterSize / 2; const int lb_index_start = sum_start_x * 3; const int lb_index_end = sum_end_x * 3; for (int lb_index = lb_index_start; lb_index <= lb_index_end; lb_index += 3) { blur_sum_r += line_buffer[lb_index]; blur_sum_g += line_buffer[lb_index + 1]; blur_sum_b += line_buffer[lb_index + 2]; } const int index = (y * width + x) * 3; imageOut[index] = blur_sum_r / (filterSize * filterSize); imageOut[index + 1] = blur_sum_g / (filterSize * filterSize); imageOut[index + 2] = blur_sum_b / (filterSize * filterSize); } // Remove last row from line buffer for (int lb_x = 0; lb_x < (int)width; ++lb_x) { const int lb_index = lb_x * 3; const int index = ((y - filterSize / 2) * width + lb_x) * 3; line_buffer[lb_index] -= imageIn[index]; line_buffer[lb_index + 1] -= imageIn[index + 1]; line_buffer[lb_index + 2] -= imageIn[index + 2]; } } } int main(int argc, char const *argv[]) { image_data image = load_image_from_png_file(IMG_FNAME); if (image.width == 0) return -1; std::vector<unsigned char> image2_pixels(image.pixels.size()); image_data image2(image2_pixels, image.width, image.height); using namespace std::chrono; auto start_time = high_resolution_clock::now(); apply_blur_filter(image.pixels, image2.pixels, image.width, image.height, 11); auto end_time = high_resolution_clock::now(); bool success = write_image_to_png_file(IMG_FNAME_MODIFIED, image2); if (!success) return -1; cout << "Processor time used to process image: " << duration_cast<microseconds>(end_time - start_time).count() << " microseconds" << endl; return 0; } <|endoftext|>
<commit_before>#include "Test.h" #include "Sk4x.h" #define ASSERT_EQ(a, b) REPORTER_ASSERT(r, a.equal(b).allTrue()) #define ASSERT_NE(a, b) REPORTER_ASSERT(r, a.notEqual(b).allTrue()) DEF_TEST(Sk4x_Construction, r) { Sk4f uninitialized; Sk4f zero(0,0,0,0); Sk4f foo(1,2,3,4), bar(foo), baz = bar; ASSERT_EQ(foo, bar); ASSERT_EQ(bar, baz); ASSERT_EQ(baz, foo); } struct AlignedFloats { Sk4f forces16ByteAlignment; // On 64-bit machines, the stack starts 128-bit aligned, float fs[5]; // but not necessarily so on 32-bit. Adding an Sk4f forces it. }; DEF_TEST(Sk4x_LoadStore, r) { AlignedFloats aligned; // fs will be 16-byte aligned, fs+1 not. float* fs = aligned.fs; for (int i = 0; i < 5; i++) { // set to 5,6,7,8,9 fs[i] = float(i+5); } Sk4f foo = Sk4f::Load(fs); Sk4f bar = Sk4f::LoadAligned(fs); ASSERT_EQ(foo, bar); foo = Sk4f::Load(fs+1); ASSERT_NE(foo, bar); foo.storeAligned(fs); bar.store(fs+1); REPORTER_ASSERT(r, fs[0] == 6 && fs[1] == 5 && fs[2] == 6 && fs[3] == 7 && fs[4] == 8); } DEF_TEST(Sk4x_Conversions, r) { // Assuming IEEE floats. Sk4f zerof(0,0,0,0); Sk4i zeroi(0,0,0,0); ASSERT_EQ(zeroi, zerof.cast<Sk4i>()); ASSERT_EQ(zeroi, zerof.reinterpret<Sk4i>()); ASSERT_EQ(zerof, zeroi.cast<Sk4f>()); ASSERT_EQ(zerof, zeroi.reinterpret<Sk4f>()); Sk4f twof(2,2,2,2); Sk4i twoi(2,2,2,2); ASSERT_EQ(twoi, twof.cast<Sk4i>()); ASSERT_NE(twoi, twof.reinterpret<Sk4i>()); ASSERT_EQ(twof, twoi.cast<Sk4f>()); ASSERT_NE(twof, twoi.reinterpret<Sk4f>()); } DEF_TEST(Sk4x_Bits, r) { ASSERT_EQ(Sk4i(0,0,0,0).bitNot(), Sk4i(-1,-1,-1,-1)); Sk4i a(2,3,4,5), b(1,3,5,7); ASSERT_EQ(Sk4i(0,3,4,5), a & b); ASSERT_EQ(Sk4i(3,3,5,7), a | b); } DEF_TEST(Sk4x_Arith, r) { ASSERT_EQ(Sk4f(4,6,8,10), Sk4f(1,2,3,4) + Sk4f(3,4,5,6)); ASSERT_EQ(Sk4f(-2,-2,-2,-2), Sk4f(1,2,3,4) - Sk4f(3,4,5,6)); ASSERT_EQ(Sk4f(3,8,15,24), Sk4f(1,2,3,4) * Sk4f(3,4,5,6)); ASSERT_EQ(Sk4f(-1,-2,-3,-4), -Sk4f(1,2,3,4)); float third = 1.0f/3.0f; ASSERT_EQ(Sk4f(1*third, 0.5f, 0.6f, 2*third), Sk4f(1,2,3,4) / Sk4f(3,4,5,6)); ASSERT_EQ(Sk4i(4,6,8,10), Sk4i(1,2,3,4) + Sk4i(3,4,5,6)); ASSERT_EQ(Sk4i(-2,-2,-2,-2), Sk4i(1,2,3,4) - Sk4i(3,4,5,6)); ASSERT_EQ(Sk4i(3,8,15,24), Sk4i(1,2,3,4) * Sk4i(3,4,5,6)); } DEF_TEST(Sk4x_ExplicitPromotion, r) { ASSERT_EQ(Sk4f(2,4,6,8), Sk4f(1,2,3,4) * Sk4f(2.0f)); } DEF_TEST(Sk4x_Sqrt, r) { Sk4f squares(4, 16, 25, 121), roots(2, 4, 5, 11); // .sqrt() should be pretty precise. Sk4f error = roots.subtract(squares.sqrt()); REPORTER_ASSERT(r, error.greaterThanEqual(Sk4f(0.0f)).allTrue()); REPORTER_ASSERT(r, error.lessThan(Sk4f(0.000001f)).allTrue()); // .rsqrt() isn't so precise (for SSE), but should be pretty close. error = roots.subtract(squares.multiply(squares.rsqrt())); REPORTER_ASSERT(r, error.greaterThanEqual(Sk4f(0.0f)).allTrue()); REPORTER_ASSERT(r, error.lessThan(Sk4f(0.01f)).allTrue()); } DEF_TEST(Sk4x_Comparison, r) { ASSERT_EQ(Sk4f(1,2,3,4), Sk4f(1,2,3,4)); ASSERT_NE(Sk4f(4,3,2,1), Sk4f(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,0,-1), Sk4f(1,2,5,4) == Sk4f(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4f(1,2,3,4) < Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4f(1,2,3,4) <= Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4f(1,2,3,4) > Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4f(1,2,3,4) >= Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(1,2,3,4), Sk4i(1,2,3,4)); ASSERT_NE(Sk4i(4,3,2,1), Sk4i(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,0,-1), Sk4i(1,2,5,4) == Sk4i(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4i(1,2,3,4) < Sk4i(2,3,4,5)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4i(1,2,3,4) <= Sk4i(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4i(1,2,3,4) > Sk4i(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4i(1,2,3,4) >= Sk4i(2,3,4,5)); } DEF_TEST(Sk4x_MinMax, r) { ASSERT_EQ(Sk4f(1,2,2,1), Sk4f::Min(Sk4f(1,2,3,4), Sk4f(4,3,2,1))); ASSERT_EQ(Sk4f(4,3,3,4), Sk4f::Max(Sk4f(1,2,3,4), Sk4f(4,3,2,1))); ASSERT_EQ(Sk4i(1,2,2,1), Sk4i::Min(Sk4i(1,2,3,4), Sk4i(4,3,2,1))); ASSERT_EQ(Sk4i(4,3,3,4), Sk4i::Max(Sk4i(1,2,3,4), Sk4i(4,3,2,1))); } DEF_TEST(Sk4x_Swizzle, r) { ASSERT_EQ(Sk4f(3,4,1,2), Sk4f(1,2,3,4).zwxy()); ASSERT_EQ(Sk4f(1,2,5,6), Sk4f::XYAB(Sk4f(1,2,3,4), Sk4f(5,6,7,8))); ASSERT_EQ(Sk4f(3,4,7,8), Sk4f::ZWCD(Sk4f(1,2,3,4), Sk4f(5,6,7,8))); ASSERT_EQ(Sk4i(3,4,1,2), Sk4i(1,2,3,4).zwxy()); ASSERT_EQ(Sk4i(1,2,5,6), Sk4i::XYAB(Sk4i(1,2,3,4), Sk4i(5,6,7,8))); ASSERT_EQ(Sk4i(3,4,7,8), Sk4i::ZWCD(Sk4i(1,2,3,4), Sk4i(5,6,7,8))); } <commit_msg>Allow negative error for Sk4f::sqrt() test.<commit_after>#include "Test.h" #include "Sk4x.h" #define ASSERT_EQ(a, b) REPORTER_ASSERT(r, a.equal(b).allTrue()) #define ASSERT_NE(a, b) REPORTER_ASSERT(r, a.notEqual(b).allTrue()) DEF_TEST(Sk4x_Construction, r) { Sk4f uninitialized; Sk4f zero(0,0,0,0); Sk4f foo(1,2,3,4), bar(foo), baz = bar; ASSERT_EQ(foo, bar); ASSERT_EQ(bar, baz); ASSERT_EQ(baz, foo); } struct AlignedFloats { Sk4f forces16ByteAlignment; // On 64-bit machines, the stack starts 128-bit aligned, float fs[5]; // but not necessarily so on 32-bit. Adding an Sk4f forces it. }; DEF_TEST(Sk4x_LoadStore, r) { AlignedFloats aligned; // fs will be 16-byte aligned, fs+1 not. float* fs = aligned.fs; for (int i = 0; i < 5; i++) { // set to 5,6,7,8,9 fs[i] = float(i+5); } Sk4f foo = Sk4f::Load(fs); Sk4f bar = Sk4f::LoadAligned(fs); ASSERT_EQ(foo, bar); foo = Sk4f::Load(fs+1); ASSERT_NE(foo, bar); foo.storeAligned(fs); bar.store(fs+1); REPORTER_ASSERT(r, fs[0] == 6 && fs[1] == 5 && fs[2] == 6 && fs[3] == 7 && fs[4] == 8); } DEF_TEST(Sk4x_Conversions, r) { // Assuming IEEE floats. Sk4f zerof(0,0,0,0); Sk4i zeroi(0,0,0,0); ASSERT_EQ(zeroi, zerof.cast<Sk4i>()); ASSERT_EQ(zeroi, zerof.reinterpret<Sk4i>()); ASSERT_EQ(zerof, zeroi.cast<Sk4f>()); ASSERT_EQ(zerof, zeroi.reinterpret<Sk4f>()); Sk4f twof(2,2,2,2); Sk4i twoi(2,2,2,2); ASSERT_EQ(twoi, twof.cast<Sk4i>()); ASSERT_NE(twoi, twof.reinterpret<Sk4i>()); ASSERT_EQ(twof, twoi.cast<Sk4f>()); ASSERT_NE(twof, twoi.reinterpret<Sk4f>()); } DEF_TEST(Sk4x_Bits, r) { ASSERT_EQ(Sk4i(0,0,0,0).bitNot(), Sk4i(-1,-1,-1,-1)); Sk4i a(2,3,4,5), b(1,3,5,7); ASSERT_EQ(Sk4i(0,3,4,5), a & b); ASSERT_EQ(Sk4i(3,3,5,7), a | b); } DEF_TEST(Sk4x_Arith, r) { ASSERT_EQ(Sk4f(4,6,8,10), Sk4f(1,2,3,4) + Sk4f(3,4,5,6)); ASSERT_EQ(Sk4f(-2,-2,-2,-2), Sk4f(1,2,3,4) - Sk4f(3,4,5,6)); ASSERT_EQ(Sk4f(3,8,15,24), Sk4f(1,2,3,4) * Sk4f(3,4,5,6)); ASSERT_EQ(Sk4f(-1,-2,-3,-4), -Sk4f(1,2,3,4)); float third = 1.0f/3.0f; ASSERT_EQ(Sk4f(1*third, 0.5f, 0.6f, 2*third), Sk4f(1,2,3,4) / Sk4f(3,4,5,6)); ASSERT_EQ(Sk4i(4,6,8,10), Sk4i(1,2,3,4) + Sk4i(3,4,5,6)); ASSERT_EQ(Sk4i(-2,-2,-2,-2), Sk4i(1,2,3,4) - Sk4i(3,4,5,6)); ASSERT_EQ(Sk4i(3,8,15,24), Sk4i(1,2,3,4) * Sk4i(3,4,5,6)); } DEF_TEST(Sk4x_ExplicitPromotion, r) { ASSERT_EQ(Sk4f(2,4,6,8), Sk4f(1,2,3,4) * Sk4f(2.0f)); } DEF_TEST(Sk4x_Sqrt, r) { Sk4f squares(4, 16, 25, 121), roots(2, 4, 5, 11); // .sqrt() should be pretty precise. Sk4f error = roots.subtract(squares.sqrt()); REPORTER_ASSERT(r, (error > Sk4f(-0.000001f)).allTrue()); REPORTER_ASSERT(r, (error < Sk4f(+0.000001f)).allTrue()); // .rsqrt() isn't so precise (for SSE), but should be pretty close. error = roots.subtract(squares.multiply(squares.rsqrt())); REPORTER_ASSERT(r, (error > Sk4f(-0.01f)).allTrue()); REPORTER_ASSERT(r, (error < Sk4f(+0.01f)).allTrue()); } DEF_TEST(Sk4x_Comparison, r) { ASSERT_EQ(Sk4f(1,2,3,4), Sk4f(1,2,3,4)); ASSERT_NE(Sk4f(4,3,2,1), Sk4f(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,0,-1), Sk4f(1,2,5,4) == Sk4f(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4f(1,2,3,4) < Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4f(1,2,3,4) <= Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4f(1,2,3,4) > Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4f(1,2,3,4) >= Sk4f(2,3,4,5)); ASSERT_EQ(Sk4i(1,2,3,4), Sk4i(1,2,3,4)); ASSERT_NE(Sk4i(4,3,2,1), Sk4i(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,0,-1), Sk4i(1,2,5,4) == Sk4i(1,2,3,4)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4i(1,2,3,4) < Sk4i(2,3,4,5)); ASSERT_EQ(Sk4i(-1,-1,-1,-1), Sk4i(1,2,3,4) <= Sk4i(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4i(1,2,3,4) > Sk4i(2,3,4,5)); ASSERT_EQ(Sk4i(0,0,0,0), Sk4i(1,2,3,4) >= Sk4i(2,3,4,5)); } DEF_TEST(Sk4x_MinMax, r) { ASSERT_EQ(Sk4f(1,2,2,1), Sk4f::Min(Sk4f(1,2,3,4), Sk4f(4,3,2,1))); ASSERT_EQ(Sk4f(4,3,3,4), Sk4f::Max(Sk4f(1,2,3,4), Sk4f(4,3,2,1))); ASSERT_EQ(Sk4i(1,2,2,1), Sk4i::Min(Sk4i(1,2,3,4), Sk4i(4,3,2,1))); ASSERT_EQ(Sk4i(4,3,3,4), Sk4i::Max(Sk4i(1,2,3,4), Sk4i(4,3,2,1))); } DEF_TEST(Sk4x_Swizzle, r) { ASSERT_EQ(Sk4f(3,4,1,2), Sk4f(1,2,3,4).zwxy()); ASSERT_EQ(Sk4f(1,2,5,6), Sk4f::XYAB(Sk4f(1,2,3,4), Sk4f(5,6,7,8))); ASSERT_EQ(Sk4f(3,4,7,8), Sk4f::ZWCD(Sk4f(1,2,3,4), Sk4f(5,6,7,8))); ASSERT_EQ(Sk4i(3,4,1,2), Sk4i(1,2,3,4).zwxy()); ASSERT_EQ(Sk4i(1,2,5,6), Sk4i::XYAB(Sk4i(1,2,3,4), Sk4i(5,6,7,8))); ASSERT_EQ(Sk4i(3,4,7,8), Sk4i::ZWCD(Sk4i(1,2,3,4), Sk4i(5,6,7,8))); } <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #include "../general/array.hpp" #include "vector.hpp" #include "blockvector.hpp" namespace mfem { void BlockVector::SetBlocks() { for (int i = 0; i < numBlocks; ++i) { blocks[i].NewDataAndSize(data+blockOffsets[i], blockOffsets[i+1]-blockOffsets[i]); } } BlockVector::BlockVector(): Vector(), numBlocks(0), blockOffsets(NULL), blocks(NULL) { } //! Standard constructor BlockVector::BlockVector(const Array<int> & bOffsets): Vector(bOffsets.Last()), numBlocks(bOffsets.Size()-1), blockOffsets(bOffsets.GetData()) { blocks = new Vector[numBlocks]; SetBlocks(); } //! Copy constructor BlockVector::BlockVector(const BlockVector & v): Vector(v), numBlocks(v.numBlocks), blockOffsets(v.blockOffsets) { blocks = new Vector[numBlocks]; SetBlocks(); } //! View constructor BlockVector::BlockVector(double *data, const Array<int> & bOffsets): Vector(data, bOffsets.Last()), numBlocks(bOffsets.Size()-1), blockOffsets(bOffsets.GetData()) { blocks = new Vector[numBlocks]; SetBlocks(); } void BlockVector::Update(double *data, const Array<int> & bOffsets) { NewDataAndSize(data, bOffsets.Last()); blockOffsets = bOffsets.GetData(); if (numBlocks != bOffsets.Size()-1) { delete [] blocks; numBlocks = bOffsets.Size()-1; blocks = new Vector[numBlocks]; } SetBlocks(); } void BlockVector::Update(const Array<int> &bOffsets) { if (OwnsData()) { // check if 'bOffsets' agree with the 'blocks' if (bOffsets.Size() == numBlocks+1) { if (numBlocks == 0) { return; } for (int i = 0; true; i++) { if (blocks[i].GetData() - data != bOffsets[i]) { break; } if (i == numBlocks - 1) if (blocks[numBlocks - 1].Size() == bOffsets[numBlocks] - bOffsets[numBlocks - 1]) { blockOffsets = bOffsets.GetData(); return; } else { break; } } } } else { Destroy(); } SetSize(bOffsets.Last()); blockOffsets = bOffsets.GetData(); if (numBlocks != bOffsets.Size()-1) { delete [] blocks; numBlocks = bOffsets.Size()-1; blocks = new Vector[numBlocks]; } SetBlocks(); } BlockVector & BlockVector::operator=(const BlockVector & original) { if (numBlocks!=original.numBlocks) { mfem_error("Number of Blocks don't match in BlockVector::operator="); } for (int i(0); i <= numBlocks; ++i) if (blockOffsets[i]!=original.blockOffsets[i]) { mfem_error("Size of Blocks don't match in BlockVector::operator="); } Vector::operator=(original.GetData()); return *this; } BlockVector & BlockVector::operator=(double val) { Vector::operator=(val); return *this; } //! Destructor BlockVector::~BlockVector() { delete [] blocks; } void BlockVector::GetBlockView(int i, Vector & blockView) { blockView.NewDataAndSize(data+blockOffsets[i], blockOffsets[i+1]-blockOffsets[i]); } } <commit_msg>Tweak a bit the logic in BlockVector::Update().<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #include "../general/array.hpp" #include "vector.hpp" #include "blockvector.hpp" namespace mfem { void BlockVector::SetBlocks() { for (int i = 0; i < numBlocks; ++i) { blocks[i].NewDataAndSize(data+blockOffsets[i], blockOffsets[i+1]-blockOffsets[i]); } } BlockVector::BlockVector(): Vector(), numBlocks(0), blockOffsets(NULL), blocks(NULL) { } //! Standard constructor BlockVector::BlockVector(const Array<int> & bOffsets): Vector(bOffsets.Last()), numBlocks(bOffsets.Size()-1), blockOffsets(bOffsets.GetData()) { blocks = new Vector[numBlocks]; SetBlocks(); } //! Copy constructor BlockVector::BlockVector(const BlockVector & v): Vector(v), numBlocks(v.numBlocks), blockOffsets(v.blockOffsets) { blocks = new Vector[numBlocks]; SetBlocks(); } //! View constructor BlockVector::BlockVector(double *data, const Array<int> & bOffsets): Vector(data, bOffsets.Last()), numBlocks(bOffsets.Size()-1), blockOffsets(bOffsets.GetData()) { blocks = new Vector[numBlocks]; SetBlocks(); } void BlockVector::Update(double *data, const Array<int> & bOffsets) { NewDataAndSize(data, bOffsets.Last()); blockOffsets = bOffsets.GetData(); if (numBlocks != bOffsets.Size()-1) { delete [] blocks; numBlocks = bOffsets.Size()-1; blocks = new Vector[numBlocks]; } SetBlocks(); } void BlockVector::Update(const Array<int> &bOffsets) { blockOffsets = bOffsets.GetData(); if (OwnsData()) { // check if 'bOffsets' agree with the 'blocks' if (bOffsets.Size() == numBlocks+1) { for (int i = 0; true; i++) { if (i >= numBlocks) { return; } if (blocks[i].Size() != bOffsets[i+1] - bOffsets[i]) { break; } MFEM_ASSERT(blocks[i].GetData() == data + bOffsets[i], "invalid blocks[" << i << ']'); } } } else { Destroy(); } SetSize(bOffsets.Last()); if (numBlocks != bOffsets.Size()-1) { delete [] blocks; numBlocks = bOffsets.Size()-1; blocks = new Vector[numBlocks]; } SetBlocks(); } BlockVector & BlockVector::operator=(const BlockVector & original) { if (numBlocks!=original.numBlocks) { mfem_error("Number of Blocks don't match in BlockVector::operator="); } for (int i(0); i <= numBlocks; ++i) if (blockOffsets[i]!=original.blockOffsets[i]) { mfem_error("Size of Blocks don't match in BlockVector::operator="); } Vector::operator=(original.GetData()); return *this; } BlockVector & BlockVector::operator=(double val) { Vector::operator=(val); return *this; } //! Destructor BlockVector::~BlockVector() { delete [] blocks; } void BlockVector::GetBlockView(int i, Vector & blockView) { blockView.NewDataAndSize(data+blockOffsets[i], blockOffsets[i+1]-blockOffsets[i]); } } <|endoftext|>
<commit_before>//----------------------------------------------------------- // // Copyright (C) 2015 by the deal2lkit authors // // This file is part of the deal2lkit library. // // The deal2lkit library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal2lkit distribution. // //----------------------------------------------------------- #include <deal2lkit/sundials_interface.h> #include <deal2lkit/imex_stepper.h> #ifdef D2K_WITH_SUNDIALS #include <deal.II/base/utilities.h> #include <deal.II/lac/block_vector.h> #ifdef DEAL_II_WITH_TRILINOS #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/lac/trilinos_parallel_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #endif #include <deal.II/base/utilities.h> #include <iostream> #include <iomanip> #ifdef DEAL_II_WITH_MPI #include <nvector/nvector_parallel.h> #endif using namespace dealii; D2K_NAMESPACE_OPEN template <typename VEC> IMEXStepper<VEC>::IMEXStepper(SundialsInterface<VEC> &interface, const double &step_size, const double &initial_time, const double &final_time) : ParameterAcceptor("IMEX Parameters"), interface(interface), step_size(step_size), initial_time(initial_time), final_time(final_time) { abs_tol = 1e-6; rel_tol = 1e-8; output_period = 1; max_outer_non_linear_iterations = 5; max_inner_non_linear_iterations = 3; update_jacobian_continuously = true; } template <typename VEC> void IMEXStepper<VEC>::declare_parameters(ParameterHandler &prm) { add_parameter(prm, &step_size, "Initial step size", "1e-4", Patterns::Double()); add_parameter(prm, &abs_tol, "Absolute error tolerance", std::to_string(abs_tol), Patterns::Double()); add_parameter(prm, &rel_tol, "Relative error tolerance", std::to_string(rel_tol), Patterns::Double()); add_parameter(prm, &initial_time, "Initial time", std::to_string(initial_time), Patterns::Double()); add_parameter(prm, &final_time, "Final time", std::to_string(final_time), Patterns::Double()); add_parameter(prm, &output_period, "Intervals between outputs", std::to_string(output_period), Patterns::Integer()); add_parameter(prm, &max_outer_non_linear_iterations, "Maximum number of outer nonlinear iterations", std::to_string(max_outer_non_linear_iterations), Patterns::Integer(), "At each outer iteration the Jacobian is updated if it is set that the \n" "Jacobian is continuously updated and a cycle of inner iterations is \n" "perfomed."); add_parameter(prm, &max_inner_non_linear_iterations, "Maximum number of inner nonlinear iterations", std::to_string(max_inner_non_linear_iterations), Patterns::Integer(), "At each inner iteration the Jacobian is NOT updated."); add_parameter(prm, &newton_alpha, "Newton relaxation parameter", std::to_string(newton_alpha), Patterns::Double()); add_parameter(prm, &update_jacobian_continuously, "Update continuously Jacobian", std::to_string(update_jacobian_continuously), Patterns::Bool()); } template <typename VEC> unsigned int IMEXStepper<VEC>::start_ode(VEC &solution) { AssertDimension(solution.size(), interface.n_dofs()); unsigned int step_number = 0; int status; // The solution is stored in // solution. Here we take only a // view of it. auto previous_solution = interface.create_new_vector(); auto solution_dot = interface.create_new_vector(); auto solution_update = interface.create_new_vector(); auto residual = interface.create_new_vector(); auto rhs = interface.create_new_vector(); *previous_solution = solution; double t = initial_time; const double alpha = 1./step_size; interface.output_step( 0, solution, *solution_dot, 0, step_size); // Initialization of the state of the boolean variable // responsible to keep track of the requirement that the // system's Jacobian be updated. bool update_Jacobian = true; // The overall cycle over time begins here. for (; t<=final_time; t+= step_size, ++step_number) { // Implicit Euler scheme. *solution_dot = solution; *solution_dot -= *previous_solution; *solution_dot *= alpha; // Initialization of two counters for the monitoring of // progress of the nonlinear solver. unsigned int inner_iter = 0; unsigned int outer_iter = 0; unsigned int nonlin_iter = 0; interface.residual(t, solution, *solution_dot, *residual); double res_norm = residual->l2_norm(); // The nonlinear solver iteration cycle begins here. while (outer_iter < max_outer_non_linear_iterations && res_norm > abs_tol) { outer_iter += 1; if (update_Jacobian == true) { interface.setup_jacobian(t, solution, *solution_dot, *residual, alpha); } inner_iter = 0; while (inner_iter < max_inner_non_linear_iterations && res_norm > abs_tol) { inner_iter += 1; *rhs = *residual; *rhs *= -1.0; interface.solve_jacobian_system(t, solution, *solution_dot, *residual, alpha, *rhs, *solution_update); solution.sadd(1.0, newton_alpha, *solution_update); // Implicit Euler scheme. *solution_dot = solution; *solution_dot -= *previous_solution; *solution_dot *= alpha; interface.residual(t, solution, *solution_dot, *residual); res_norm = solution_update->l2_norm(); } nonlin_iter += inner_iter; if (std::fabs(res_norm) < abs_tol) { std::printf(" %-16.3e (converged in %d iterations)\n\n", res_norm, nonlin_iter); break; // Break of the while cycle ... after this a time advancement happens. } else if (outer_iter == max_outer_non_linear_iterations) { std::printf(" %-16.3e (not converged in %d iterations)\n\n", res_norm, nonlin_iter); AssertThrow(false, ExcMessage ("No convergence in nonlinear solver")); } } // The nonlinear solver iteration cycle ends here. *previous_solution = solution; interface.output_step(t, solution, *solution_dot, step_number, step_size); update_Jacobian = update_jacobian_continuously; } // End of the cycle over time. return 0; } D2K_NAMESPACE_CLOSE template class deal2lkit::IMEXStepper<BlockVector<double> >; #ifdef DEAL_II_WITH_MPI #ifdef DEAL_II_WITH_TRILINOS template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::Vector>; template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::BlockVector>; #endif #endif #endif <commit_msg>removed unused variable<commit_after>//----------------------------------------------------------- // // Copyright (C) 2015 by the deal2lkit authors // // This file is part of the deal2lkit library. // // The deal2lkit library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal2lkit distribution. // //----------------------------------------------------------- #include <deal2lkit/sundials_interface.h> #include <deal2lkit/imex_stepper.h> #ifdef D2K_WITH_SUNDIALS #include <deal.II/base/utilities.h> #include <deal.II/lac/block_vector.h> #ifdef DEAL_II_WITH_TRILINOS #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/lac/trilinos_parallel_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #endif #include <deal.II/base/utilities.h> #include <iostream> #include <iomanip> #ifdef DEAL_II_WITH_MPI #include <nvector/nvector_parallel.h> #endif using namespace dealii; D2K_NAMESPACE_OPEN template <typename VEC> IMEXStepper<VEC>::IMEXStepper(SundialsInterface<VEC> &interface, const double &step_size, const double &initial_time, const double &final_time) : ParameterAcceptor("IMEX Parameters"), interface(interface), step_size(step_size), initial_time(initial_time), final_time(final_time) { abs_tol = 1e-6; rel_tol = 1e-8; output_period = 1; max_outer_non_linear_iterations = 5; max_inner_non_linear_iterations = 3; update_jacobian_continuously = true; } template <typename VEC> void IMEXStepper<VEC>::declare_parameters(ParameterHandler &prm) { add_parameter(prm, &step_size, "Initial step size", "1e-4", Patterns::Double()); add_parameter(prm, &abs_tol, "Absolute error tolerance", std::to_string(abs_tol), Patterns::Double()); add_parameter(prm, &rel_tol, "Relative error tolerance", std::to_string(rel_tol), Patterns::Double()); add_parameter(prm, &initial_time, "Initial time", std::to_string(initial_time), Patterns::Double()); add_parameter(prm, &final_time, "Final time", std::to_string(final_time), Patterns::Double()); add_parameter(prm, &output_period, "Intervals between outputs", std::to_string(output_period), Patterns::Integer()); add_parameter(prm, &max_outer_non_linear_iterations, "Maximum number of outer nonlinear iterations", std::to_string(max_outer_non_linear_iterations), Patterns::Integer(), "At each outer iteration the Jacobian is updated if it is set that the \n" "Jacobian is continuously updated and a cycle of inner iterations is \n" "perfomed."); add_parameter(prm, &max_inner_non_linear_iterations, "Maximum number of inner nonlinear iterations", std::to_string(max_inner_non_linear_iterations), Patterns::Integer(), "At each inner iteration the Jacobian is NOT updated."); add_parameter(prm, &newton_alpha, "Newton relaxation parameter", std::to_string(newton_alpha), Patterns::Double()); add_parameter(prm, &update_jacobian_continuously, "Update continuously Jacobian", std::to_string(update_jacobian_continuously), Patterns::Bool()); } template <typename VEC> unsigned int IMEXStepper<VEC>::start_ode(VEC &solution) { AssertDimension(solution.size(), interface.n_dofs()); unsigned int step_number = 0; auto previous_solution = interface.create_new_vector(); auto solution_dot = interface.create_new_vector(); auto solution_update = interface.create_new_vector(); auto residual = interface.create_new_vector(); auto rhs = interface.create_new_vector(); *previous_solution = solution; double t = initial_time; const double alpha = 1./step_size; interface.output_step( 0, solution, *solution_dot, 0, step_size); // Initialization of the state of the boolean variable // responsible to keep track of the requirement that the // system's Jacobian be updated. bool update_Jacobian = true; // The overall cycle over time begins here. for (; t<=final_time; t+= step_size, ++step_number) { // Implicit Euler scheme. *solution_dot = solution; *solution_dot -= *previous_solution; *solution_dot *= alpha; // Initialization of two counters for the monitoring of // progress of the nonlinear solver. unsigned int inner_iter = 0; unsigned int outer_iter = 0; unsigned int nonlin_iter = 0; interface.residual(t, solution, *solution_dot, *residual); double res_norm = residual->l2_norm(); // The nonlinear solver iteration cycle begins here. while (outer_iter < max_outer_non_linear_iterations && res_norm > abs_tol) { outer_iter += 1; if (update_Jacobian == true) { interface.setup_jacobian(t, solution, *solution_dot, *residual, alpha); } inner_iter = 0; while (inner_iter < max_inner_non_linear_iterations && res_norm > abs_tol) { inner_iter += 1; *rhs = *residual; *rhs *= -1.0; interface.solve_jacobian_system(t, solution, *solution_dot, *residual, alpha, *rhs, *solution_update); solution.sadd(1.0, newton_alpha, *solution_update); // Implicit Euler scheme. *solution_dot = solution; *solution_dot -= *previous_solution; *solution_dot *= alpha; interface.residual(t, solution, *solution_dot, *residual); res_norm = solution_update->l2_norm(); } nonlin_iter += inner_iter; if (std::fabs(res_norm) < abs_tol) { std::printf(" %-16.3e (converged in %d iterations)\n\n", res_norm, nonlin_iter); break; // Break of the while cycle ... after this a time advancement happens. } else if (outer_iter == max_outer_non_linear_iterations) { std::printf(" %-16.3e (not converged in %d iterations)\n\n", res_norm, nonlin_iter); AssertThrow(false, ExcMessage ("No convergence in nonlinear solver")); } } // The nonlinear solver iteration cycle ends here. *previous_solution = solution; interface.output_step(t, solution, *solution_dot, step_number, step_size); update_Jacobian = update_jacobian_continuously; } // End of the cycle over time. return 0; } D2K_NAMESPACE_CLOSE template class deal2lkit::IMEXStepper<BlockVector<double> >; #ifdef DEAL_II_WITH_MPI #ifdef DEAL_II_WITH_TRILINOS template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::Vector>; template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::BlockVector>; #endif #endif #endif <|endoftext|>
<commit_before>#ifndef ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__ #define ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__ #include <aleph/utilities/String.hh> #include <aleph/topology/filtrations/Data.hh> #include <algorithm> #include <fstream> #include <istream> #include <string> #include <unordered_map> #include <vector> #include <cmath> namespace aleph { namespace topology { namespace io { /** @class AdjacencyMatrixReader @brief Reads square adjacency matrices in text format This reader class is meant to load square adjacency matrices (square) in text format. Entry (i,j) in the matrix contains the edge weight of the (unique) edge connecting nodes i and j. Depending on the configuration of the class, cells with a pre-defined weight (usually zero) are taken to indicate missing edges. The number of rows and columns must not vary over the file. An *empty* line is permitted, though. Likewise, lines starting with `#` will just be ignored. An example of a 3-by-3 matrix follows: \code 0 1 2 3 4 5 2 1 7 \endcode All simplicial complexes created by this class will be reported in filtration order, following the detected weights. This class offers the option to supply an *optional* functor for modifying the weights of the matrix. This can be useful when edge weights are supposed to be negated, for example. */ class AdjacencyMatrixReader { public: enum class VertexWeightAssignmentStrategy { AssignGlobalMinimum, // assigns the global minimum weight AssignZero // assigns zero }; /** Reads a simplicial complex from a file. @param filename Input filename @param K Simplicial complex */ template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( filename, K, // Use the identity functor so that weights are not changed at all // and just stored as-is. [] ( DataType /* a */, DataType /* b */, DataType x ) { return x; } ); } template <class SimplicialComplex, class Functor> void operator()( const std::string& filename, SimplicialComplex& K, Functor f ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K, f ); } /** @overload operator()( const std::string&, SimplicialComplex& ) */ template <class SimplicialComplex, class Functor> void operator()( std::istream& in, SimplicialComplex& K, Functor f ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; auto position = in.tellg(); std::size_t n = 0; // An 'unrolled' version of all edge weights that can be read from // the file. They are supposed to correspond to a matrix with some // number of columns and some number of rows. std::vector<DataType> values; using namespace aleph::utilities; { std::string line; while( std::getline( in, line ) ) { // Skip empty lines and comments as promised if( line.empty() || line.front() == '#' ) continue; ++n; } in.clear(); in.seekg( position ); } // FIXME: this will not work in case comments are part of the file. // Drat---should probably rewrite it. std::copy( std::istream_iterator<DataType>( in ), std::istream_iterator<DataType>(), std::back_inserter( values ) ); // We cannot fill an empty simplicial complex. It might be useful to // throw an error here, though. if( values.empty() ) return; _dimension = n; if( values.size() != _dimension * _dimension ) throw std::runtime_error( "Format error: number of columns must not vary" ); std::vector<Simplex> simplices; // First part of that equation reserves $n$ nodes, where $n$ is the // dimension of the matrix, followed by at most $n^2$ edges. Notice // that this assumes that *all* edges are defined. simplices.reserve( _dimension + ( _dimension * _dimension ) ); DataType minWeight = DataType(); DataType maxWeight = DataType(); { auto minmax = std::minmax_element( values.begin(), values.end() ); minWeight = *minmax.first; maxWeight = *minmax.second; } // Edges ----------------------------------------------------------- // // Create the edges first and update information about their weights // along with them. for( std::size_t y = 0; y < _dimension; y++ ) { // The way this loop is set up avoids the calculation of // self-edges. Also, it looks at weights from a *single* // direction only. Essentially, half of the data set may // not be considered here. for( std::size_t x = y + 1; x < _dimension; x++ ) { auto i = static_cast<VertexType>( _dimension * y + x ); auto w = values[i]; // Map matrix indices to the corresponding vertex indices as // outlined above. auto u = VertexType(y); auto v = VertexType(x + _dimension); if( _ignoreNaNs && std::isnan( w ) ) continue; if( _ignoreZeroWeights && w == DataType() ) continue; // Apply the client-specified functor here and store the // resulting simplex in the complex. simplices.push_back( Simplex( {u,v}, f( maxWeight, minWeight, w ) ) ); } } // Vertices -------------------------------------------------------- // // Create a vertex for every node in the input data. This will use // the minimum weight detected in the file. for( std::size_t i = 0; i < _dimension; i++ ) { DataType weight = DataType(); if( _vertexWeightAssignmentStrategy == VertexWeightAssignmentStrategy::AssignGlobalMinimum ) { // This weight selection strategy requires applying the functor // because the weight might be anything, whereas the zero-based // initialization uses a *fixed* weight. weight = f( maxWeight, minWeight, minWeight ); } else if( _vertexWeightAssignmentStrategy == VertexWeightAssignmentStrategy::AssignZero ) weight = DataType(); else throw std::runtime_error( "Unknown vertex weight assignment strategy" ); simplices.push_back( Simplex( VertexType( i ), weight ) ); } K = SimplicialComplex( simplices.begin(), simplices.end() ); // Establish filtration order based on weights. There does not seem // to be much of a point to make this configurable; the edge weight // is a given property of the data. K.sort( filtrations::Data<Simplex>() ); } /** @returns Dimension of matrix that was read last */ std::size_t dimension() const noexcept { return _dimension; } void setIgnoreNaNs( bool value = true ) noexcept { _ignoreNaNs = value; } void setIgnoreZeroWeights( bool value = true ) noexcept { _ignoreZeroWeights = value; } void setVertexWeightAssignmentStrategy( VertexWeightAssignmentStrategy strategy ) noexcept { _vertexWeightAssignmentStrategy = strategy; } private: // Dimension of the matrix that was read last by this reader; this // will only be set if the matrix is actually square. std::size_t _dimension = 0; // If set, NaNs are ignored by the reader and treated as a missing // edge of the graph. bool _ignoreNaNs = false; // If set, zero weights are ignored by the reader and treated as // a missing edge of the graph. // a missing edge. bool _ignoreZeroWeights = false; // Strategy/policy for assigning vertex weights. Can be either one of // the options outlined in the enumeration class above. By default, a // global minimum weight is identified and assigned. VertexWeightAssignmentStrategy _vertexWeightAssignmentStrategy = VertexWeightAssignmentStrategy::AssignGlobalMinimum; }; } // namespace io } // namespace topology } // namespace aleph #endif <commit_msg>Fixed missing overload for adjacency matrix reader<commit_after>#ifndef ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__ #define ALEPH_TOPOLOGY_IO_ADJACENCY_MATRIX_HH__ #include <aleph/utilities/String.hh> #include <aleph/topology/filtrations/Data.hh> #include <algorithm> #include <fstream> #include <istream> #include <string> #include <unordered_map> #include <vector> #include <cmath> namespace aleph { namespace topology { namespace io { /** @class AdjacencyMatrixReader @brief Reads square adjacency matrices in text format This reader class is meant to load square adjacency matrices (square) in text format. Entry (i,j) in the matrix contains the edge weight of the (unique) edge connecting nodes i and j. Depending on the configuration of the class, cells with a pre-defined weight (usually zero) are taken to indicate missing edges. The number of rows and columns must not vary over the file. An *empty* line is permitted, though. Likewise, lines starting with `#` will just be ignored. An example of a 3-by-3 matrix follows: \code 0 1 2 3 4 5 2 1 7 \endcode All simplicial complexes created by this class will be reported in filtration order, following the detected weights. This class offers the option to supply an *optional* functor for modifying the weights of the matrix. This can be useful when edge weights are supposed to be negated, for example. */ class AdjacencyMatrixReader { public: enum class VertexWeightAssignmentStrategy { AssignGlobalMinimum, // assigns the global minimum weight AssignZero // assigns zero }; /** Reads a simplicial complex from a file. @param filename Input filename @param K Simplicial complex */ template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( filename, K, // Use the identity functor so that weights are not changed at all // and just stored as-is. [] ( DataType /* a */, DataType /* b */, DataType x ) { return x; } ); } template <class SimplicialComplex, class Functor> void operator()( const std::string& filename, SimplicialComplex& K, Functor f ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K, f ); } /** @overload operator()( const std::string&, SimplicialComplex& ) */ template <class SimplicialComplex> void operator()( std::istream& in, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( in, K, // Use the identity functor so that weights are not changed at all // and just stored as-is. [] ( DataType /* a */, DataType /* b */, DataType x ) { return x; } ); } /** @overload operator()( const std::string&, SimplicialComplex& ) */ template <class SimplicialComplex, class Functor> void operator()( std::istream& in, SimplicialComplex& K, Functor f ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; auto position = in.tellg(); std::size_t n = 0; // An 'unrolled' version of all edge weights that can be read from // the file. They are supposed to correspond to a matrix with some // number of columns and some number of rows. std::vector<DataType> values; using namespace aleph::utilities; { std::string line; while( std::getline( in, line ) ) { // Skip empty lines and comments as promised if( line.empty() || line.front() == '#' ) continue; ++n; } in.clear(); in.seekg( position ); } // FIXME: this will not work in case comments are part of the file. // Drat---should probably rewrite it. std::copy( std::istream_iterator<DataType>( in ), std::istream_iterator<DataType>(), std::back_inserter( values ) ); // We cannot fill an empty simplicial complex. It might be useful to // throw an error here, though. if( values.empty() ) return; _dimension = n; if( values.size() != _dimension * _dimension ) throw std::runtime_error( "Format error: number of columns must not vary" ); std::vector<Simplex> simplices; // First part of that equation reserves $n$ nodes, where $n$ is the // dimension of the matrix, followed by at most $n^2$ edges. Notice // that this assumes that *all* edges are defined. simplices.reserve( _dimension + ( _dimension * _dimension ) ); DataType minWeight = DataType(); DataType maxWeight = DataType(); { auto minmax = std::minmax_element( values.begin(), values.end() ); minWeight = *minmax.first; maxWeight = *minmax.second; } // Edges ----------------------------------------------------------- // // Create the edges first and update information about their weights // along with them. for( std::size_t y = 0; y < _dimension; y++ ) { // The way this loop is set up avoids the calculation of // self-edges. Also, it looks at weights from a *single* // direction only. Essentially, half of the data set may // not be considered here. for( std::size_t x = y + 1; x < _dimension; x++ ) { auto i = static_cast<VertexType>( _dimension * y + x ); auto w = values[i]; // Map matrix indices to the corresponding vertex indices as // outlined above. auto u = VertexType(y); auto v = VertexType(x + _dimension); if( _ignoreNaNs && std::isnan( w ) ) continue; if( _ignoreZeroWeights && w == DataType() ) continue; // Apply the client-specified functor here and store the // resulting simplex in the complex. simplices.push_back( Simplex( {u,v}, f( maxWeight, minWeight, w ) ) ); } } // Vertices -------------------------------------------------------- // // Create a vertex for every node in the input data. This will use // the minimum weight detected in the file. for( std::size_t i = 0; i < _dimension; i++ ) { DataType weight = DataType(); if( _vertexWeightAssignmentStrategy == VertexWeightAssignmentStrategy::AssignGlobalMinimum ) { // This weight selection strategy requires applying the functor // because the weight might be anything, whereas the zero-based // initialization uses a *fixed* weight. weight = f( maxWeight, minWeight, minWeight ); } else if( _vertexWeightAssignmentStrategy == VertexWeightAssignmentStrategy::AssignZero ) weight = DataType(); else throw std::runtime_error( "Unknown vertex weight assignment strategy" ); simplices.push_back( Simplex( VertexType( i ), weight ) ); } K = SimplicialComplex( simplices.begin(), simplices.end() ); // Establish filtration order based on weights. There does not seem // to be much of a point to make this configurable; the edge weight // is a given property of the data. K.sort( filtrations::Data<Simplex>() ); } /** @returns Dimension of matrix that was read last */ std::size_t dimension() const noexcept { return _dimension; } void setIgnoreNaNs( bool value = true ) noexcept { _ignoreNaNs = value; } void setIgnoreZeroWeights( bool value = true ) noexcept { _ignoreZeroWeights = value; } void setVertexWeightAssignmentStrategy( VertexWeightAssignmentStrategy strategy ) noexcept { _vertexWeightAssignmentStrategy = strategy; } private: // Dimension of the matrix that was read last by this reader; this // will only be set if the matrix is actually square. std::size_t _dimension = 0; // If set, NaNs are ignored by the reader and treated as a missing // edge of the graph. bool _ignoreNaNs = false; // If set, zero weights are ignored by the reader and treated as // a missing edge of the graph. // a missing edge. bool _ignoreZeroWeights = false; // Strategy/policy for assigning vertex weights. Can be either one of // the options outlined in the enumeration class above. By default, a // global minimum weight is identified and assigned. VertexWeightAssignmentStrategy _vertexWeightAssignmentStrategy = VertexWeightAssignmentStrategy::AssignGlobalMinimum; }; } // namespace io } // namespace topology } // namespace aleph #endif <|endoftext|>