text
stringlengths
54
60.6k
<commit_before>/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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 "LIEF/BinaryStream/BinaryStream.hpp" #include "LIEF/DWARF/enums.hpp" #include "LIEF/utils.hpp" #include "third-party/utfcpp.hpp" #include <mbedtls/platform.h> #include <mbedtls/asn1.h> #include <mbedtls/error.h> #include <mbedtls/oid.h> #include <mbedtls/x509_crt.h> #include "intmem.h" #include <iomanip> #include <sstream> #include <algorithm> #include <iostream> #define TMPL_DECL(T) template T BinaryStream::swap_endian<T>(T u) namespace LIEF { BinaryStream::~BinaryStream() = default; BinaryStream::BinaryStream() = default; template<typename T> T BinaryStream::swap_endian(T u) { return intmem::bswap(u); } template<> char16_t BinaryStream::swap_endian<char16_t>(char16_t u) { return intmem::bswap(static_cast<uint16_t>(u)); } template<> char BinaryStream::swap_endian<char>(char u) { return intmem::bswap(static_cast<uint8_t>(u)); } TMPL_DECL(uint8_t); TMPL_DECL(uint16_t); TMPL_DECL(uint32_t); TMPL_DECL(uint64_t); TMPL_DECL(int8_t); TMPL_DECL(int16_t); TMPL_DECL(int32_t); TMPL_DECL(int64_t); void BinaryStream::setpos(size_t pos) const { pos_ = pos; } void BinaryStream::increment_pos(size_t value) const { pos_ += value; } BinaryStream::operator bool() const { return pos_ < size(); } size_t BinaryStream::pos() const { return pos_; } result<int64_t> BinaryStream::read_dwarf_encoded(uint8_t encoding) const { const auto encodevalue = static_cast<LIEF::DWARF::EH_ENCODING>(encoding & 0x0F); switch (encodevalue) { case LIEF::DWARF::EH_ENCODING::ULEB128: { return read_uleb128(); } case LIEF::DWARF::EH_ENCODING::SDATA2: case LIEF::DWARF::EH_ENCODING::UDATA2: { return read<int16_t>(); } case LIEF::DWARF::EH_ENCODING::SDATA4: case LIEF::DWARF::EH_ENCODING::UDATA4: { return read<int32_t>(); } case LIEF::DWARF::EH_ENCODING::SDATA8: case LIEF::DWARF::EH_ENCODING::UDATA8: { return read<int64_t>(); } case LIEF::DWARF::EH_ENCODING::SLEB128: { return read_sleb128(); } default: { return 0; } } } result<uint64_t> BinaryStream::read_uleb128() const { uint64_t value = 0; unsigned shift = 0; result<uint8_t> byte_read; do { byte_read = read<uint8_t>(); if (!byte_read) { return make_error_code(lief_errors::read_error); } value += static_cast<uint64_t>(*byte_read & 0x7f) << shift; shift += 7; } while (byte_read && *byte_read >= 128); return value; } result<uint64_t> BinaryStream::read_sleb128() const { int64_t value = 0; unsigned shift = 0; result<uint8_t> byte_read; do { byte_read = read<uint8_t>(); if (!byte_read) { return make_error_code(lief_errors::read_error); } value += static_cast<int64_t>(*byte_read & 0x7f) << shift; shift += 7; } while (byte_read && *byte_read >= 128); // Sign extend if ((*byte_read & 0x40) != 0) { value |= -1llu << shift; } return value; } result<std::string> BinaryStream::read_string(size_t maxsize) const { result<std::string> str = peek_string(maxsize); if (!str) { return str.error(); } increment_pos(str->size() + 1); // +1 for'\0' return str; } result<std::string> BinaryStream::peek_string(size_t maxsize) const { std::string str_result; str_result.reserve(10); result<char> c = '\0'; size_t off = pos(); if (!can_read<char>()) { return str_result.c_str(); } size_t count = 0; do { c = peek<char>(off); if (!c) { return c.error(); } off += sizeof(char); str_result.push_back(*c); ++count; } while (count < maxsize && c && *c != '\0' && off < size()); str_result.back() = '\0'; return str_result.c_str(); } result<std::string> BinaryStream::peek_string_at(size_t offset, size_t maxsize) const { size_t saved_offset = pos(); setpos(offset); result<std::string> tmp = peek_string(maxsize); setpos(saved_offset); return tmp; } result<std::u16string> BinaryStream::read_u16string() const { result<std::u16string> str = peek_u16string(); if (!str) { return str.error(); } increment_pos((str->size() + 1) * sizeof(uint16_t)); // +1 for'\0' return str.value(); } result<std::u16string> BinaryStream::peek_u16string() const { std::u16string u16_str; u16_str.reserve(10); result<char16_t> c = '\0'; size_t off = pos(); if (!can_read<char16_t>()) { return u16_str; } size_t count = 0; do { c = peek<char16_t>(off); if (!c) { return c.error(); } off += sizeof(char16_t); u16_str.push_back(*c); ++count; } while (c && *c != 0 && pos() < size()); u16_str.back() = '\0'; return u16_str.c_str(); } result<std::u16string> BinaryStream::read_u16string(size_t length) const { result<std::u16string> str = peek_u16string(length); increment_pos(length * sizeof(uint16_t)); // +1 for'\0' return str; } result<std::u16string> BinaryStream::peek_u16string(size_t length) const { if (length == static_cast<size_t>(-1u)) { return peek_u16string(); } std::unique_ptr<char16_t[]> raw = peek_conv_array<char16_t>(pos(), length); if (raw == nullptr) { return std::u16string(); } return std::u16string{raw.get(), length}; } result<std::u16string> BinaryStream::peek_u16string_at(size_t offset, size_t length) const { size_t saved_offset = pos(); setpos(offset); result<std::u16string> tmp = peek_u16string(length); setpos(saved_offset); return tmp; } size_t BinaryStream::align(size_t align_on) const { if (align_on == 0 || (pos() % align_on) == 0) { return 0; } size_t padding = align_on - (pos() % align_on); increment_pos(padding); return padding; } result<std::string> BinaryStream::read_mutf8(size_t maxsize) const { std::u32string u32str; for (size_t i = 0; i < maxsize; ++i) { result<uint8_t> res_a = read<char>(); if (!res_a) { return res_a.error(); } uint8_t a = *res_a; if (static_cast<uint8_t>(a) < 0x80) { if (a == 0) { break; } u32str.push_back(a); } else if ((a & 0xe0) == 0xc0) { result<uint8_t> res_b = read<int8_t>(); if (!res_b) { return res_b.error(); } uint8_t b = *res_b & 0xFF; if ((b & 0xC0) != 0x80) { break; } u32str.push_back(static_cast<char32_t>((((a & 0x1F) << 6) | (b & 0x3F)))); } else if ((a & 0xf0) == 0xe0) { result<uint8_t> res_b = read<uint8_t>(); result<uint8_t> res_c = read<uint8_t>(); if (!res_b) { return res_b.error(); } if (!res_c) { return res_c.error(); } uint8_t b = *res_b; uint8_t c = *res_c; if (((b & 0xC0) != 0x80) || ((c & 0xC0) != 0x80)) { break; } u32str.push_back(static_cast<char32_t>(((a & 0x1F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))); } else { break; } } std::string u8str; std::replace_if(std::begin(u32str), std::end(u32str), [] (const char32_t c) { return !utf8::internal::is_code_point_valid(c); }, '.'); utf8::utf32to8(std::begin(u32str), std::end(u32str), std::back_inserter(u8str)); std::string u8str_clean; for (const char c : u8str) { if (c != -1) { u8str_clean.push_back(c); } else { u8str_clean += "\\xFF"; } } return u8str_clean; } void BinaryStream::set_endian_swap(bool swap) { endian_swap_ = swap; } result<size_t> BinaryStream::asn1_read_tag(int) { return make_error_code(lief_errors::not_implemented); } result<size_t> BinaryStream::asn1_read_len() { return make_error_code(lief_errors::not_implemented); } result<std::string> BinaryStream::asn1_read_alg() { return make_error_code(lief_errors::not_implemented); } result<std::string> BinaryStream::asn1_read_oid() { return make_error_code(lief_errors::not_implemented); } result<int32_t> BinaryStream::asn1_read_int() { return make_error_code(lief_errors::not_implemented); } result<std::vector<uint8_t>> BinaryStream::asn1_read_bitstring() { return make_error_code(lief_errors::not_implemented); } result<std::vector<uint8_t>> BinaryStream::asn1_read_octet_string() { return make_error_code(lief_errors::not_implemented); } result<std::unique_ptr<mbedtls_x509_crt>> BinaryStream::asn1_read_cert() { return make_error_code(lief_errors::not_implemented); } result<std::string> BinaryStream::x509_read_names() { return make_error_code(lief_errors::not_implemented); } result<std::vector<uint8_t>> BinaryStream::x509_read_serial() { return make_error_code(lief_errors::not_implemented); } result<std::unique_ptr<mbedtls_x509_time>> BinaryStream::x509_read_time() { return make_error_code(lief_errors::not_implemented); } } <commit_msg>BinaryStream improvment<commit_after>/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * 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 "LIEF/BinaryStream/BinaryStream.hpp" #include "LIEF/DWARF/enums.hpp" #include "LIEF/utils.hpp" #include "third-party/utfcpp.hpp" #include <mbedtls/platform.h> #include <mbedtls/asn1.h> #include <mbedtls/error.h> #include <mbedtls/oid.h> #include <mbedtls/x509_crt.h> #include "intmem.h" #include <iomanip> #include <sstream> #include <algorithm> #include <iostream> #define TMPL_DECL(T) template T BinaryStream::swap_endian<T>(T u) namespace LIEF { BinaryStream::~BinaryStream() = default; BinaryStream::BinaryStream() = default; template<typename T> T BinaryStream::swap_endian(T u) { return intmem::bswap(u); } template<> char16_t BinaryStream::swap_endian<char16_t>(char16_t u) { return intmem::bswap(static_cast<uint16_t>(u)); } template<> char BinaryStream::swap_endian<char>(char u) { return intmem::bswap(static_cast<uint8_t>(u)); } TMPL_DECL(uint8_t); TMPL_DECL(uint16_t); TMPL_DECL(uint32_t); TMPL_DECL(uint64_t); TMPL_DECL(int8_t); TMPL_DECL(int16_t); TMPL_DECL(int32_t); TMPL_DECL(int64_t); void BinaryStream::setpos(size_t pos) const { pos_ = pos; } void BinaryStream::increment_pos(size_t value) const { pos_ += value; } BinaryStream::operator bool() const { return pos_ < size(); } size_t BinaryStream::pos() const { return pos_; } result<int64_t> BinaryStream::read_dwarf_encoded(uint8_t encoding) const { const auto encodevalue = static_cast<LIEF::DWARF::EH_ENCODING>(encoding & 0x0F); switch (encodevalue) { case LIEF::DWARF::EH_ENCODING::ULEB128: { return read_uleb128(); } case LIEF::DWARF::EH_ENCODING::SDATA2: case LIEF::DWARF::EH_ENCODING::UDATA2: { return read<int16_t>(); } case LIEF::DWARF::EH_ENCODING::SDATA4: case LIEF::DWARF::EH_ENCODING::UDATA4: { return read<int32_t>(); } case LIEF::DWARF::EH_ENCODING::SDATA8: case LIEF::DWARF::EH_ENCODING::UDATA8: { return read<int64_t>(); } case LIEF::DWARF::EH_ENCODING::SLEB128: { return read_sleb128(); } default: { return 0; } } } result<uint64_t> BinaryStream::read_uleb128() const { uint64_t value = 0; unsigned shift = 0; result<uint8_t> byte_read; do { byte_read = read<uint8_t>(); if (!byte_read) { return make_error_code(lief_errors::read_error); } value += static_cast<uint64_t>(*byte_read & 0x7f) << shift; shift += 7; } while (byte_read && *byte_read >= 128); return value; } result<uint64_t> BinaryStream::read_sleb128() const { int64_t value = 0; unsigned shift = 0; result<uint8_t> byte_read; do { byte_read = read<uint8_t>(); if (!byte_read) { return make_error_code(lief_errors::read_error); } value += static_cast<int64_t>(*byte_read & 0x7f) << shift; shift += 7; } while (byte_read && *byte_read >= 128); // Sign extend if ((*byte_read & 0x40) != 0) { value |= -1llu << shift; } return value; } result<std::string> BinaryStream::read_string(size_t maxsize) const { result<std::string> str = peek_string(maxsize); if (!str) { return str.error(); } increment_pos(str->size() + 1); // +1 for'\0' return str; } result<std::string> BinaryStream::peek_string(size_t maxsize) const { std::string str_result; str_result.reserve(10); result<char> c = '\0'; size_t off = pos(); if (!can_read<char>()) { return str_result.c_str(); } size_t count = 0; do { c = peek<char>(off); if (!c) { return c.error(); } off += sizeof(char); str_result.push_back(*c); ++count; } while (count < maxsize && c && *c != '\0' && off < size()); str_result.back() = '\0'; return str_result.c_str(); } result<std::string> BinaryStream::peek_string_at(size_t offset, size_t maxsize) const { size_t saved_offset = pos(); setpos(offset); result<std::string> tmp = peek_string(maxsize); setpos(saved_offset); return tmp; } result<std::u16string> BinaryStream::read_u16string() const { result<std::u16string> str = peek_u16string(); if (!str) { return str.error(); } increment_pos((str->size() + 1) * sizeof(uint16_t)); // +1 for'\0' return str.value(); } result<std::u16string> BinaryStream::peek_u16string() const { std::u16string u16_str; u16_str.reserve(10); result<char16_t> c = '\0'; size_t off = pos(); if (!can_read<char16_t>()) { return u16_str; } size_t count = 0; do { c = peek<char16_t>(off); if (!c) { return c.error(); } off += sizeof(char16_t); u16_str.push_back(*c); ++count; } while (c && *c != 0 && off < size()); u16_str.back() = '\0'; return u16_str.c_str(); } result<std::u16string> BinaryStream::read_u16string(size_t length) const { result<std::u16string> str = peek_u16string(length); increment_pos(length * sizeof(uint16_t)); // +1 for'\0' return str; } result<std::u16string> BinaryStream::peek_u16string(size_t length) const { if (length == static_cast<size_t>(-1u)) { return peek_u16string(); } std::vector<char16_t> raw_u16str; raw_u16str.resize(length, 0); if (peek_in(raw_u16str.data(), pos(), length * sizeof(char16_t))) { if (endian_swap_) { for (char16_t& x : raw_u16str) { LIEF::Convert::swap_endian(&x); } } return std::u16string{std::begin(raw_u16str), std::end(raw_u16str)}; } return make_error_code(lief_errors::read_error); } result<std::u16string> BinaryStream::peek_u16string_at(size_t offset, size_t length) const { size_t saved_offset = pos(); setpos(offset); result<std::u16string> tmp = peek_u16string(length); setpos(saved_offset); return tmp; } size_t BinaryStream::align(size_t align_on) const { if (align_on == 0) { return 0; } const size_t r = pos() % align_on; if (r == 0) { return 0; } size_t padding = align_on - r; increment_pos(padding); return padding; } result<std::string> BinaryStream::read_mutf8(size_t maxsize) const { std::u32string u32str; for (size_t i = 0; i < maxsize; ++i) { result<uint8_t> res_a = read<char>(); if (!res_a) { return res_a.error(); } uint8_t a = *res_a; if (static_cast<uint8_t>(a) < 0x80) { if (a == 0) { break; } u32str.push_back(a); } else if ((a & 0xe0) == 0xc0) { result<uint8_t> res_b = read<int8_t>(); if (!res_b) { return res_b.error(); } uint8_t b = *res_b & 0xFF; if ((b & 0xC0) != 0x80) { break; } u32str.push_back(static_cast<char32_t>((((a & 0x1F) << 6) | (b & 0x3F)))); } else if ((a & 0xf0) == 0xe0) { result<uint8_t> res_b = read<uint8_t>(); result<uint8_t> res_c = read<uint8_t>(); if (!res_b) { return res_b.error(); } if (!res_c) { return res_c.error(); } uint8_t b = *res_b; uint8_t c = *res_c; if (((b & 0xC0) != 0x80) || ((c & 0xC0) != 0x80)) { break; } u32str.push_back(static_cast<char32_t>(((a & 0x1F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F))); } else { break; } } std::string u8str; std::replace_if(std::begin(u32str), std::end(u32str), [] (const char32_t c) { return !utf8::internal::is_code_point_valid(c); }, '.'); utf8::utf32to8(std::begin(u32str), std::end(u32str), std::back_inserter(u8str)); std::string u8str_clean; for (const char c : u8str) { if (c != -1) { u8str_clean.push_back(c); } else { u8str_clean += "\\xFF"; } } return u8str_clean; } void BinaryStream::set_endian_swap(bool swap) { endian_swap_ = swap; } result<size_t> BinaryStream::asn1_read_tag(int) { return make_error_code(lief_errors::not_implemented); } result<size_t> BinaryStream::asn1_read_len() { return make_error_code(lief_errors::not_implemented); } result<std::string> BinaryStream::asn1_read_alg() { return make_error_code(lief_errors::not_implemented); } result<std::string> BinaryStream::asn1_read_oid() { return make_error_code(lief_errors::not_implemented); } result<int32_t> BinaryStream::asn1_read_int() { return make_error_code(lief_errors::not_implemented); } result<std::vector<uint8_t>> BinaryStream::asn1_read_bitstring() { return make_error_code(lief_errors::not_implemented); } result<std::vector<uint8_t>> BinaryStream::asn1_read_octet_string() { return make_error_code(lief_errors::not_implemented); } result<std::unique_ptr<mbedtls_x509_crt>> BinaryStream::asn1_read_cert() { return make_error_code(lief_errors::not_implemented); } result<std::string> BinaryStream::x509_read_names() { return make_error_code(lief_errors::not_implemented); } result<std::vector<uint8_t>> BinaryStream::x509_read_serial() { return make_error_code(lief_errors::not_implemented); } result<std::unique_ptr<mbedtls_x509_time>> BinaryStream::x509_read_time() { return make_error_code(lief_errors::not_implemented); } } <|endoftext|>
<commit_before>// Filename: texturePool.cxx // Created by: drose (26Apr00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "texturePool.h" #include "config_gobj.h" #include "config_util.h" #include "config_express.h" #include "virtualFileSystem.h" TexturePool *TexturePool::_global_ptr = (TexturePool *)NULL; //////////////////////////////////////////////////////////////////// // Function: TexturePool::write // Access: Published, Static // Description: Lists the contents of the texture pool to the // indicated output stream. // For debugging. //////////////////////////////////////////////////////////////////// void TexturePool:: write(ostream &out) { get_ptr()->ns_list_contents(out); } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_has_texture // Access: Private // Description: The nonstatic implementation of has_texture(). //////////////////////////////////////////////////////////////////// bool TexturePool:: ns_has_texture(const Filename &orig_filename) { Filename filename(orig_filename); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()); vfs->resolve_filename(filename, get_model_path()); Textures::const_iterator ti; ti = _textures.find(filename); if (ti != _textures.end()) { // This texture was previously loaded. return true; } return false; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_texture // Access: Private // Description: The nonstatic implementation of load_texture(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_texture(const Filename &orig_filename, int primary_file_num_channels) { Filename filename(orig_filename); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); Textures::const_iterator ti; ti = _textures.find(filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading texture " << filename << "\n"; PT(Texture) tex = new Texture; if (!tex->read(filename, 0, primary_file_num_channels)) { // This texture was not found or could not be read. report_texture_unreadable(filename); return NULL; } // Set the original filename, before we searched along the path. tex->set_filename(orig_filename); _textures[filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_texture // Access: Private // Description: The nonstatic implementation of load_texture(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_texture(const Filename &orig_filename, const Filename &orig_alpha_filename, int primary_file_num_channels, int alpha_file_channel) { Filename filename(orig_filename); Filename alpha_filename(orig_alpha_filename); if (!_fake_texture_image.empty()) { return ns_load_texture(_fake_texture_image, primary_file_num_channels); } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); vfs->resolve_filename(alpha_filename, get_texture_path()) || vfs->resolve_filename(alpha_filename, get_model_path()); Textures::const_iterator ti; ti = _textures.find(filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading texture " << filename << " and alpha component " << alpha_filename << endl; PT(Texture) tex = new Texture; if (!tex->read(filename, alpha_filename, 0, primary_file_num_channels, alpha_file_channel)) { // This texture was not found or could not be read. report_texture_unreadable(filename); return NULL; } // Set the original filenames, before we searched along the path. tex->set_filename(orig_filename); tex->set_alpha_filename(orig_alpha_filename); _textures[filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_3d_texture // Access: Private // Description: The nonstatic implementation of load_3d_texture(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_3d_texture(const HashFilename &filename_template) { // Look up filename 0 on the model path. Filename filename = filename_template.get_filename_index(0); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); // Then, replace everything before the hash code with the directory // we've found. string hash = filename_template.get_hash_to_end(); HashFilename hash_filename(filename.substr(0, filename.length() - hash.length()) + hash); Textures::const_iterator ti; ti = _textures.find(hash_filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading 3-d texture " << hash_filename << "\n"; PT(Texture) tex = new Texture; tex->setup_3d_texture(); if (!tex->read_pages(hash_filename)) { // This texture was not found or could not be read. report_texture_unreadable(filename); } // Set the original filename, before we searched along the path. tex->set_filename(filename_template); _textures[hash_filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_cube_map // Access: Private // Description: The nonstatic implementation of load_cube_map(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_cube_map(const HashFilename &filename_template) { // Look up filename 0 on the model path. Filename filename = filename_template.get_filename_index(0); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); // Then, replace everything before the hash code with the directory // we've found. string hash = filename_template.get_hash_to_end(); HashFilename hash_filename(filename.substr(0, filename.length() - hash.length()) + hash); Textures::const_iterator ti; ti = _textures.find(hash_filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading cube map texture " << hash_filename << "\n"; PT(Texture) tex = new Texture; tex->setup_cube_map(); if (!tex->read_pages(hash_filename)) { // This texture was not found or could not be read. report_texture_unreadable(filename); } // Set the original filename, before we searched along the path. tex->set_filename(filename_template); _textures[hash_filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_get_normalization_cube_map // Access: Private // Description: The nonstatic implementation of get_normalization_cube_map(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_get_normalization_cube_map(int size) { if (_normalization_cube_map == (Texture *)NULL) { _normalization_cube_map = new Texture("normalization_cube_map"); } if (_normalization_cube_map->get_x_size() < size || _normalization_cube_map->get_texture_type() != Texture::TT_cube_map) { _normalization_cube_map->generate_normalization_cube_map(size); } return _normalization_cube_map; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_add_texture // Access: Private // Description: The nonstatic implementation of add_texture(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_add_texture(Texture *tex) { string filename = tex->get_filename(); if (filename.empty()) { gobj_cat.error() << "Attempt to call add_texture() on an unnamed texture.\n"; } // We blow away whatever texture was there previously, if any. _textures[filename] = tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_release_texture // Access: Private // Description: The nonstatic implementation of release_texture(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_release_texture(Texture *tex) { string filename = tex->get_filename(); Textures::iterator ti; ti = _textures.find(filename); if (ti != _textures.end() && (*ti).second == tex) { _textures.erase(ti); } } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_release_all_textures // Access: Private // Description: The nonstatic implementation of release_all_textures(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_release_all_textures() { _textures.clear(); _normalization_cube_map = NULL; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_garbage_collect // Access: Private // Description: The nonstatic implementation of garbage_collect(). //////////////////////////////////////////////////////////////////// int TexturePool:: ns_garbage_collect() { int num_released = 0; Textures new_set; Textures::iterator ti; for (ti = _textures.begin(); ti != _textures.end(); ++ti) { Texture *tex = (*ti).second; if (tex->get_ref_count() == 1) { if (gobj_cat.is_debug()) { gobj_cat.debug() << "Releasing " << (*ti).first << "\n"; } ++num_released; } else { new_set.insert(new_set.end(), *ti); } } _textures.swap(new_set); if (_normalization_cube_map->get_ref_count() == 1) { if (gobj_cat.is_debug()) { gobj_cat.debug() << "Releasing normalization cube map\n"; } ++num_released; _normalization_cube_map = NULL; } return num_released; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_list_contents // Access: Private // Description: The nonstatic implementation of list_contents(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_list_contents(ostream &out) const { out << _textures.size() << " textures:\n"; Textures::const_iterator ti; for (ti = _textures.begin(); ti != _textures.end(); ++ti) { Texture *texture = (*ti).second; out << " " << (*ti).first << " (count = " << texture->get_ref_count() << ", ram = " << texture->get_ram_image_size() / 1024 << " Kb)\n"; } } //////////////////////////////////////////////////////////////////// // Function: TexturePool::report_texture_unreadable // Access: Private // Description: Prints a suitable error message when a texture could // not be loaded. //////////////////////////////////////////////////////////////////// void TexturePool:: report_texture_unreadable(const Filename &filename) const { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); if (!vfs->exists(filename)) { if (filename.is_local()) { // The file doesn't exist, and it wasn't // fully-qualified--therefore, it wasn't found along either // search path. gobj_cat.error() << "Unable to find texture \"" << filename << "\"" << " on texture_path " << texture_path << " or model_path " << model_path <<"\n"; } else { // A fully-specified filename is not searched along the path, so // don't mislead the user with the error message. gobj_cat.error() << "Texture \"" << filename << "\" does not exist.\n"; } } else { // The file exists, but it couldn't be read for some reason. gobj_cat.error() << "Texture \"" << filename << "\" exists but cannot be read.\n"; } } //////////////////////////////////////////////////////////////////// // Function: TexturePool::get_ptr // Access: Private, Static // Description: Initializes and/or returns the global pointer to the // one TexturePool object in the system. //////////////////////////////////////////////////////////////////// TexturePool *TexturePool:: get_ptr() { if (_global_ptr == (TexturePool *)NULL) { _global_ptr = new TexturePool; } return _global_ptr; } <commit_msg>drose: i'm such a dope<commit_after>// Filename: texturePool.cxx // Created by: drose (26Apr00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// #include "texturePool.h" #include "config_gobj.h" #include "config_util.h" #include "config_express.h" #include "virtualFileSystem.h" TexturePool *TexturePool::_global_ptr = (TexturePool *)NULL; //////////////////////////////////////////////////////////////////// // Function: TexturePool::write // Access: Published, Static // Description: Lists the contents of the texture pool to the // indicated output stream. // For debugging. //////////////////////////////////////////////////////////////////// void TexturePool:: write(ostream &out) { get_ptr()->ns_list_contents(out); } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_has_texture // Access: Private // Description: The nonstatic implementation of has_texture(). //////////////////////////////////////////////////////////////////// bool TexturePool:: ns_has_texture(const Filename &orig_filename) { Filename filename(orig_filename); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()); vfs->resolve_filename(filename, get_model_path()); Textures::const_iterator ti; ti = _textures.find(filename); if (ti != _textures.end()) { // This texture was previously loaded. return true; } return false; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_texture // Access: Private // Description: The nonstatic implementation of load_texture(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_texture(const Filename &orig_filename, int primary_file_num_channels) { Filename filename(orig_filename); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); Textures::const_iterator ti; ti = _textures.find(filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading texture " << filename << "\n"; PT(Texture) tex = new Texture; if (!tex->read(filename, 0, primary_file_num_channels)) { // This texture was not found or could not be read. report_texture_unreadable(filename); return NULL; } // Set the original filename, before we searched along the path. tex->set_filename(orig_filename); _textures[filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_texture // Access: Private // Description: The nonstatic implementation of load_texture(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_texture(const Filename &orig_filename, const Filename &orig_alpha_filename, int primary_file_num_channels, int alpha_file_channel) { Filename filename(orig_filename); Filename alpha_filename(orig_alpha_filename); if (!_fake_texture_image.empty()) { return ns_load_texture(_fake_texture_image, primary_file_num_channels); } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); vfs->resolve_filename(alpha_filename, get_texture_path()) || vfs->resolve_filename(alpha_filename, get_model_path()); Textures::const_iterator ti; ti = _textures.find(filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading texture " << filename << " and alpha component " << alpha_filename << endl; PT(Texture) tex = new Texture; if (!tex->read(filename, alpha_filename, 0, primary_file_num_channels, alpha_file_channel)) { // This texture was not found or could not be read. report_texture_unreadable(filename); return NULL; } // Set the original filenames, before we searched along the path. tex->set_filename(orig_filename); tex->set_alpha_filename(orig_alpha_filename); _textures[filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_3d_texture // Access: Private // Description: The nonstatic implementation of load_3d_texture(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_3d_texture(const HashFilename &filename_template) { // Look up filename 0 on the model path. Filename filename = filename_template.get_filename_index(0); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); // Then, replace everything before the hash code with the directory // we've found. string hash = filename_template.get_hash_to_end(); HashFilename hash_filename(filename.substr(0, filename.length() - hash.length()) + hash); Textures::const_iterator ti; ti = _textures.find(hash_filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading 3-d texture " << hash_filename << "\n"; PT(Texture) tex = new Texture; tex->setup_3d_texture(); if (!tex->read_pages(hash_filename)) { // This texture was not found or could not be read. report_texture_unreadable(filename); } // Set the original filename, before we searched along the path. tex->set_filename(filename_template); _textures[hash_filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_load_cube_map // Access: Private // Description: The nonstatic implementation of load_cube_map(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_load_cube_map(const HashFilename &filename_template) { // Look up filename 0 on the model path. Filename filename = filename_template.get_filename_index(0); if (!_fake_texture_image.empty()) { filename = _fake_texture_image; } VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->resolve_filename(filename, get_texture_path()) || vfs->resolve_filename(filename, get_model_path()); // Then, replace everything before the hash code with the directory // we've found. string hash = filename_template.get_hash_to_end(); HashFilename hash_filename(filename.substr(0, filename.length() - hash.length()) + hash); Textures::const_iterator ti; ti = _textures.find(hash_filename); if (ti != _textures.end()) { // This texture was previously loaded. return (*ti).second; } gobj_cat.info() << "Loading cube map texture " << hash_filename << "\n"; PT(Texture) tex = new Texture; tex->setup_cube_map(); if (!tex->read_pages(hash_filename)) { // This texture was not found or could not be read. report_texture_unreadable(filename); } // Set the original filename, before we searched along the path. tex->set_filename(filename_template); _textures[hash_filename] = tex; return tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_get_normalization_cube_map // Access: Private // Description: The nonstatic implementation of get_normalization_cube_map(). //////////////////////////////////////////////////////////////////// Texture *TexturePool:: ns_get_normalization_cube_map(int size) { if (_normalization_cube_map == (Texture *)NULL) { _normalization_cube_map = new Texture("normalization_cube_map"); } if (_normalization_cube_map->get_x_size() < size || _normalization_cube_map->get_texture_type() != Texture::TT_cube_map) { _normalization_cube_map->generate_normalization_cube_map(size); } return _normalization_cube_map; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_add_texture // Access: Private // Description: The nonstatic implementation of add_texture(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_add_texture(Texture *tex) { string filename = tex->get_filename(); if (filename.empty()) { gobj_cat.error() << "Attempt to call add_texture() on an unnamed texture.\n"; } // We blow away whatever texture was there previously, if any. _textures[filename] = tex; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_release_texture // Access: Private // Description: The nonstatic implementation of release_texture(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_release_texture(Texture *tex) { string filename = tex->get_filename(); Textures::iterator ti; ti = _textures.find(filename); if (ti != _textures.end() && (*ti).second == tex) { _textures.erase(ti); } } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_release_all_textures // Access: Private // Description: The nonstatic implementation of release_all_textures(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_release_all_textures() { _textures.clear(); _normalization_cube_map = NULL; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_garbage_collect // Access: Private // Description: The nonstatic implementation of garbage_collect(). //////////////////////////////////////////////////////////////////// int TexturePool:: ns_garbage_collect() { int num_released = 0; Textures new_set; Textures::iterator ti; for (ti = _textures.begin(); ti != _textures.end(); ++ti) { Texture *tex = (*ti).second; if (tex->get_ref_count() == 1) { if (gobj_cat.is_debug()) { gobj_cat.debug() << "Releasing " << (*ti).first << "\n"; } ++num_released; } else { new_set.insert(new_set.end(), *ti); } } _textures.swap(new_set); if (_normalization_cube_map != (Texture *)NULL && _normalization_cube_map->get_ref_count() == 1) { if (gobj_cat.is_debug()) { gobj_cat.debug() << "Releasing normalization cube map\n"; } ++num_released; _normalization_cube_map = NULL; } return num_released; } //////////////////////////////////////////////////////////////////// // Function: TexturePool::ns_list_contents // Access: Private // Description: The nonstatic implementation of list_contents(). //////////////////////////////////////////////////////////////////// void TexturePool:: ns_list_contents(ostream &out) const { out << _textures.size() << " textures:\n"; Textures::const_iterator ti; for (ti = _textures.begin(); ti != _textures.end(); ++ti) { Texture *texture = (*ti).second; out << " " << (*ti).first << " (count = " << texture->get_ref_count() << ", ram = " << texture->get_ram_image_size() / 1024 << " Kb)\n"; } } //////////////////////////////////////////////////////////////////// // Function: TexturePool::report_texture_unreadable // Access: Private // Description: Prints a suitable error message when a texture could // not be loaded. //////////////////////////////////////////////////////////////////// void TexturePool:: report_texture_unreadable(const Filename &filename) const { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); if (!vfs->exists(filename)) { if (filename.is_local()) { // The file doesn't exist, and it wasn't // fully-qualified--therefore, it wasn't found along either // search path. gobj_cat.error() << "Unable to find texture \"" << filename << "\"" << " on texture_path " << texture_path << " or model_path " << model_path <<"\n"; } else { // A fully-specified filename is not searched along the path, so // don't mislead the user with the error message. gobj_cat.error() << "Texture \"" << filename << "\" does not exist.\n"; } } else { // The file exists, but it couldn't be read for some reason. gobj_cat.error() << "Texture \"" << filename << "\" exists but cannot be read.\n"; } } //////////////////////////////////////////////////////////////////// // Function: TexturePool::get_ptr // Access: Private, Static // Description: Initializes and/or returns the global pointer to the // one TexturePool object in the system. //////////////////////////////////////////////////////////////////// TexturePool *TexturePool:: get_ptr() { if (_global_ptr == (TexturePool *)NULL) { _global_ptr = new TexturePool; } return _global_ptr; } <|endoftext|>
<commit_before>/* This file is part of the KDE libraries Copyright (C) 2008 Niko Sams <niko.sams\gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "completion_test.h" #include "codecompletiontestmodels.h" #include "codecompletiontestmodels.moc" #include <qtest_kde.h> #include <ksycoca.h> #include <ktexteditor/document.h> #include <ktexteditor/editorchooser.h> #include <kateview.h> #include <katecompletionwidget.h> #include <katecompletionmodel.h> #include <katerenderer.h> #include <kateconfig.h> QTEST_KDEMAIN(CompletionTest, GUI) using namespace KTextEditor; int countItems(KateCompletionModel *model) { int ret = 0; for (int i=0; i < model->rowCount(QModelIndex()); ++i) { ret += model->rowCount(model->index(i, 0)); } return ret; } static void invokeCompletionBox(KateView* view) { QTest::qWait(500); // needed, otherwise, test fails view->userInvokedCompletion(); QTest::qWait(500); // wait until code completion pops up QVERIFY(view->completionWidget()->isCompletionActive()); } void CompletionTest::init() { if ( !KSycoca::isAvailable() ) QSKIP( "ksycoca not available", SkipAll ); Editor* editor = EditorChooser::editor(); QVERIFY(editor); m_doc = editor->createDocument(this); QVERIFY(m_doc); m_doc->setText("aa bb cc\ndd"); KTextEditor::View *v = m_doc->createView(0); QApplication::setActiveWindow(v); m_view = static_cast<KateView*>(v); Q_ASSERT(m_view); //view needs to be shown as completion won't work if the cursor is off screen m_view->show(); } void CompletionTest::cleanup() { delete m_view; delete m_doc; } void CompletionTest::testFilterEmptyRange() { KateCompletionModel *model = m_view->completionWidget()->model(); new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); m_view->insertText("aa"); QTest::qWait(100); // process events QCOMPARE(countItems(model), 14); } void CompletionTest::testFilterWithRange() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 2)); invokeCompletionBox(m_view); Range complRange = *m_view->completionWidget()->completionRange(testModel); QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 2))); QCOMPARE(countItems(model), 14); m_view->insertText("a"); QTest::qWait(100); // process events QCOMPARE(countItems(model), 1); } void CompletionTest::testAbortCursorMovedOutOfRange() { KateCompletionModel *model = m_view->completionWidget()->model(); new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 2)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 14); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->setCursorPosition(Cursor(0, 4)); QTest::qWait(100); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testAbortInvalidText() { KateCompletionModel *model = m_view->completionWidget()->model(); new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 2)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 14); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("."); QTest::qWait(100); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testCustomRange1() { m_doc->setText("$aa bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new CustomRangeModel(m_view, "$a"); m_view->setCursorPosition(Cursor(0, 3)); invokeCompletionBox(m_view); Range complRange = *m_view->completionWidget()->completionRange(testModel); kDebug() << complRange; QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 3))); QCOMPARE(countItems(model), 14); m_view->insertText("a"); QTest::qWait(100); // process events QCOMPARE(countItems(model), 1); } void CompletionTest::testCustomRange2() { m_doc->setText("$ bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new CustomRangeModel(m_view, "$a"); m_view->setCursorPosition(Cursor(0, 1)); invokeCompletionBox(m_view); Range complRange = *m_view->completionWidget()->completionRange(testModel); QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 1))); QCOMPARE(countItems(model), 40); m_view->insertText("aa"); QTest::qWait(100); // process events QCOMPARE(countItems(model), 14); } void CompletionTest::testCustomRangeMultipleModels() { m_doc->setText("$a bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel1 = new CustomRangeModel(m_view, "$a"); CodeCompletionTestModel* testModel2 = new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 1)); invokeCompletionBox(m_view); QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel1)), Range(Cursor(0, 0), Cursor(0, 2))); QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel2)), Range(Cursor(0, 1), Cursor(0, 2))); QCOMPARE(model->currentCompletion(testModel1), QString("$")); QCOMPARE(model->currentCompletion(testModel2), QString("")); QCOMPARE(countItems(model), 80); m_view->insertText("aa"); QTest::qWait(100); // process events QCOMPARE(model->currentCompletion(testModel1), QString("$aa")); QCOMPARE(model->currentCompletion(testModel2), QString("aa")); QCOMPARE(countItems(model), 14*2); } void CompletionTest::testAbortController() { KateCompletionModel *model = m_view->completionWidget()->model(); new CustomRangeModel(m_view, "$a"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("$a"); QTest::qWait(100); // process events QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("."); QTest::qWait(100); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testAbortControllerMultipleModels() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel1 = new CodeCompletionTestModel(m_view, "aa"); CodeCompletionTestModel* testModel2 = new CustomAbortModel(m_view, "a-"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 80); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("a"); QTest::qWait(100); // process events QVERIFY(m_view->completionWidget()->isCompletionActive()); QCOMPARE(countItems(model), 80); m_view->insertText("-"); QTest::qWait(100); // process events QVERIFY(m_view->completionWidget()->isCompletionActive()); QVERIFY(!m_view->completionWidget()->completionRanges().contains(testModel1)); QVERIFY(m_view->completionWidget()->completionRanges().contains(testModel2)); QCOMPARE(countItems(model), 40); m_view->insertText(" "); QTest::qWait(100); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testEmptyFilterString() { KateCompletionModel *model = m_view->completionWidget()->model(); new EmptyFilterStringModel(m_view, "aa"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); m_view->insertText("a"); QTest::qWait(100); // process events QCOMPARE(countItems(model), 40); m_view->insertText("bam"); QTest::qWait(100); // process events QCOMPARE(countItems(model), 40); } void CompletionTest::testUpdateCompletionRange() { m_doc->setText("ab bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new UpdateCompletionRangeModel(m_view, "ab ab"); m_view->setCursorPosition(Cursor(0, 3)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel)), Range(Cursor(0, 3), Cursor(0, 3))); m_view->insertText("ab"); QTest::qWait(100); // process events QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel)), Range(Cursor(0, 0), Cursor(0, 5))); QCOMPARE(countItems(model), 40); } void CompletionTest::testCustomStartCompl() { KateCompletionModel *model = m_view->completionWidget()->model(); m_view->completionWidget()->setAutomaticInvocationDelay(1); new StartCompletionModel(m_view, "aa"); m_view->setCursorPosition(Cursor(0, 0)); m_view->insertText("%"); QTest::qWait(100); QVERIFY(m_view->completionWidget()->isCompletionActive()); QCOMPARE(countItems(model), 40); } void CompletionTest::testKateCompletionModel() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel1 = new CodeCompletionTestModel(m_view, "aa"); CodeCompletionTestModel* testModel2 = new CodeCompletionTestModel(m_view, "bb"); model->setCompletionModel(testModel1); QCOMPARE(countItems(model), 40); model->addCompletionModel(testModel2); QCOMPARE(countItems(model), 80); model->removeCompletionModel(testModel2); QCOMPARE(countItems(model), 40); } void CompletionTest::testAbortImmideatelyAfterStart() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new ImmideatelyAbortCompletionModel(m_view); m_view->setCursorPosition(Cursor(0, 3)); QVERIFY(!m_view->completionWidget()->isCompletionActive()); emit m_view->userInvokedCompletion(); QVERIFY(!m_view->completionWidget()->isCompletionActive()); } #include "completion_test.moc" <commit_msg>try to fix some automated tests<commit_after>/* This file is part of the KDE libraries Copyright (C) 2008 Niko Sams <niko.sams\gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "completion_test.h" #include "codecompletiontestmodels.h" #include "codecompletiontestmodels.moc" #include <qtest_kde.h> #include <ksycoca.h> #include <ktexteditor/document.h> #include <ktexteditor/editorchooser.h> #include <kateview.h> #include <katecompletionwidget.h> #include <katecompletionmodel.h> #include <katerenderer.h> #include <kateconfig.h> QTEST_KDEMAIN(CompletionTest, GUI) using namespace KTextEditor; int countItems(KateCompletionModel *model) { int ret = 0; for (int i=0; i < model->rowCount(QModelIndex()); ++i) { ret += model->rowCount(model->index(i, 0)); } return ret; } static void invokeCompletionBox(KateView* view) { QTest::qWait(1000); // needed, otherwise, test fails view->userInvokedCompletion(); QTest::qWait(1000); // wait until code completion pops up QVERIFY(view->completionWidget()->isCompletionActive()); } void CompletionTest::init() { if ( !KSycoca::isAvailable() ) QSKIP( "ksycoca not available", SkipAll ); Editor* editor = EditorChooser::editor(); QVERIFY(editor); m_doc = editor->createDocument(this); QVERIFY(m_doc); m_doc->setText("aa bb cc\ndd"); KTextEditor::View *v = m_doc->createView(0); QApplication::setActiveWindow(v); m_view = static_cast<KateView*>(v); Q_ASSERT(m_view); //view needs to be shown as completion won't work if the cursor is off screen m_view->show(); } void CompletionTest::cleanup() { delete m_view; delete m_doc; } void CompletionTest::testFilterEmptyRange() { KateCompletionModel *model = m_view->completionWidget()->model(); new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); m_view->insertText("aa"); QTest::qWait(1000); // process events QCOMPARE(countItems(model), 14); } void CompletionTest::testFilterWithRange() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 2)); invokeCompletionBox(m_view); Range complRange = *m_view->completionWidget()->completionRange(testModel); QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 2))); QCOMPARE(countItems(model), 14); m_view->insertText("a"); QTest::qWait(1000); // process events QCOMPARE(countItems(model), 1); } void CompletionTest::testAbortCursorMovedOutOfRange() { KateCompletionModel *model = m_view->completionWidget()->model(); new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 2)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 14); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->setCursorPosition(Cursor(0, 4)); QTest::qWait(1000); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testAbortInvalidText() { KateCompletionModel *model = m_view->completionWidget()->model(); new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 2)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 14); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("."); QTest::qWait(1000); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testCustomRange1() { m_doc->setText("$aa bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new CustomRangeModel(m_view, "$a"); m_view->setCursorPosition(Cursor(0, 3)); invokeCompletionBox(m_view); Range complRange = *m_view->completionWidget()->completionRange(testModel); kDebug() << complRange; QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 3))); QCOMPARE(countItems(model), 14); m_view->insertText("a"); QTest::qWait(1000); // process events QCOMPARE(countItems(model), 1); } void CompletionTest::testCustomRange2() { m_doc->setText("$ bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new CustomRangeModel(m_view, "$a"); m_view->setCursorPosition(Cursor(0, 1)); invokeCompletionBox(m_view); Range complRange = *m_view->completionWidget()->completionRange(testModel); QCOMPARE(complRange, Range(Cursor(0, 0), Cursor(0, 1))); QCOMPARE(countItems(model), 40); m_view->insertText("aa"); QTest::qWait(1000); // process events QCOMPARE(countItems(model), 14); } void CompletionTest::testCustomRangeMultipleModels() { m_doc->setText("$a bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel1 = new CustomRangeModel(m_view, "$a"); CodeCompletionTestModel* testModel2 = new CodeCompletionTestModel(m_view, "a"); m_view->setCursorPosition(Cursor(0, 1)); invokeCompletionBox(m_view); QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel1)), Range(Cursor(0, 0), Cursor(0, 2))); QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel2)), Range(Cursor(0, 1), Cursor(0, 2))); QCOMPARE(model->currentCompletion(testModel1), QString("$")); QCOMPARE(model->currentCompletion(testModel2), QString("")); QCOMPARE(countItems(model), 80); m_view->insertText("aa"); QTest::qWait(1000); // process events QCOMPARE(model->currentCompletion(testModel1), QString("$aa")); QCOMPARE(model->currentCompletion(testModel2), QString("aa")); QCOMPARE(countItems(model), 14*2); } void CompletionTest::testAbortController() { KateCompletionModel *model = m_view->completionWidget()->model(); new CustomRangeModel(m_view, "$a"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("$a"); QTest::qWait(1000); // process events QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("."); QTest::qWait(1000); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testAbortControllerMultipleModels() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel1 = new CodeCompletionTestModel(m_view, "aa"); CodeCompletionTestModel* testModel2 = new CustomAbortModel(m_view, "a-"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 80); QVERIFY(m_view->completionWidget()->isCompletionActive()); m_view->insertText("a"); QTest::qWait(1000); // process events QVERIFY(m_view->completionWidget()->isCompletionActive()); QCOMPARE(countItems(model), 80); m_view->insertText("-"); QTest::qWait(1000); // process events QVERIFY(m_view->completionWidget()->isCompletionActive()); QVERIFY(!m_view->completionWidget()->completionRanges().contains(testModel1)); QVERIFY(m_view->completionWidget()->completionRanges().contains(testModel2)); QCOMPARE(countItems(model), 40); m_view->insertText(" "); QTest::qWait(1000); // process events QVERIFY(!m_view->completionWidget()->isCompletionActive()); } void CompletionTest::testEmptyFilterString() { KateCompletionModel *model = m_view->completionWidget()->model(); new EmptyFilterStringModel(m_view, "aa"); m_view->setCursorPosition(Cursor(0, 0)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); m_view->insertText("a"); QTest::qWait(1000); // process events QCOMPARE(countItems(model), 40); m_view->insertText("bam"); QTest::qWait(1000); // process events QCOMPARE(countItems(model), 40); } void CompletionTest::testUpdateCompletionRange() { m_doc->setText("ab bb cc\ndd"); KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new UpdateCompletionRangeModel(m_view, "ab ab"); m_view->setCursorPosition(Cursor(0, 3)); invokeCompletionBox(m_view); QCOMPARE(countItems(model), 40); QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel)), Range(Cursor(0, 3), Cursor(0, 3))); m_view->insertText("ab"); QTest::qWait(1000); // process events QCOMPARE(Range(*m_view->completionWidget()->completionRange(testModel)), Range(Cursor(0, 0), Cursor(0, 5))); QCOMPARE(countItems(model), 40); } void CompletionTest::testCustomStartCompl() { KateCompletionModel *model = m_view->completionWidget()->model(); m_view->completionWidget()->setAutomaticInvocationDelay(1); new StartCompletionModel(m_view, "aa"); m_view->setCursorPosition(Cursor(0, 0)); m_view->insertText("%"); QTest::qWait(1000); QVERIFY(m_view->completionWidget()->isCompletionActive()); QCOMPARE(countItems(model), 40); } void CompletionTest::testKateCompletionModel() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel1 = new CodeCompletionTestModel(m_view, "aa"); CodeCompletionTestModel* testModel2 = new CodeCompletionTestModel(m_view, "bb"); model->setCompletionModel(testModel1); QCOMPARE(countItems(model), 40); model->addCompletionModel(testModel2); QCOMPARE(countItems(model), 80); model->removeCompletionModel(testModel2); QCOMPARE(countItems(model), 40); } void CompletionTest::testAbortImmideatelyAfterStart() { KateCompletionModel *model = m_view->completionWidget()->model(); CodeCompletionTestModel* testModel = new ImmideatelyAbortCompletionModel(m_view); m_view->setCursorPosition(Cursor(0, 3)); QVERIFY(!m_view->completionWidget()->isCompletionActive()); emit m_view->userInvokedCompletion(); QVERIFY(!m_view->completionWidget()->isCompletionActive()); } #include "completion_test.moc" <|endoftext|>
<commit_before>/* * Written by Nitin Kumar Maharana * [email protected] */ //Delete a node from BST. #include <iostream> using namespace std; struct node { node *left; int val; node *right; }; node* insert(node *root, int val) { if(root == nullptr) { root = new node(); root->val = val; root->left = root->right = nullptr; return root; } if(val > root->val) root->right = insert(root->right, val); else root->left = insert(root->left, val); return root; } void traverse(node *root) { if(root == nullptr) return; traverse(root->left); cout << root->val << " "; traverse(root->right); return; } node* getMax(node *root) { while(root->right) root = root->right; return root; } node* deleteNode(node *root, int val) { if(root == nullptr) return root; if(val > root->val) root->right = deleteNode(root->right, val); else if(val < root->val) root->left = deleteNode(root->left, val); else { node *temp; if(root->left == nullptr && root->right == nullptr) { delete root; root = nullptr; } else if(root->left == nullptr) { temp = root->right; delete root; root = temp; } else if(root->right == nullptr) { temp = root->left; delete root; root = temp; } else { temp = getMax(root->left); root->val = temp->val; root->left = deleteNode(root->left, temp->val); } } return root; } int main(void) { node *root; root = nullptr; root = insert(root, 10); root = insert(root, 5); root = insert(root, 3); root = insert(root, 7); root = insert(root, 15); root = insert(root, 12); root = insert(root, 20); cout << "Before Deletion: "; traverse(root); cout << endl; root = deleteNode(root, 10); cout << "After Deletion: "; traverse(root); cout << endl; return 0; }<commit_msg>Function for finding the inorder successor of a node.<commit_after>/* * Written by Nitin Kumar Maharana * [email protected] */ //Delete a node from BST. #include <iostream> using namespace std; struct node { node *left; int val; node *right; }; node* insert(node *root, int val) { if(root == nullptr) { root = new node(); root->val = val; root->left = root->right = nullptr; return root; } if(val > root->val) root->right = insert(root->right, val); else root->left = insert(root->left, val); return root; } void traverse(node *root) { if(root == nullptr) return; traverse(root->left); cout << root->val << " "; traverse(root->right); return; } node* getMax(node *root) { while(root->right) root = root->right; return root; } node* deleteNode(node *root, int val) { if(root == nullptr) return root; if(val > root->val) root->right = deleteNode(root->right, val); else if(val < root->val) root->left = deleteNode(root->left, val); else { node *temp; if(root->left == nullptr && root->right == nullptr) { delete root; root = nullptr; } else if(root->left == nullptr) { temp = root->right; delete root; root = temp; } else if(root->right == nullptr) { temp = root->left; delete root; root = temp; } else { temp = getMax(root->left); root->val = temp->val; root->left = deleteNode(root->left, temp->val); } } return root; } //Assuming it is always present. node* findNode(node *root, int val) { if(root->val == val) return root; if(val < root->val) return findNode(root->left, val); else return findNode(root->right, val); } //Assume it is always present. int inorderSuccessor(node *root, int val) { node *p = findNode(root, val); if(p->right) { p = p->right; while(p->left) p = p->left; return p->val; } node *result = root; node *curr = root; while(curr != p) { if(p->val < curr->val) { result = curr; curr = curr->left; } else curr = curr->right; } return result->val; } int main(void) { node *root; root = nullptr; root = insert(root, 10); root = insert(root, 5); root = insert(root, 3); root = insert(root, 7); root = insert(root, 15); root = insert(root, 12); root = insert(root, 20); cout << "Before Deletion: "; traverse(root); cout << endl; root = deleteNode(root, 10); cout << "After Deletion: "; traverse(root); cout << endl; cout << "Inorder Successor of 7: "; cout << inorderSuccessor(root, 7) << endl; return 0; }<|endoftext|>
<commit_before><commit_msg>merging<commit_after><|endoftext|>
<commit_before>/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /** * @file MuscleNP.cpp * @brief Definition of a massless cable with contact dynamics * $Id$ */ // This object #include "MuscleNP.h" // NTRT #include "tgcreator/tgUtil.h" #include "core/muscleAnchor.h" #include "core/tgCast.h" // The Bullet Physics library #include "btBulletDynamicsCommon.h" #include "BulletCollision/CollisionDispatch/btGhostObject.h" #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btCollisionWorld.h" #include "BulletDynamics/Dynamics/btActionInterface.h" #include "LinearMath/btDefaultMotionState.h" // Classes for manual collision detection - will likely remove later #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" #include "BulletCollision/NarrowPhaseCollision/btPointCollector.h" #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" #include <iostream> #include <algorithm> // std::sort MuscleNP::MuscleNP(btPairCachingGhostObject* ghostObject, btBroadphaseInterface* broadphase, btRigidBody * body1, btVector3 pos1, btRigidBody * body2, btVector3 pos2, double coefK, double dampingCoefficient) : Muscle2P (body1, pos1, body2, pos2, coefK, dampingCoefficient), m_ghostObject(ghostObject), m_overlappingPairCache(broadphase), m_ac(anchor1, anchor2) { } MuscleNP::~MuscleNP() { } const btScalar MuscleNP::getActualLength() const { btScalar length = 0; std::size_t n = m_anchors.size() - 1; for (std::size_t i = 0; i < n; i++) { length += (m_anchors[i]->getWorldPosition() - m_anchors[i+1]->getWorldPosition()).length(); } return length; } btVector3 MuscleNP::calculateAndApplyForce(double dt) { updateAnchorList(dt); // Apply forces btVector3 from = anchor1->getWorldPosition(); btVector3 to = anchor2->getWorldPosition(); btTransform transform = tgUtil::getTransform(from, to); //std::cout << (to - from).length()/2.0 << std::endl; m_ghostObject->setWorldTransform(transform); btScalar radius = 0.1; btCylinderShape* shape = tgCast::cast<btCollisionShape, btCylinderShape>(*m_ghostObject->getCollisionShape()); /* Note that 1) this is listed as "use with care" in Bullet's documentation and * 2) we had to remove the object from DemoApplication's render function in order for it to render properly * changing from a non-contact object will break that behavior. */ shape->setImplicitShapeDimensions(btVector3(radius, (to - from).length()/2.0, radius)); m_ghostObject->setCollisionShape(shape); Muscle2P::calculateAndApplyForce(dt); } void MuscleNP::updateAnchorList(double dt) { std::vector<const muscleAnchor*>::iterator it = m_anchors.begin(); muscleAnchor* temp; for (it = m_anchors.begin(); it != m_anchors.end(); it++) { if ((*it)->permanent == false) { delete *it; } } m_anchors.clear(); m_anchors.insert(m_anchors.begin(), anchor1); m_anchors.insert(m_anchors.end(), anchor2); btManifoldArray m_manifoldArray; btVector3 m_touchingNormal; //std::cout << m_ghostObject->getOverlappingPairCache()->getNumOverlappingPairs() << std::endl; // Only caches the pairs, they don't have a lot of useful information btBroadphasePairArray& pairArray = m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray(); int numPairs = pairArray.size(); for (int i=0;i<numPairs;i++) { m_manifoldArray.clear(); const btBroadphasePair& pair = pairArray[i]; // The real broadphase's pair cache has the useful info btBroadphasePair* collisionPair = m_overlappingPairCache->getOverlappingPairCache()->findPair(pair.m_pProxy0,pair.m_pProxy1); btCollisionObject* obj0 = static_cast<btCollisionObject*>(collisionPair->m_pProxy0->m_clientObject); btCollisionObject* obj1 = static_cast<btCollisionObject*>(collisionPair->m_pProxy1->m_clientObject); if (collisionPair->m_algorithm) collisionPair->m_algorithm->getAllContactManifolds(m_manifoldArray); //std::cout << m_manifoldArray.size() << std::endl; for (int j=0;j<m_manifoldArray.size();j++) { btPersistentManifold* manifold = m_manifoldArray[j]; btScalar directionSign = manifold->getBody0() == m_ghostObject ? btScalar(-1.0) : btScalar(1.0); for (int p=0;p<manifold->getNumContacts();p++) { const btManifoldPoint&pt = manifold->getContactPoint(p); btScalar dist = pt.getDistance(); // Ensures the force is pointed outwards - may need to double check if (dist < 0.0) { m_touchingNormal = pt.m_normalWorldOnB * directionSign;//?? btRigidBody* rb = NULL; btVector3 pos; if (directionSign < 0) { rb = btRigidBody::upcast(obj1); pos = pt.m_localPointA; } else { rb = btRigidBody::upcast(obj0); pos = pt.m_localPointB; } if(rb) { const muscleAnchor* newAnchor = new muscleAnchor(rb, pos, m_touchingNormal, false, true); m_anchors.push_back(newAnchor); btScalar mass = rb->getInvMass() == 0 ? 0.0 : 1.0 / rb->getInvMass(); btVector3 impulse = mass * dt * m_touchingNormal * getTension() / getActualLength() * -1.0* dist; rb->applyImpulse(impulse, pos); } } } } } std::sort (m_anchors.begin(), m_anchors.end(), m_ac); } MuscleNP::anchorCompare::anchorCompare(const muscleAnchor* m1, const muscleAnchor* m2) : ma1(m1), ma2(m2) { } bool MuscleNP::anchorCompare::operator() (const muscleAnchor* lhs, const muscleAnchor* rhs) { btVector3 pt1 = ma1->getWorldPosition(); btVector3 ptN = ma2->getWorldPosition(); btVector3 pt2 = lhs->getWorldPosition(); btVector3 pt3 = rhs->getWorldPosition(); btScalar lhDot = (ptN - pt1).dot(pt2); btScalar rhDot = (ptN - pt1).dot(pt3); return lhDot < rhDot; } <commit_msg>Bugfix in anchor definition<commit_after>/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /** * @file MuscleNP.cpp * @brief Definition of a massless cable with contact dynamics * $Id$ */ // This object #include "MuscleNP.h" // NTRT #include "tgcreator/tgUtil.h" #include "core/muscleAnchor.h" #include "core/tgCast.h" // The Bullet Physics library #include "btBulletDynamicsCommon.h" #include "BulletCollision/CollisionDispatch/btGhostObject.h" #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h" #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h" #include "BulletCollision/CollisionDispatch/btCollisionWorld.h" #include "BulletDynamics/Dynamics/btActionInterface.h" #include "LinearMath/btDefaultMotionState.h" // Classes for manual collision detection - will likely remove later #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h" #include "BulletCollision/NarrowPhaseCollision/btPointCollector.h" #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h" #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h" #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h" #include <iostream> #include <algorithm> // std::sort MuscleNP::MuscleNP(btPairCachingGhostObject* ghostObject, btBroadphaseInterface* broadphase, btRigidBody * body1, btVector3 pos1, btRigidBody * body2, btVector3 pos2, double coefK, double dampingCoefficient) : Muscle2P (body1, pos1, body2, pos2, coefK, dampingCoefficient), m_ghostObject(ghostObject), m_overlappingPairCache(broadphase), m_ac(anchor1, anchor2) { } MuscleNP::~MuscleNP() { } const btScalar MuscleNP::getActualLength() const { btScalar length = 0; std::size_t n = m_anchors.size() - 1; for (std::size_t i = 0; i < n; i++) { length += (m_anchors[i]->getWorldPosition() - m_anchors[i+1]->getWorldPosition()).length(); } return length; } btVector3 MuscleNP::calculateAndApplyForce(double dt) { updateAnchorList(dt); // Apply forces btVector3 from = anchor1->getWorldPosition(); btVector3 to = anchor2->getWorldPosition(); btTransform transform = tgUtil::getTransform(from, to); //std::cout << (to - from).length()/2.0 << std::endl; m_ghostObject->setWorldTransform(transform); btScalar radius = 0.01; btCylinderShape* shape = tgCast::cast<btCollisionShape, btCylinderShape>(*m_ghostObject->getCollisionShape()); /* Note that 1) this is listed as "use with care" in Bullet's documentation and * 2) we had to remove the object from DemoApplication's render function in order for it to render properly * changing from a non-contact object will break that behavior. */ shape->setImplicitShapeDimensions(btVector3(radius, (to - from).length()/2.0, radius)); m_ghostObject->setCollisionShape(shape); Muscle2P::calculateAndApplyForce(dt); } void MuscleNP::updateAnchorList(double dt) { std::vector<const muscleAnchor*>::iterator it = m_anchors.begin(); muscleAnchor* temp; for (it = m_anchors.begin(); it != m_anchors.end(); it++) { if ((*it)->permanent == false) { delete *it; } } m_anchors.clear(); m_anchors.insert(m_anchors.begin(), anchor1); m_anchors.insert(m_anchors.end(), anchor2); btManifoldArray m_manifoldArray; btVector3 m_touchingNormal; //std::cout << m_ghostObject->getOverlappingPairCache()->getNumOverlappingPairs() << std::endl; // Only caches the pairs, they don't have a lot of useful information btBroadphasePairArray& pairArray = m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray(); int numPairs = pairArray.size(); for (int i=0;i<numPairs;i++) { m_manifoldArray.clear(); const btBroadphasePair& pair = pairArray[i]; // The real broadphase's pair cache has the useful info btBroadphasePair* collisionPair = m_overlappingPairCache->getOverlappingPairCache()->findPair(pair.m_pProxy0,pair.m_pProxy1); btCollisionObject* obj0 = static_cast<btCollisionObject*>(collisionPair->m_pProxy0->m_clientObject); btCollisionObject* obj1 = static_cast<btCollisionObject*>(collisionPair->m_pProxy1->m_clientObject); if (collisionPair->m_algorithm) collisionPair->m_algorithm->getAllContactManifolds(m_manifoldArray); //std::cout << m_manifoldArray.size() << std::endl; for (int j=0;j<m_manifoldArray.size();j++) { btPersistentManifold* manifold = m_manifoldArray[j]; btScalar directionSign = manifold->getBody0() == m_ghostObject ? btScalar(-1.0) : btScalar(1.0); for (int p=0;p<manifold->getNumContacts();p++) { const btManifoldPoint&pt = manifold->getContactPoint(p); btScalar dist = pt.getDistance(); // Ensures the force is pointed outwards - may need to double check if (dist < 0.0) { m_touchingNormal = pt.m_normalWorldOnB * directionSign;//?? btRigidBody* rb = NULL; btVector3 pos; if (directionSign < 0) { rb = btRigidBody::upcast(obj1); pos = pt.m_positionWorldOnA; } else { rb = btRigidBody::upcast(obj0); pos = pt.m_positionWorldOnB; } if(rb) { const muscleAnchor* newAnchor = new muscleAnchor(rb, pos, m_touchingNormal, false, true); m_anchors.push_back(newAnchor); /* btScalar mass = rb->getInvMass() == 0 ? 0.0 : 1.0 / rb->getInvMass(); btVector3 impulse = mass * dt * m_touchingNormal * getTension() / getActualLength() * -1.0* dist; rb->applyImpulse(impulse, pos); */ } } } } } std::sort (m_anchors.begin(), m_anchors.end(), m_ac); std::size_t n = m_anchors.size(); for (int i = 0; i < n; i++) { std::cout << m_anchors[i]->getWorldPosition() << std::endl; } } MuscleNP::anchorCompare::anchorCompare(const muscleAnchor* m1, const muscleAnchor* m2) : ma1(m1), ma2(m2) { } bool MuscleNP::anchorCompare::operator() (const muscleAnchor* lhs, const muscleAnchor* rhs) { btVector3 pt1 = ma1->getWorldPosition(); btVector3 ptN = ma2->getWorldPosition(); btVector3 pt2 = lhs->getWorldPosition(); btVector3 pt3 = rhs->getWorldPosition(); btScalar lhDot = (ptN - pt1).dot(pt2); btScalar rhDot = (ptN - pt1).dot(pt3); return lhDot < rhDot; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors. * License: https://github.com/dbartolini/crown/blob/master/LICENSE */ #include "config.h" #include "core/command_line.h" #include "core/filesystem/path.h" #include "device/device_options.h" #include <stdlib.h> namespace crown { static void help(const char* msg = NULL) { printf( "The Flexible Game Engine\n" "Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.\n" "License: https://github.com/dbartolini/crown/blob/master/LICENSE\n" "\n" "Usage:\n" " crown [options]\n" "\n" "Options:\n" " -h --help Display this help.\n" " -v --version Display engine version.\n" " --source-dir <path> Use <path> as the source directory for resource compilation.\n" " --data-dir <path> Use <path> as the destination directory for compiled resources.\n" " --map-source-dir <name> <path> Mount <path>/<name> at <source-dir>/<name>.\n" " --boot-dir <prefix> Use <prefix>/boot.config to boot the engine.\n" " --compile Do a full compile of the resources.\n" " --platform <platform> Compile resources for the given <platform>.\n" " linux\n" " windows\n" " android\n" " --continue Run the engine after resource compilation.\n" " --console-port <port> Set port of the console.\n" " --wait-console Wait for a console connection before starting up.\n" " --parent-window <handle> Set the parent window <handle> of the main window.\n" " --server Run the engine in server mode.\n" "\n" "Complete documentation available at https://dbartolini.github.io/crown/html/v" CROWN_VERSION "\n" ); if (msg) printf("Error: %s\n", msg); } DeviceOptions::DeviceOptions(Allocator& a, int argc, const char** argv) : _argc(argc) , _argv(argv) , _source_dir(a) , _map_source_dir_name(NULL) , _map_source_dir_prefix(a) , _data_dir(a) , _boot_dir(NULL) , _platform(NULL) , _lua_string(a) , _wait_console(false) , _do_compile(false) , _do_continue(false) , _server(false) , _parent_window(0) , _console_port(CROWN_DEFAULT_CONSOLE_PORT) , _window_x(0) , _window_y(0) , _window_width(CROWN_DEFAULT_WINDOW_WIDTH) , _window_height(CROWN_DEFAULT_WINDOW_HEIGHT) { } int DeviceOptions::parse() { CommandLine cl(_argc, _argv); if (cl.has_option("help", 'h')) { help(); return EXIT_FAILURE; } if (cl.has_option("version", 'v')) { printf(CROWN_VERSION); return EXIT_FAILURE; } path::reduce(_source_dir, cl.get_parameter(0, "source-dir")); path::reduce(_data_dir, cl.get_parameter(0, "data-dir")); _map_source_dir_name = cl.get_parameter(0, "map-source-dir"); if (_map_source_dir_name) { path::reduce(_map_source_dir_prefix, cl.get_parameter(1, "map-source-dir")); if (_map_source_dir_prefix.empty()) { help("Mapped source directory must be specified."); return EXIT_FAILURE; } } _do_compile = cl.has_option("compile"); if (_do_compile) { _platform = cl.get_parameter(0, "platform"); // Compile for platform the executable is built for. if (!_platform) _platform = CROWN_PLATFORM_NAME; if (true && strcmp(_platform, "android") != 0 && strcmp(_platform, "linux") != 0 && strcmp(_platform, "windows") != 0 ) { help("Cannot compile for the given platform."); return EXIT_FAILURE; } if (_source_dir.empty()) { help("Source dir must be specified."); return EXIT_FAILURE; } if (_data_dir.empty()) { _data_dir += _source_dir; _data_dir += '_'; _data_dir += _platform; } } _server = cl.has_option("server"); if (_server) { if (_source_dir.empty()) { help("Source dir must be specified."); return EXIT_FAILURE; } } if (!_data_dir.empty()) { if (!path::is_absolute(_data_dir.c_str())) { help("Data dir must be absolute."); return EXIT_FAILURE; } } if (!_source_dir.empty()) { if (!path::is_absolute(_source_dir.c_str())) { help("Source dir must be absolute."); return EXIT_FAILURE; } } if (!_map_source_dir_prefix.empty()) { if (!path::is_absolute(_map_source_dir_prefix.c_str())) { help("Mapped source dir must be absolute."); return EXIT_FAILURE; } } _do_continue = cl.has_option("continue"); _boot_dir = cl.get_parameter(0, "boot-dir"); if (_boot_dir) { if (!path::is_relative(_boot_dir)) { help("Boot dir must be relative."); return EXIT_FAILURE; } } _wait_console = cl.has_option("wait-console"); const char* parent = cl.get_parameter(0, "parent-window"); if (parent) { if (sscanf(parent, "%u", &_parent_window) != 1) { help("Parent window is invalid."); return EXIT_FAILURE; } } const char* port = cl.get_parameter(0, "console-port"); if (port) { if (sscanf(port, "%hu", &_console_port) != 1) { help("Console port is invalid."); return EXIT_FAILURE; } } const char* ls = cl.get_parameter(0, "lua-string"); if (ls) _lua_string = ls; return EXIT_SUCCESS; } } // namespace crown <commit_msg>device: fix --version<commit_after>/* * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors. * License: https://github.com/dbartolini/crown/blob/master/LICENSE */ #include "config.h" #include "core/command_line.h" #include "core/filesystem/path.h" #include "device/device_options.h" #include <stdlib.h> namespace crown { static void help(const char* msg = NULL) { printf( "The Flexible Game Engine\n" "Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.\n" "License: https://github.com/dbartolini/crown/blob/master/LICENSE\n" "\n" "Usage:\n" " crown [options]\n" "\n" "Options:\n" " -h --help Display this help.\n" " -v --version Display engine version.\n" " --source-dir <path> Use <path> as the source directory for resource compilation.\n" " --data-dir <path> Use <path> as the destination directory for compiled resources.\n" " --map-source-dir <name> <path> Mount <path>/<name> at <source-dir>/<name>.\n" " --boot-dir <prefix> Use <prefix>/boot.config to boot the engine.\n" " --compile Do a full compile of the resources.\n" " --platform <platform> Compile resources for the given <platform>.\n" " linux\n" " windows\n" " android\n" " --continue Run the engine after resource compilation.\n" " --console-port <port> Set port of the console.\n" " --wait-console Wait for a console connection before starting up.\n" " --parent-window <handle> Set the parent window <handle> of the main window.\n" " --server Run the engine in server mode.\n" "\n" "Complete documentation available at https://dbartolini.github.io/crown/html/v" CROWN_VERSION "\n" ); if (msg) printf("Error: %s\n", msg); } DeviceOptions::DeviceOptions(Allocator& a, int argc, const char** argv) : _argc(argc) , _argv(argv) , _source_dir(a) , _map_source_dir_name(NULL) , _map_source_dir_prefix(a) , _data_dir(a) , _boot_dir(NULL) , _platform(NULL) , _lua_string(a) , _wait_console(false) , _do_compile(false) , _do_continue(false) , _server(false) , _parent_window(0) , _console_port(CROWN_DEFAULT_CONSOLE_PORT) , _window_x(0) , _window_y(0) , _window_width(CROWN_DEFAULT_WINDOW_WIDTH) , _window_height(CROWN_DEFAULT_WINDOW_HEIGHT) { } int DeviceOptions::parse() { CommandLine cl(_argc, _argv); if (cl.has_option("help", 'h')) { help(); return EXIT_FAILURE; } if (cl.has_option("version", 'v')) { printf("Crown " CROWN_VERSION "\n"); return EXIT_FAILURE; } path::reduce(_source_dir, cl.get_parameter(0, "source-dir")); path::reduce(_data_dir, cl.get_parameter(0, "data-dir")); _map_source_dir_name = cl.get_parameter(0, "map-source-dir"); if (_map_source_dir_name) { path::reduce(_map_source_dir_prefix, cl.get_parameter(1, "map-source-dir")); if (_map_source_dir_prefix.empty()) { help("Mapped source directory must be specified."); return EXIT_FAILURE; } } _do_compile = cl.has_option("compile"); if (_do_compile) { _platform = cl.get_parameter(0, "platform"); // Compile for platform the executable is built for. if (!_platform) _platform = CROWN_PLATFORM_NAME; if (true && strcmp(_platform, "android") != 0 && strcmp(_platform, "linux") != 0 && strcmp(_platform, "windows") != 0 ) { help("Cannot compile for the given platform."); return EXIT_FAILURE; } if (_source_dir.empty()) { help("Source dir must be specified."); return EXIT_FAILURE; } if (_data_dir.empty()) { _data_dir += _source_dir; _data_dir += '_'; _data_dir += _platform; } } _server = cl.has_option("server"); if (_server) { if (_source_dir.empty()) { help("Source dir must be specified."); return EXIT_FAILURE; } } if (!_data_dir.empty()) { if (!path::is_absolute(_data_dir.c_str())) { help("Data dir must be absolute."); return EXIT_FAILURE; } } if (!_source_dir.empty()) { if (!path::is_absolute(_source_dir.c_str())) { help("Source dir must be absolute."); return EXIT_FAILURE; } } if (!_map_source_dir_prefix.empty()) { if (!path::is_absolute(_map_source_dir_prefix.c_str())) { help("Mapped source dir must be absolute."); return EXIT_FAILURE; } } _do_continue = cl.has_option("continue"); _boot_dir = cl.get_parameter(0, "boot-dir"); if (_boot_dir) { if (!path::is_relative(_boot_dir)) { help("Boot dir must be relative."); return EXIT_FAILURE; } } _wait_console = cl.has_option("wait-console"); const char* parent = cl.get_parameter(0, "parent-window"); if (parent) { if (sscanf(parent, "%u", &_parent_window) != 1) { help("Parent window is invalid."); return EXIT_FAILURE; } } const char* port = cl.get_parameter(0, "console-port"); if (port) { if (sscanf(port, "%hu", &_console_port) != 1) { help("Console port is invalid."); return EXIT_FAILURE; } } const char* ls = cl.get_parameter(0, "lua-string"); if (ls) _lua_string = ls; return EXIT_SUCCESS; } } // namespace crown <|endoftext|>
<commit_before>// // Copyright RIME Developers // Distributed under the BSD License // // 2011-11-27 GONG Chen <[email protected]> // #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <utf8.h> #include <rime/service.h> #include <rime/dict/preset_vocabulary.h> #include <rime/dict/text_db.h> namespace rime { struct VocabularyDb : public TextDb { explicit VocabularyDb(const string& path); an<DbAccessor> cursor; static const TextFormat format; }; VocabularyDb::VocabularyDb(const string& path) : TextDb(path, "vocabulary", VocabularyDb::format) { } static bool rime_vocabulary_entry_parser(const Tsv& row, string* key, string* value) { if (row.size() < 1 || row[0].empty()) { return false; } *key = row[0]; *value = row.size() > 1 ? row[1] : "0"; return true; } static bool rime_vocabulary_entry_formatter(const string& key, const string& value, Tsv* tsv) { //Tsv& row(*tsv); //row.push_back(key); //row.push_back(value); return true; } const TextFormat VocabularyDb::format = { rime_vocabulary_entry_parser, rime_vocabulary_entry_formatter, "Rime vocabulary", }; string PresetVocabulary::DictFilePath() { boost::filesystem::path path(Service::instance().deployer().shared_data_dir); path /= "essay.txt"; return path.string(); } PresetVocabulary::PresetVocabulary() { db_.reset(new VocabularyDb(DictFilePath())); if (db_ && db_->OpenReadOnly()) { db_->cursor = db_->QueryAll(); } } PresetVocabulary::~PresetVocabulary() { if (db_) db_->Close(); } bool PresetVocabulary::GetWeightForEntry(const string &key, double *weight) { string weight_str; if (!db_ || !db_->Fetch(key, &weight_str)) return false; try { *weight = boost::lexical_cast<double>(weight_str); } catch (...) { return false; } return true; } void PresetVocabulary::Reset() { if (db_ && db_->cursor) db_->cursor->Reset(); } bool PresetVocabulary::GetNextEntry(string *key, string *value) { if (!db_ || !db_->cursor) return false; bool got = false; do { got = db_->cursor->GetNextRecord(key, value); } while (got && !IsQualifiedPhrase(*key, *value)); return got; } bool PresetVocabulary::IsQualifiedPhrase(const string& phrase, const string& weight_str) { if (max_phrase_length_ > 0) { size_t length = utf8::unchecked::distance(phrase.c_str(), phrase.c_str() + phrase.length()); if (static_cast<int>(length) > max_phrase_length_) return false; } if (min_phrase_weight_ > 0.0) { double weight = boost::lexical_cast<double>(weight_str); if (weight < min_phrase_weight_) return false; } return true; } } // namespace rime <commit_msg>(dict) find essay.txt in user data directory as a fallback.<commit_after>// // Copyright RIME Developers // Distributed under the BSD License // // 2011-11-27 GONG Chen <[email protected]> // #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <utf8.h> #include <rime/service.h> #include <rime/dict/preset_vocabulary.h> #include <rime/dict/text_db.h> namespace rime { struct VocabularyDb : public TextDb { explicit VocabularyDb(const string& path); an<DbAccessor> cursor; static const TextFormat format; }; VocabularyDb::VocabularyDb(const string& path) : TextDb(path, "vocabulary", VocabularyDb::format) { } static bool rime_vocabulary_entry_parser(const Tsv& row, string* key, string* value) { if (row.size() < 1 || row[0].empty()) { return false; } *key = row[0]; *value = row.size() > 1 ? row[1] : "0"; return true; } static bool rime_vocabulary_entry_formatter(const string& key, const string& value, Tsv* tsv) { //Tsv& row(*tsv); //row.push_back(key); //row.push_back(value); return true; } const TextFormat VocabularyDb::format = { rime_vocabulary_entry_parser, rime_vocabulary_entry_formatter, "Rime vocabulary", }; string PresetVocabulary::DictFilePath() { auto& deployer(Service::instance().deployer()); boost::filesystem::path path(deployer.shared_data_dir); path /= "essay.txt"; if (!boost::filesystem::exists(path)) { path = deployer.user_data_dir; path /= "essay.txt"; } return path.string(); } PresetVocabulary::PresetVocabulary() { db_.reset(new VocabularyDb(DictFilePath())); if (db_ && db_->OpenReadOnly()) { db_->cursor = db_->QueryAll(); } } PresetVocabulary::~PresetVocabulary() { if (db_) db_->Close(); } bool PresetVocabulary::GetWeightForEntry(const string &key, double *weight) { string weight_str; if (!db_ || !db_->Fetch(key, &weight_str)) return false; try { *weight = boost::lexical_cast<double>(weight_str); } catch (...) { return false; } return true; } void PresetVocabulary::Reset() { if (db_ && db_->cursor) db_->cursor->Reset(); } bool PresetVocabulary::GetNextEntry(string *key, string *value) { if (!db_ || !db_->cursor) return false; bool got = false; do { got = db_->cursor->GetNextRecord(key, value); } while (got && !IsQualifiedPhrase(*key, *value)); return got; } bool PresetVocabulary::IsQualifiedPhrase(const string& phrase, const string& weight_str) { if (max_phrase_length_ > 0) { size_t length = utf8::unchecked::distance(phrase.c_str(), phrase.c_str() + phrase.length()); if (static_cast<int>(length) > max_phrase_length_) return false; } if (min_phrase_weight_ > 0.0) { double weight = boost::lexical_cast<double>(weight_str); if (weight < min_phrase_weight_) return false; } return true; } } // namespace rime <|endoftext|>
<commit_before>/** \brief Utility for deleting partial or entire MARC records based on an input list. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <memory> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "MarcUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << progname << " deletion_list input_marc output_marc\n"; std::exit(EXIT_FAILURE); } void ExtractDeletionIds(FILE *const deletion_list, std::unordered_set <std::string> *const title_deletion_ids, std::unordered_set <std::string> *const local_deletion_ids) { unsigned line_no(0); char line[100]; while (std::fgets(line, sizeof(line), deletion_list) != nullptr) { ++line_no; size_t line_length(std::strlen(line)); if (line_length < 13) Error("short line in deletion list file: \"" + std::string(line) + "\"!"); if (line[line_length - 1] == '\n') { line[line_length - 1] = '\0'; --line_length; } if (line[11] == 'A') title_deletion_ids->insert(line + 12); // extract PPN else if (line[11] == '9') { if (line_length != 25) Error("unexpected line length for local entry on line " + std::to_string(line_no) + "!"); local_deletion_ids->insert(std::string(line).substr(12, 9)); // extract ELN } } std::fclose(deletion_list); } int MatchLocalID(const std::unordered_set <std::string> &local_ids, const std::vector <DirectoryEntry> &dir_entries, const std::vector <std::string> &field_data) { for (size_t i(0); i < dir_entries.size(); ++i) { if (dir_entries[i].getTag() != "LOK") continue; const Subfields subfields(field_data[i]); if (not subfields.hasSubfield('0')) continue; const std::string subfield_contents(subfields.getFirstSubfieldValue('0')); if (not StringUtil::StartsWith(subfield_contents, "001 ") or local_ids.find(subfield_contents.substr(4)) == local_ids.end()) continue; return i; } return -1; } class MatchTag { const std::string tag_to_match_; public: explicit MatchTag(const std::string &tag_to_match) : tag_to_match_(tag_to_match) { } bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; } }; void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids, const std::unordered_set <std::string> &local_deletion_ids, FILE *const input, FILE *const output) { unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0); while (MarcUtil::Record record = MarcUtil::Record(input)) { ++total_record_count; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); ssize_t start_local_match; const std::vector<std::string> &fields(record.getFields()); if (title_deletion_ids.find(fields[0]) != title_deletion_ids.end()) { ++deleted_record_count; std::cout << "Deleted record with ID " << fields[0] << '\n'; } else { // Look for local data sets that may need to be deleted. bool modified(false); while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, fields)) != -1) { // We now expect a field "000" before the current "001" field: --start_local_match; if (start_local_match <= 0) Error("weird data structure (1)!"); const Subfields subfields1(fields[start_local_match]); if (not subfields1.hasSubfield('0') or not StringUtil::StartsWith(subfields1.getFirstSubfieldValue('0'), "000 ")) Error("missing or empty local field \"000\"! (EPN: " + fields[start_local_match + 1].substr(8) + ", PPN: " + fields[0] + ")"); // Now we need to find the index one past the end of the local record. This would // be either the "000" field of the next local record or one past the end of the overall // MARC record. bool found_next_000(false); size_t end_local_match(start_local_match + 2); while (end_local_match < fields.size()) { const Subfields subfields2(fields[end_local_match]); if (not subfields2.hasSubfield('0')) Error("weird data (2)!"); if (StringUtil::StartsWith(subfields2.getFirstSubfieldValue('0'), "000 ")) { found_next_000 = true; break; } ++end_local_match; } if (not found_next_000) ++end_local_match; for (ssize_t dir_entry(end_local_match - 1); dir_entry >= start_local_match; --dir_entry) record.deleteField(dir_entry); modified = true; } if (not modified) record.write(output); else { // Only keep records that still have at least one "LOK" tag: if (std::find_if(dir_entries.cbegin(), dir_entries.cend(), MatchTag("LOK")) == dir_entries.cend()) ++deleted_record_count; else { ++modified_record_count; record.write(output); } } } } std::cerr << "Read " << total_record_count << " records.\n"; std::cerr << "Deleted " << deleted_record_count << " records.\n"; std::cerr << "Modified " << modified_record_count << " records.\n"; std::fclose(input); std::fclose(output); } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 4) Usage(); const std::string deletion_list_filename(argv[1]); FILE *deletion_list = std::fopen(deletion_list_filename.c_str(), "rb"); if (deletion_list == nullptr) Error("can't open \"" + deletion_list_filename + "\" for reading!"); std::unordered_set <std::string> title_deletion_ids, local_deletion_ids; ExtractDeletionIds(deletion_list, &title_deletion_ids, &local_deletion_ids); const std::string marc_input_filename(argv[2]); FILE *marc_input = std::fopen(marc_input_filename.c_str(), "rb"); if (marc_input == nullptr) Error("can't open \"" + marc_input_filename + "\" for reading!"); const std::string marc_output_filename(argv[3]); FILE *marc_output = std::fopen(marc_output_filename.c_str(), "wb"); if (marc_output == nullptr) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { ProcessRecords(title_deletion_ids, local_deletion_ids, marc_input, marc_output); } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <commit_msg>Fixed an off-by-two error.<commit_after>/** \brief Utility for deleting partial or entire MARC records based on an input list. * \author Dr. Johannes Ruscheinski ([email protected]) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <iostream> #include <memory> #include <stdexcept> #include <unordered_set> #include <vector> #include <cstdio> #include <cstdlib> #include "MarcUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << progname << " deletion_list input_marc output_marc\n"; std::exit(EXIT_FAILURE); } void ExtractDeletionIds(FILE *const deletion_list, std::unordered_set <std::string> *const title_deletion_ids, std::unordered_set <std::string> *const local_deletion_ids) { unsigned line_no(0); char line[100]; while (std::fgets(line, sizeof(line), deletion_list) != nullptr) { ++line_no; size_t line_length(std::strlen(line)); if (line_length < 13) Error("short line in deletion list file: \"" + std::string(line) + "\"!"); if (line[line_length - 1] == '\n') { line[line_length - 1] = '\0'; --line_length; } if (line[11] == 'A') title_deletion_ids->insert(line + 12); // extract PPN else if (line[11] == '9') { if (line_length != 25) Error("unexpected line length for local entry on line " + std::to_string(line_no) + "!"); local_deletion_ids->insert(std::string(line).substr(12, 9)); // extract ELN } } std::fclose(deletion_list); } int MatchLocalID(const std::unordered_set <std::string> &local_ids, const std::vector <DirectoryEntry> &dir_entries, const std::vector <std::string> &field_data) { for (size_t i(0); i < dir_entries.size(); ++i) { if (dir_entries[i].getTag() != "LOK") continue; const Subfields subfields(field_data[i]); if (not subfields.hasSubfield('0')) continue; const std::string subfield_contents(subfields.getFirstSubfieldValue('0')); if (not StringUtil::StartsWith(subfield_contents, "001 ") or local_ids.find(subfield_contents.substr(4)) == local_ids.end()) continue; return i; } return -1; } class MatchTag { const std::string tag_to_match_; public: explicit MatchTag(const std::string &tag_to_match) : tag_to_match_(tag_to_match) { } bool operator()(const DirectoryEntry &dir_entry) const { return dir_entry.getTag() == tag_to_match_; } }; /** \brief Deletes LOK sections if their pseudo tags are found in "local_deletion_ids" * \return True if at least one local section has been deleted, else false. */ bool DeleteLocalSections(const std::vector<DirectoryEntry> &dir_entries, const std::vector<std::string> &fields, const std::unordered_set <std::string> &local_deletion_ids, MarcUtil::Record * const record) { bool modified(false); ssize_t start_local_match; while ((start_local_match = MatchLocalID(local_deletion_ids, dir_entries, fields)) != -1) { // We now expect a field "000" before the current "001" field. (This is just a sanity check!): --start_local_match; if (start_local_match <= 0) Error("weird data structure (1)!"); const Subfields subfields1(fields[start_local_match]); if (not subfields1.hasSubfield('0') or not StringUtil::StartsWith(subfields1.getFirstSubfieldValue('0'), "000 ")) Error("missing or empty local field \"000\"! (EPN: " + fields[start_local_match + 1].substr(8) + ", PPN: " + fields[0] + ")"); // Now we need to find the index one past the end of the local record. This would // be either the "000" field of the next local record or one past the end of the overall // MARC record. size_t end_local_match(start_local_match + 2); while (end_local_match < fields.size()) { const Subfields subfields2(fields[end_local_match]); if (not subfields2.hasSubfield('0')) Error("weird data structure (2)!"); if (StringUtil::StartsWith(subfields2.getFirstSubfieldValue('0'), "000 ")) { --end_local_match; break; } ++end_local_match; } for (ssize_t dir_entry_index(end_local_match - 1); dir_entry_index >= start_local_match; --dir_entry_index) record->deleteField(dir_entry_index); modified = true; } return modified; } void ProcessRecords(const std::unordered_set <std::string> &title_deletion_ids, const std::unordered_set <std::string> &local_deletion_ids, FILE *const input, FILE *const output) { unsigned total_record_count(0), deleted_record_count(0), modified_record_count(0); while (MarcUtil::Record record = MarcUtil::Record(input)) { ++total_record_count; const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); if (dir_entries[0].getTag() != "001") Error("First field is not \"001\"!"); const std::vector<std::string> &fields(record.getFields()); if (title_deletion_ids.find(fields[0]) != title_deletion_ids.end()) { ++deleted_record_count; std::cout << "Deleted record with ID " << fields[0] << '\n'; } else { // Look for local (LOK) data sets that may need to be deleted. if (not DeleteLocalSections(dir_entries, fields, local_deletion_ids, &record)) record.write(output); else { // Only keep records that still have at least one "LOK" tag: if (std::find_if(dir_entries.cbegin(), dir_entries.cend(), MatchTag("LOK")) == dir_entries.cend()) ++deleted_record_count; else { ++modified_record_count; record.write(output); } } } } std::cerr << "Read " << total_record_count << " records.\n"; std::cerr << "Deleted " << deleted_record_count << " records.\n"; std::cerr << "Modified " << modified_record_count << " records.\n"; std::fclose(input); std::fclose(output); } int main(int argc, char *argv[]) { progname = argv[0]; if (argc != 4) Usage(); const std::string deletion_list_filename(argv[1]); FILE *deletion_list = std::fopen(deletion_list_filename.c_str(), "rb"); if (deletion_list == nullptr) Error("can't open \"" + deletion_list_filename + "\" for reading!"); std::unordered_set <std::string> title_deletion_ids, local_deletion_ids; ExtractDeletionIds(deletion_list, &title_deletion_ids, &local_deletion_ids); const std::string marc_input_filename(argv[2]); FILE *marc_input = std::fopen(marc_input_filename.c_str(), "rb"); if (marc_input == nullptr) Error("can't open \"" + marc_input_filename + "\" for reading!"); const std::string marc_output_filename(argv[3]); FILE *marc_output = std::fopen(marc_output_filename.c_str(), "wb"); if (marc_output == nullptr) Error("can't open \"" + marc_output_filename + "\" for writing!"); try { ProcessRecords(title_deletion_ids, local_deletion_ids, marc_input, marc_output); } catch (const std::exception &e) { Error("Caught exception: " + std::string(e.what())); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved. */ #define __STDC_CONSTANT_MACROS #include "monarch/rt/System.h" // include NULL #include <stddef.h> #ifdef WIN32 #include <windows.h> #elif MACOS #include <sys/param.h> #include <sys/sysctl.h> #else #include <unistd.h> #endif using namespace monarch::rt; uint64_t System::getCurrentMilliseconds() { uint64_t rval = 0; // get the current time of day struct timeval now; gettimeofday(&now, NULL); // get total number of milliseconds // 1 millisecond is 1000 microseconds rval = now.tv_sec * UINT64_C(1000) + (uint64_t)(now.tv_usec / 1000.0); return rval; } uint32_t System::getCpuCoreCount() { #ifdef WIN32 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #elif MACOS int nm[2]; size_t len = 4; uint32_t count; // names to look up nm[0] = CTL_HW; nm[1] = HW_AVAILCPU; sysctl(nm, 2, &count, &len, NULL, 0); // handle error case if(count < 1) { // look up HW_NCPU instead nm[1] = HW_NCPU; sysctl(nm, 2, &count, &len, NULL, 0); if(count < 1) { // default to 1 cpu/core count = 1; } } return count; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } <commit_msg>Added note about using clock_gettime.<commit_after>/* * Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved. */ #define __STDC_CONSTANT_MACROS #include "monarch/rt/System.h" // include NULL #include <stddef.h> #ifdef WIN32 #include <windows.h> #elif MACOS #include <sys/param.h> #include <sys/sysctl.h> #else #include <unistd.h> #endif using namespace monarch::rt; uint64_t System::getCurrentMilliseconds() { uint64_t rval = 0; // FIXME: consider using clock_gettime(), at least on *nix // get the current time of day struct timeval now; gettimeofday(&now, NULL); // get total number of milliseconds // 1 millisecond is 1000 microseconds rval = now.tv_sec * UINT64_C(1000) + (uint64_t)(now.tv_usec / 1000.0); return rval; } uint32_t System::getCpuCoreCount() { #ifdef WIN32 SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #elif MACOS int nm[2]; size_t len = 4; uint32_t count; // names to look up nm[0] = CTL_HW; nm[1] = HW_AVAILCPU; sysctl(nm, 2, &count, &len, NULL, 0); // handle error case if(count < 1) { // look up HW_NCPU instead nm[1] = HW_NCPU; sysctl(nm, 2, &count, &len, NULL, 0); if(count < 1) { // default to 1 cpu/core count = 1; } } return count; #else return sysconf(_SC_NPROCESSORS_ONLN); #endif } <|endoftext|>
<commit_before>// 最適化の有無で結果が変わるテストと // デバッガから実行したかどうかで結果が変わるテスト #include <cstdint> #include <algorithm> #include <atomic> #include <future> #include <iostream> #include <string> #include <thread> #include <vector> #include <gtest/gtest.h> #include <windows.h> #include "cFriendsCommon.h" #include "cppFriends.hpp" class MyCounter { public: using Number = int; explicit MyCounter(Number count) : count_(count) {} virtual ~MyCounter(void) = default; void Run(void) { // コンパイラが最適化すれば、足した結果をまとめてnonVolatileCounter_に格納する可能性がある for(Number i = 0; i < count_; ++i) { ++nonVolatileCounter_; } // volatileはatomicではないので競合する可能性がある for(Number i = 0; i < count_; ++i) { ++volatileCounter_; ++atomicCounter_; } } static void Reset(void) { nonVolatileCounter_ = 0; volatileCounter_ = 0; atomicCounter_ = 0; } static Number GetValue(void) { return nonVolatileCounter_; } static Number GetVolatileValue(void) { return volatileCounter_; } static Number GetAtomicValue(void) { return atomicCounter_; } private: Number count_ {0}; static Number nonVolatileCounter_; static volatile Number volatileCounter_; static std::atomic<Number> atomicCounter_; }; MyCounter::Number MyCounter::nonVolatileCounter_ {0}; volatile MyCounter::Number MyCounter::volatileCounter_ {0}; std::atomic<MyCounter::Number> MyCounter::atomicCounter_ {0}; class TestMyCounter : public ::testing::Test { protected: using SizeOfThreads = int; virtual void SetUp() override { MyCounter::Reset(); hardwareConcurrency_ = static_cast<decltype(hardwareConcurrency_)>(std::thread::hardware_concurrency()); processAffinityMask_ = 0; systemAffinityMask_ = 0; // https://msdn.microsoft.com/ja-jp/library/cc429135.aspx // https://msdn.microsoft.com/ja-jp/library/windows/desktop/ms683213(v=vs.85).aspx // で引数の型が異なる。下が正しい。 if (!GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask_, &systemAffinityMask_)) { // 取得に失敗したらシングルコアとみなす std::cout << "GetProcessAffinityMask failed\n"; processAffinityMask_ = 1; systemAffinityMask_ = 1; } } virtual void TearDown() override { if (!SetProcessAffinityMask(GetCurrentProcess(), processAffinityMask_)) { std::cout << "Restoring ProcessAffinityMask failed\n"; } else { std::cout << "ProcessAffinityMask restored\n"; } } void runCounters(SizeOfThreads sizeOfThreads, MyCounter::Number count) { std::vector<std::unique_ptr<MyCounter>> counterSet; std::vector<std::future<void>> futureSet; // 並行処理を作って、後で実行できるようにする for(decltype(sizeOfThreads) index = 0; index < sizeOfThreads; ++index) { std::unique_ptr<MyCounter> pCounter(new MyCounter(count)); MyCounter* pRawCounter = pCounter.get(); futureSet.push_back(std::async(std::launch::async, [=](void) -> void { pRawCounter->Run(); })); counterSet.push_back(std::move(pCounter)); } // 並行して評価して、結果がそろうのを待つ for(auto& f : futureSet) { f.get(); } std::cout << "MyCounter::GetValue() = " << MyCounter::GetValue() << "\n"; std::cout << "MyCounter::GetVolatileValue() = " << MyCounter::GetVolatileValue() << "\n"; std::cout << "MyCounter::GetAtomicValue() = " << MyCounter::GetAtomicValue() << "\n"; return; } class IntBox { public: using Data = int; explicit IntBox(Data n) : var_(n), mvar_(n), cvar_(n) {} virtual ~IntBox() = default; Data Get(void) const { return var_; } Data GetMutableVar(void) const { return mvar_; } Data GetConstVar(void) const { return cvar_; } void Set(Data n) { var_ = n; } void SetMutableVar(Data n) const { mvar_ = n; } // コンパイラはメンバ変数が不変だとは断定できないので、動作するだろう // Exceptional C++ Style 項目24を参照 void Overwrite1(Data n) const { const_cast<IntBox*>(this)->var_ = n; } void Overwrite2(Data n) const { *(const_cast<Data*>(&var_)) = n; *(const_cast<Data*>(&cvar_)) = n; } private: Data var_; mutable Data mvar_; const Data cvar_; }; SizeOfThreads hardwareConcurrency_ {0}; private: DWORD_PTR processAffinityMask_ {1}; DWORD_PTR systemAffinityMask_ {1}; }; TEST_F(TestMyCounter, MultiCore) { if (hardwareConcurrency_ <= 1) { return; } const MyCounter::Number count = 4000000; // 十分大きくする SizeOfThreads sizeOfThreads = hardwareConcurrency_; std::cout << "Run on " << sizeOfThreads << " threads\n"; runCounters(sizeOfThreads, count); MyCounter::Number expected = static_cast<decltype(expected)>(sizeOfThreads) * count; // 最適化しなければこうはならない #ifdef CPPFRIENDS_NO_OPTIMIZATION // 偶然割り切れることもあり得なくもないが EXPECT_TRUE(MyCounter::GetValue() % count); EXPECT_GT(expected, MyCounter::GetValue()); #else EXPECT_FALSE(MyCounter::GetValue() % count); #if (__GNUC__ < 6) EXPECT_EQ(expected, MyCounter::GetValue()); // GCC6では物理コア数分しか増えない // 2コア4論理スレッドなら、4倍ではなく2倍になるということ // 競合動作なのだから、そもそも正しいexpectationは書けない #endif #endif // マルチコアなら競合が起きるので成り立つはずだが、条件次第では競合しない可能性もある EXPECT_GT(expected, MyCounter::GetVolatileValue()); // これは常に成り立つはず EXPECT_EQ(expected, MyCounter::GetAtomicValue()); } TEST_F(TestMyCounter, SingleCore) { /* 使うCPUを1個に固定する */ DWORD_PTR procMask = 1; if (!SetProcessAffinityMask(GetCurrentProcess(), procMask)) { std::cout << "SetProcessAffinityMask failed\n"; } SizeOfThreads sizeOfThreads = std::max(hardwareConcurrency_, 4); const MyCounter::Number count = 4000000; std::cout << "Run on a single thread\n"; runCounters(sizeOfThreads, count); MyCounter::Number expected = static_cast<decltype(expected)>(sizeOfThreads) * count; EXPECT_EQ(expected, MyCounter::GetValue()); // シングルコアなら競合しない EXPECT_EQ(expected, MyCounter::GetVolatileValue()); // これは常に成り立つはず EXPECT_EQ(expected, MyCounter::GetAtomicValue()); } TEST_F(TestMyCounter, ConstMemberFunction) { IntBox::Data n = 1; IntBox box {n}; EXPECT_EQ(n, box.Get()); EXPECT_EQ(n, box.GetMutableVar()); EXPECT_EQ(n, box.GetConstVar()); ++n; box.Set(n); EXPECT_EQ(n, box.Get()); ++n; box.SetMutableVar(n); EXPECT_EQ(n, box.GetMutableVar()); ++n; box.Overwrite1(n); EXPECT_EQ(n, box.Get()); ++n; box.Overwrite2(n); EXPECT_EQ(n, box.Get()); EXPECT_EQ(n, box.GetConstVar()); } class TestShifter : public ::testing::Test{}; TEST_F(TestShifter, All) { constexpr int32_t var = 2; int32_t result = -1; constexpr int32_t expected = var << 3; // 35回のはずが3回しかシフトされないのは、シフト回数がCLレジスタの値 mod 32だから Shift35ForInt32Asm(result, var); #ifdef CPPFRIENDS_NO_OPTIMIZATION // 0でもexpectedでもない値が返る // EXPECT_EQ(expected, result); EXPECT_EQ(expected, Shift35ForInt32(var)); #else // N-bit整数をNビット以上シフトしたときの値は未定義なので、 // コンパイラは35回シフトして0になったと考えるが、CPUの動作とは一致しない EXPECT_EQ(expected, result); EXPECT_EQ(0, Shift35ForInt32(var)); #endif EXPECT_EQ(expected, ShiftForInt32(var, CPPFRIENDS_SHIFT_COUNT)); } namespace { std::atomic<bool> g_breakPointHandled; LONG CALLBACK MyVectoredHandler(PEXCEPTION_POINTERS pExceptionInfo) { if (pExceptionInfo && pExceptionInfo->ContextRecord && pExceptionInfo->ExceptionRecord && pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) { // 次の命令に移る #ifdef __x86_64__ pExceptionInfo->ContextRecord->Rip++; #else pExceptionInfo->ContextRecord->Eip++; #endif g_breakPointHandled = true; return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } } class TestDebuggerDetecter : public ::testing::Test { protected: virtual void SetUp() override { g_breakPointHandled = false; } }; TEST_F(TestDebuggerDetecter, Trap) { EXPECT_FALSE(g_breakPointHandled.load()); // ハンドラを登録する。最後に呼ばれるようにする。 PVOID handler = ::AddVectoredExceptionHandler(0, MyVectoredHandler); ASSERT_TRUE(handler); // Int3を発生させる ::DebugBreak(); // ハンドラを元に戻す ::RemoveVectoredExceptionHandler(handler); handler = 0; // デバッガから起動したときには、ハンドラに制御が渡らないのでFALSEになる EXPECT_TRUE(g_breakPointHandled.load()); } class TestOverwriteVtable : public ::testing::Test {}; TEST_F(TestOverwriteVtable, Standard) { std::unique_ptr<DynamicObjectMemFunc> pObj(new SubDynamicObjectMemFunc(2,3)); std::ostringstream os; pObj->Print(os); EXPECT_EQ("23", os.str()); ExtraMemFunc ex; ex.Print(os); EXPECT_EQ("23Extra", os.str()); } #if 0 TEST_F(TestOverwriteVtable, Overwrite) { std::unique_ptr<DynamicObjectMemFunc> pObj(new SubDynamicObjectMemFunc(2,3)); std::ostringstream os; pObj->Print(os); auto pBase = reinterpret_cast<size_t**>(pObj.get()); auto pVtable = *pBase; // 本当はC++では、unionを使ったキャストはできない union FuncPtr{ size_t addr; decltype(&ExtraMemFunc::Print) f; }; // (gdb) info address ExtraMemFunc::Print // アドレスはコンパイルすると変わる // &ExtraMemFunc::Printを代入するととても小さい数字(25)が入る FuncPtr fptr = {0x1004038b2ull}; // 0:デストラクタ, 1:Clear, 2:Print pVtable[1] = fptr.addr; // というようには、残念ながら書き換えることはできない // (gdb) x/4gx pBase // (gdb) x/4xg pVtable // (gdb) maintenance info sections // [2] 0x100433000->0x100438f34 at 0x00030e00: .rdata ALLOC LOAD READONLY DATA HAS_CONTENTS // つまりvtableは書き換えられない pObj->Print(os); EXPECT_EQ("23Extra", os.str()); } #endif /* Local Variables: mode: c++ coding: utf-8-dos tab-width: nil c-file-style: "stroustrup" End: */ <commit_msg>Produce a round-off error<commit_after>// 最適化の有無で結果が変わるテストと // デバッガから実行したかどうかで結果が変わるテスト #include <cstdint> #include <algorithm> #include <atomic> #include <future> #include <iostream> #include <string> #include <thread> #include <vector> #include <gtest/gtest.h> #include <windows.h> #include "cFriendsCommon.h" #include "cppFriends.hpp" class MyCounter { public: using Number = int; explicit MyCounter(Number count) : count_(count) {} virtual ~MyCounter(void) = default; void Run(void) { // コンパイラが最適化すれば、足した結果をまとめてnonVolatileCounter_に格納する可能性がある for(Number i = 0; i < count_; ++i) { ++nonVolatileCounter_; } // volatileはatomicではないので競合する可能性がある for(Number i = 0; i < count_; ++i) { ++volatileCounter_; ++atomicCounter_; } } static void Reset(void) { nonVolatileCounter_ = 0; volatileCounter_ = 0; atomicCounter_ = 0; } static Number GetValue(void) { return nonVolatileCounter_; } static Number GetVolatileValue(void) { return volatileCounter_; } static Number GetAtomicValue(void) { return atomicCounter_; } private: Number count_ {0}; static Number nonVolatileCounter_; static volatile Number volatileCounter_; static std::atomic<Number> atomicCounter_; }; MyCounter::Number MyCounter::nonVolatileCounter_ {0}; volatile MyCounter::Number MyCounter::volatileCounter_ {0}; std::atomic<MyCounter::Number> MyCounter::atomicCounter_ {0}; class TestMyCounter : public ::testing::Test { protected: using SizeOfThreads = int; virtual void SetUp() override { MyCounter::Reset(); hardwareConcurrency_ = static_cast<decltype(hardwareConcurrency_)>(std::thread::hardware_concurrency()); processAffinityMask_ = 0; systemAffinityMask_ = 0; // https://msdn.microsoft.com/ja-jp/library/cc429135.aspx // https://msdn.microsoft.com/ja-jp/library/windows/desktop/ms683213(v=vs.85).aspx // で引数の型が異なる。下が正しい。 if (!GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask_, &systemAffinityMask_)) { // 取得に失敗したらシングルコアとみなす std::cout << "GetProcessAffinityMask failed\n"; processAffinityMask_ = 1; systemAffinityMask_ = 1; } } virtual void TearDown() override { if (!SetProcessAffinityMask(GetCurrentProcess(), processAffinityMask_)) { std::cout << "Restoring ProcessAffinityMask failed\n"; } else { std::cout << "ProcessAffinityMask restored\n"; } } void runCounters(SizeOfThreads sizeOfThreads, MyCounter::Number count) { std::vector<std::unique_ptr<MyCounter>> counterSet; std::vector<std::future<void>> futureSet; // 並行処理を作って、後で実行できるようにする for(decltype(sizeOfThreads) index = 0; index < sizeOfThreads; ++index) { std::unique_ptr<MyCounter> pCounter(new MyCounter(count)); MyCounter* pRawCounter = pCounter.get(); futureSet.push_back(std::async(std::launch::async, [=](void) -> void { pRawCounter->Run(); })); counterSet.push_back(std::move(pCounter)); } // 並行して評価して、結果がそろうのを待つ for(auto& f : futureSet) { f.get(); } std::cout << "MyCounter::GetValue() = " << MyCounter::GetValue() << "\n"; std::cout << "MyCounter::GetVolatileValue() = " << MyCounter::GetVolatileValue() << "\n"; std::cout << "MyCounter::GetAtomicValue() = " << MyCounter::GetAtomicValue() << "\n"; return; } class IntBox { public: using Data = int; explicit IntBox(Data n) : var_(n), mvar_(n), cvar_(n) {} virtual ~IntBox() = default; Data Get(void) const { return var_; } Data GetMutableVar(void) const { return mvar_; } Data GetConstVar(void) const { return cvar_; } void Set(Data n) { var_ = n; } void SetMutableVar(Data n) const { mvar_ = n; } // コンパイラはメンバ変数が不変だとは断定できないので、動作するだろう // Exceptional C++ Style 項目24を参照 void Overwrite1(Data n) const { const_cast<IntBox*>(this)->var_ = n; } void Overwrite2(Data n) const { *(const_cast<Data*>(&var_)) = n; *(const_cast<Data*>(&cvar_)) = n; } private: Data var_; mutable Data mvar_; const Data cvar_; }; SizeOfThreads hardwareConcurrency_ {0}; private: DWORD_PTR processAffinityMask_ {1}; DWORD_PTR systemAffinityMask_ {1}; }; TEST_F(TestMyCounter, MultiCore) { if (hardwareConcurrency_ <= 1) { return; } const MyCounter::Number count = 4000000; // 十分大きくする SizeOfThreads sizeOfThreads = hardwareConcurrency_; std::cout << "Run on " << sizeOfThreads << " threads\n"; runCounters(sizeOfThreads, count); MyCounter::Number expected = static_cast<decltype(expected)>(sizeOfThreads) * count; // 最適化しなければこうはならない #ifdef CPPFRIENDS_NO_OPTIMIZATION // 偶然割り切れることもあり得なくもないが EXPECT_TRUE(MyCounter::GetValue() % count); EXPECT_GT(expected, MyCounter::GetValue()); #else EXPECT_FALSE(MyCounter::GetValue() % count); #if (__GNUC__ < 6) EXPECT_EQ(expected, MyCounter::GetValue()); // GCC6では物理コア数分しか増えない // 2コア4論理スレッドなら、4倍ではなく2倍になるということ // 競合動作なのだから、そもそも正しいexpectationは書けない #endif #endif // マルチコアなら競合が起きるので成り立つはずだが、条件次第では競合しない可能性もある EXPECT_GT(expected, MyCounter::GetVolatileValue()); // これは常に成り立つはず EXPECT_EQ(expected, MyCounter::GetAtomicValue()); } TEST_F(TestMyCounter, SingleCore) { /* 使うCPUを1個に固定する */ DWORD_PTR procMask = 1; if (!SetProcessAffinityMask(GetCurrentProcess(), procMask)) { std::cout << "SetProcessAffinityMask failed\n"; } SizeOfThreads sizeOfThreads = std::max(hardwareConcurrency_, 4); const MyCounter::Number count = 4000000; std::cout << "Run on a single thread\n"; runCounters(sizeOfThreads, count); MyCounter::Number expected = static_cast<decltype(expected)>(sizeOfThreads) * count; EXPECT_EQ(expected, MyCounter::GetValue()); // シングルコアなら競合しない EXPECT_EQ(expected, MyCounter::GetVolatileValue()); // これは常に成り立つはず EXPECT_EQ(expected, MyCounter::GetAtomicValue()); } TEST_F(TestMyCounter, ConstMemberFunction) { IntBox::Data n = 1; IntBox box {n}; EXPECT_EQ(n, box.Get()); EXPECT_EQ(n, box.GetMutableVar()); EXPECT_EQ(n, box.GetConstVar()); ++n; box.Set(n); EXPECT_EQ(n, box.Get()); ++n; box.SetMutableVar(n); EXPECT_EQ(n, box.GetMutableVar()); ++n; box.Overwrite1(n); EXPECT_EQ(n, box.Get()); ++n; box.Overwrite2(n); EXPECT_EQ(n, box.Get()); EXPECT_EQ(n, box.GetConstVar()); } class TestShifter : public ::testing::Test{}; TEST_F(TestShifter, All) { constexpr int32_t var = 2; int32_t result = -1; constexpr int32_t expected = var << 3; // 35回のはずが3回しかシフトされないのは、シフト回数がCLレジスタの値 mod 32だから Shift35ForInt32Asm(result, var); #ifdef CPPFRIENDS_NO_OPTIMIZATION // 0でもexpectedでもない値が返る // EXPECT_EQ(expected, result); EXPECT_EQ(expected, Shift35ForInt32(var)); #else // N-bit整数をNビット以上シフトしたときの値は未定義なので、 // コンパイラは35回シフトして0になったと考えるが、CPUの動作とは一致しない EXPECT_EQ(expected, result); EXPECT_EQ(0, Shift35ForInt32(var)); #endif EXPECT_EQ(expected, ShiftForInt32(var, CPPFRIENDS_SHIFT_COUNT)); } namespace { std::atomic<bool> g_breakPointHandled; LONG CALLBACK MyVectoredHandler(PEXCEPTION_POINTERS pExceptionInfo) { if (pExceptionInfo && pExceptionInfo->ContextRecord && pExceptionInfo->ExceptionRecord && pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) { // 次の命令に移る #ifdef __x86_64__ pExceptionInfo->ContextRecord->Rip++; #else pExceptionInfo->ContextRecord->Eip++; #endif g_breakPointHandled = true; return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } } class TestDebuggerDetecter : public ::testing::Test { protected: virtual void SetUp() override { g_breakPointHandled = false; } }; TEST_F(TestDebuggerDetecter, Trap) { EXPECT_FALSE(g_breakPointHandled.load()); // ハンドラを登録する。最後に呼ばれるようにする。 PVOID handler = ::AddVectoredExceptionHandler(0, MyVectoredHandler); ASSERT_TRUE(handler); // Int3を発生させる ::DebugBreak(); // ハンドラを元に戻す ::RemoveVectoredExceptionHandler(handler); handler = 0; // デバッガから起動したときには、ハンドラに制御が渡らないのでFALSEになる EXPECT_TRUE(g_breakPointHandled.load()); } class TestOverwriteVtable : public ::testing::Test {}; TEST_F(TestOverwriteVtable, Standard) { std::unique_ptr<DynamicObjectMemFunc> pObj(new SubDynamicObjectMemFunc(2,3)); std::ostringstream os; pObj->Print(os); EXPECT_EQ("23", os.str()); ExtraMemFunc ex; ex.Print(os); EXPECT_EQ("23Extra", os.str()); } #if 0 TEST_F(TestOverwriteVtable, Overwrite) { std::unique_ptr<DynamicObjectMemFunc> pObj(new SubDynamicObjectMemFunc(2,3)); std::ostringstream os; pObj->Print(os); auto pBase = reinterpret_cast<size_t**>(pObj.get()); auto pVtable = *pBase; // 本当はC++では、unionを使ったキャストはできない union FuncPtr{ size_t addr; decltype(&ExtraMemFunc::Print) f; }; // (gdb) info address ExtraMemFunc::Print // アドレスはコンパイルすると変わる // &ExtraMemFunc::Printを代入するととても小さい数字(25)が入る FuncPtr fptr = {0x1004038b2ull}; // 0:デストラクタ, 1:Clear, 2:Print pVtable[1] = fptr.addr; // というようには、残念ながら書き換えることはできない // (gdb) x/4gx pBase // (gdb) x/4xg pVtable // (gdb) maintenance info sections // [2] 0x100433000->0x100438f34 at 0x00030e00: .rdata ALLOC LOAD READONLY DATA HAS_CONTENTS // つまりvtableは書き換えられない pObj->Print(os); EXPECT_EQ("23Extra", os.str()); } #endif class TestDoublePrecision : public ::testing::Test{}; TEST_F(TestDoublePrecision, Round) { const double one = 1.0; double divider = 49.0; auto oneThird = one / divider; auto nearOne = oneThird * divider; // ASSERT_EQ(1.0, nearOne); } /* Local Variables: mode: c++ coding: utf-8-dos tab-width: nil c-file-style: "stroustrup" End: */ <|endoftext|>
<commit_before>// uzrect_Mollerup.C --- A 2D solution to Richard's equation in a rect. grid. // // Copyright 2006 Mikkel Mollerup and KVL. // // This file is part of Daisy. // // Daisy is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // Daisy 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 Public License for more details. // // You should have received a copy of the GNU Lesser Public License // along with Daisy; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "uzrect.h" #include "geometry_rect.h" #include "soil_water.h" #include "groundwater.h" #include "surface.h" #include "syntax.h" #include "alist.h" #include "mathlib.h" #include "assertion.h" #include <sstream> struct UZRectMollerup : public UZRect { // Parameters. // Interface. void tick (const GeometryRect&, const Soil&, SoilWater&, const SoilHeat&, const Surface&, const Groundwater&, double dt, Treelog&); // Internal functions. void lowerboundary () void upperboundary () // Create and Destroy. void has_macropores (bool); static void load_syntax (Syntax& syntax, AttributeList& alist); UZRectMollerup (Block& al); ~UZRectMollerup (); }; void UZRectMollerup::tick (const GeometryRect& geo, const Soil& soil, SoilWater& soil_water, const SoilHeat& soil_heat, const Surface& surface, const Groundwater& groundwater, const double dt, Treelog& msg) { #if 0 const size_t edge_size = geo.edge_size (); // number of edges const size_t edge_rows = geo.edge_rows (); // number of edge rows const size_t cell_size = geo.cell_size (); // number of cells const size_t cell_rows = geo.cell_rows (); // number of cell rows const size_t cell_columns = geo.cell_columns (); // number of cell columns // Insert magic here. std::vector<double> Theta (cell_size); // water content std::vector<double> h (cell_size); // matrix pressure std::vector<double> h_ice (cell_size); // std::vector<double> S (cell_size); // sink term std::vector<double> dx (cell_size); // width of cells std::vector<double> dz (cell_size); // height of cells std::vector<double> T (cell_size); // temperature std::vector<double> K (cell_size); // hydraulic conductivity std::vector<double> Cw (cell_size); // specific water capacity std::matrix<double> Dm_mat (cell_size,0.0); // upper Dir bc std::vector<double> Dm_vec (cell_size,0.0); // upper Dir bc std::vector<double> Gm (cell_size,0.0); // upper Dir bc std::vector<double> B (cell_size,0.0); // upper Neu bc // make vectors for (size_t cell = 0; cell !=cell_size ; ++cell) { Theta[cell] = soil_water.Theta (cell); h[cell] = soil_water.h (cell); h_ice[cell] = soil_water.h_ice (cell); S[cell] = soil_water.S_sum (cell); dx[cell] = geo.dx (cell); dz[cell] = geo.dz (cell); T[cell] = soil_heat.T (cell); K[cell] = soil.K (cell, h[cell], h_ice[cell], T[cell]); Cw[cell] = soil.Cw2 (cell, h[cell], h_ice[cell]); } // check gaussj.h and gaussj.C to see how it works... // ms = matrixsolve GaussJordan ms (cell_size); // initialize // void set_value (int row, double); // double get_value (int row) const; // void set_entry (int row, int column, double); // double get_entry (int row, int column) const; // inline double operator() (int row, int column) const // { return get_entry (row, column); } // void solve (); // double result (int row) const; // GaussJordan (int s); #endif } void UZRectMollerup::lowerboundary (std::matrix<double>& Dm_mat std::vector<double>& Dm_vec std::vector<double>& Gm std::vector<double>& B const size_t cell_size, const Groundwater::bottom_t boundtype const std::vector<double>& K ) { // Initialise vectors+matrices for (size_t i = 0; i !=cell_size ; ++i) { for (size_t j = 0; j !=cell_size ; ++j) { Dm_mat[i,j] = 0.0; } Dm_vec[i] = 0.0; Gm[i] = 0.0; B[i] = 0.0; } switch boundtype case 'pressure' case 'lysimeter' case 'forced_flux' case 'free_drainage' if neumanntype } void UZRectMollerup::upperboundary () {} void UZRectMollerup::has_macropores (const bool) { /* Ignore for now. */ } void UZRectMollerup::load_syntax (Syntax&, AttributeList&) { } UZRectMollerup::UZRectMollerup (Block& al) : UZRect (al) { } UZRectMollerup::~UZRectMollerup () { } const AttributeList& UZRect::default_model () { static AttributeList alist; if (!alist.check ("type")) { Syntax dummy; UZRectMollerup::load_syntax (dummy, alist); alist.add ("type", "Mollerup"); } return alist; } static struct UZRectMollerupSyntax { static UZRect& make (Block& al) { return *new UZRectMollerup (al); } UZRectMollerupSyntax () { Syntax& syntax = *new Syntax (); AttributeList& alist = *new AttributeList (); alist.add ("description", "\ A finite volume solution to matrix water transport.\n\ See Mollerup, 2007 for details."); UZRectMollerup::load_syntax (syntax, alist); Librarian<UZRect>::add_type ("Mollerup", alist, syntax, &make); } } UZRectMollerup_syntax; // uzrect_Mollerup.C ends here. <commit_msg>*** empty log message ***<commit_after>// uzrect_Mollerup.C --- A 2D solution to Richard's equation in a rect. grid. // // Copyright 2006 Mikkel Mollerup and KVL. // // This file is part of Daisy. // // Daisy is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser Public License as published by // the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // Daisy 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 Public License for more details. // // You should have received a copy of the GNU Lesser Public License // along with Daisy; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "uzrect.h" #include "geometry_rect.h" #include "soil_water.h" #include "groundwater.h" #include "surface.h" #include "syntax.h" #include "alist.h" #include "mathlib.h" #include "assertion.h" #include <sstream> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> using boost::numeric::ublas::matrix; struct UZRectMollerup : public UZRect { // Parameters. // Interface. void tick (const GeometryRect&, const Soil&, SoilWater&, const SoilHeat&, const Surface&, const Groundwater&, double dt, Treelog&); // Internal functions. void lowerboundary (matrix<double>& Dm_mat, std::vector<double>& Dm_vec, std::vector<double>& Gm, std::vector<double>& B, const size_t cell_size, const Groundwater::bottom_t boundtype, const std::vector<double>& K); void upperboundary (); void diffusion (const GeometryRect&); void gravitation (); // Create and Destroy. void has_macropores (bool); static void load_syntax (Syntax& syntax, AttributeList& alist); UZRectMollerup (Block& al); ~UZRectMollerup (); }; void UZRectMollerup::tick (const GeometryRect& geo, const Soil& soil, SoilWater& soil_water, const SoilHeat& soil_heat, const Surface& surface, const Groundwater& groundwater, const double dt, Treelog& msg) { #if 0 const size_t edge_size = geo.edge_size (); // number of edges const size_t edge_rows = geo.edge_rows (); // number of edge rows const size_t cell_size = geo.cell_size (); // number of cells const size_t cell_rows = geo.cell_rows (); // number of cell rows const size_t cell_columns = geo.cell_columns (); // number of cell columns // Insert magic here. std::vector<double> Theta (cell_size); // water content std::vector<double> h (cell_size); // matrix pressure std::vector<double> h_ice (cell_size); // std::vector<double> S (cell_size); // sink term std::vector<double> T (cell_size); // temperature std::vector<double> K (cell_size); // hydraulic conductivity std::vector<double> Cw (cell_size); // specific water capacity std::matrix<double> Dm_mat (cell_size,0.0); // upper Dir bc std::vector<double> Dm_vec (cell_size,0.0); // upper Dir bc std::vector<double> Gm (cell_size,0.0); // upper Dir bc std::vector<double> B (cell_size,0.0); // upper Neu bc // make vectors for (size_t cell = 0; cell !=cell_size ; ++cell) { Theta[cell] = soil_water.Theta (cell); h[cell] = soil_water.h (cell); h_ice[cell] = soil_water.h_ice (cell); S[cell] = soil_water.S_sum (cell); dx[cell] = geo.dx (cell); dz[cell] = geo.dz (cell); T[cell] = soil_heat.T (cell); K[cell] = soil.K (cell, h[cell], h_ice[cell], T[cell]); Cw[cell] = soil.Cw2 (cell, h[cell], h_ice[cell]); } // check gaussj.h and gaussj.C to see how it works... // ms = matrixsolve GaussJordan ms (cell_size); // initialize // void set_value (int row, double); // double get_value (int row) const; // void set_entry (int row, int column, double); // double get_entry (int row, int column) const; // inline double operator() (int row, int column) const // { return get_entry (row, column); } // void solve (); // double result (int row) const; // GaussJordan (int s); #endif } void UZRectMollerup::lowerboundary (matrix<double>& Dm_mat, std::vector<double>& Dm_vec, std::vector<double>& Gm, std::vector<double>& B, const size_t cell_size, const Groundwater::bottom_t boundtype, const std::vector<double>& K) { #if 0 // Initialise vectors+matrices for (size_t i = 0; i !=cell_size ; ++i) { for (size_t j = 0; j !=cell_size ; ++j) { Dm_mat[i,j] = 0.0; } Dm_vec[i] = 0.0; Gm[i] = 0.0; B[i] = 0.0; } switch boundtype case 'pressure' case 'lysimeter' case 'forced_flux' case 'free_drainage' if neumanntype #endif } void UZRectMollerup::upperboundary () {} void UZRectMollerup::diffusion (const GeometryRect& geo) { const size_t cell_size = geo.cell_size (); // number of cells //Initialize diffusive matrix matrix<double> diff (cell_size, cell_size); //zeros???? } void UZRectMollerup::gravitation () {} void UZRectMollerup::has_macropores (const bool) { /* Ignore for now. */ } void UZRectMollerup::load_syntax (Syntax&, AttributeList&) { } UZRectMollerup::UZRectMollerup (Block& al) : UZRect (al) { } UZRectMollerup::~UZRectMollerup () { } const AttributeList& UZRect::default_model () { static AttributeList alist; if (!alist.check ("type")) { Syntax dummy; UZRectMollerup::load_syntax (dummy, alist); alist.add ("type", "Mollerup"); } return alist; } static struct UZRectMollerupSyntax { static UZRect& make (Block& al) { return *new UZRectMollerup (al); } UZRectMollerupSyntax () { Syntax& syntax = *new Syntax (); AttributeList& alist = *new AttributeList (); alist.add ("description", "\ A finite volume solution to matrix water transport.\n\ See Mollerup, 2007 for details."); UZRectMollerup::load_syntax (syntax, alist); Librarian<UZRect>::add_type ("Mollerup", alist, syntax, &make); } } UZRectMollerup_syntax; // uzrect_Mollerup.C ends here. <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "cql3/abstract_marker.hh" #include "cql3/update_parameters.hh" #include "cql3/operation.hh" #include "cql3/values.hh" #include "cql3/term.hh" #include "core/shared_ptr.hh" namespace cql3 { /** * Static helper methods and classes for constants. */ class constants { public: #if 0 private static final Logger logger = LoggerFactory.getLogger(Constants.class); #endif public: enum class type { STRING, INTEGER, UUID, FLOAT, BOOLEAN, HEX }; /** * A constant value, i.e. a ByteBuffer. */ class value : public terminal { public: cql3::raw_value _bytes; value(cql3::raw_value bytes_) : _bytes(std::move(bytes_)) {} virtual cql3::raw_value get(const query_options& options) override { return _bytes; } virtual cql3::raw_value_view bind_and_get(const query_options& options) override { return _bytes.to_view(); } virtual sstring to_string() const override { return to_hex(*_bytes); } }; class null_literal final : public term::raw { private: class null_value final : public value { public: null_value() : value(cql3::raw_value::make_null()) {} virtual ::shared_ptr<terminal> bind(const query_options& options) override { return {}; } virtual sstring to_string() const override { return "null"; } }; static thread_local const ::shared_ptr<terminal> NULL_VALUE; public: virtual ::shared_ptr<term> prepare(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver) override { if (!is_assignable(test_assignment(db, keyspace, receiver))) { throw exceptions::invalid_request_exception("Invalid null value for counter increment/decrement"); } return NULL_VALUE; } virtual assignment_testable::test_result test_assignment(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver) override { return receiver->type->is_counter() ? assignment_testable::test_result::NOT_ASSIGNABLE : assignment_testable::test_result::WEAKLY_ASSIGNABLE; } virtual sstring to_string() const override { return "null"; } }; static thread_local const ::shared_ptr<term::raw> NULL_LITERAL; class literal : public term::raw { private: const type _type; const sstring _text; public: literal(type type_, sstring text) : _type{type_} , _text{text} { } static ::shared_ptr<literal> string(sstring text) { // This is a workaround for antlr3 not distinguishing between // calling in lexer setText() with an empty string and not calling // setText() at all. if (text.size() == 1 && text[0] == -1) { text.reset(); } return ::make_shared<literal>(type::STRING, text); } static ::shared_ptr<literal> integer(sstring text) { return ::make_shared<literal>(type::INTEGER, text); } static ::shared_ptr<literal> floating_point(sstring text) { return ::make_shared<literal>(type::FLOAT, text); } static ::shared_ptr<literal> uuid(sstring text) { return ::make_shared<literal>(type::UUID, text); } static ::shared_ptr<literal> bool_(sstring text) { return ::make_shared<literal>(type::BOOLEAN, text); } static ::shared_ptr<literal> hex(sstring text) { return ::make_shared<literal>(type::HEX, text); } virtual ::shared_ptr<term> prepare(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver); private: bytes parsed_value(data_type validator); public: const sstring& get_raw_text() { return _text; } virtual assignment_testable::test_result test_assignment(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver); virtual sstring to_string() const override { return _type == type::STRING ? sstring(sprint("'%s'", _text)) : _text; } }; class marker : public abstract_marker { public: marker(int32_t bind_index, ::shared_ptr<column_specification> receiver) : abstract_marker{bind_index, std::move(receiver)} { assert(!_receiver->type->is_collection()); } virtual cql3::raw_value_view bind_and_get(const query_options& options) override { try { auto value = options.get_value_at(_bind_index); if (value) { _receiver->type->validate(*value); } return value; } catch (const marshal_exception& e) { throw exceptions::invalid_request_exception(e.what()); } } virtual ::shared_ptr<terminal> bind(const query_options& options) override { auto bytes = bind_and_get(options); if (!bytes) { return ::shared_ptr<terminal>{}; } return ::make_shared<constants::value>(std::move(cql3::raw_value::make_value(to_bytes(*bytes)))); } }; class setter : public operation { public: using operation::operation; virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override { auto value = _t->bind_and_get(params._options); auto cell = value ? make_cell(*value, params) : make_dead_cell(params); m.set_cell(prefix, column, std::move(cell)); } }; #if 0 public static class Adder extends Operation { public Adder(ColumnDefinition column, Term t) { super(column, t); } public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException { ByteBuffer bytes = t.bindAndGet(params.options); if (bytes == null) throw new InvalidRequestException("Invalid null value for counter increment"); long increment = ByteBufferUtil.toLong(bytes); CellName cname = cf.getComparator().create(prefix, column); cf.addColumn(params.makeCounter(cname, increment)); } } public static class Substracter extends Operation { public Substracter(ColumnDefinition column, Term t) { super(column, t); } public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException { ByteBuffer bytes = t.bindAndGet(params.options); if (bytes == null) throw new InvalidRequestException("Invalid null value for counter increment"); long increment = ByteBufferUtil.toLong(bytes); if (increment == Long.MIN_VALUE) throw new InvalidRequestException("The negation of " + increment + " overflows supported counter precision (signed 8 bytes integer)"); CellName cname = cf.getComparator().create(prefix, column); cf.addColumn(params.makeCounter(cname, -increment)); } } #endif class deleter : public operation { public: deleter(const column_definition& column) : operation(column, {}) { } virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override; }; }; std::ostream& operator<<(std::ostream&out, constants::type t); } <commit_msg>cql3/constants: Unset value support<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "cql3/abstract_marker.hh" #include "cql3/update_parameters.hh" #include "cql3/operation.hh" #include "cql3/values.hh" #include "cql3/term.hh" #include "core/shared_ptr.hh" namespace cql3 { /** * Static helper methods and classes for constants. */ class constants { public: #if 0 private static final Logger logger = LoggerFactory.getLogger(Constants.class); #endif public: enum class type { STRING, INTEGER, UUID, FLOAT, BOOLEAN, HEX }; /** * A constant value, i.e. a ByteBuffer. */ class value : public terminal { public: cql3::raw_value _bytes; value(cql3::raw_value bytes_) : _bytes(std::move(bytes_)) {} virtual cql3::raw_value get(const query_options& options) override { return _bytes; } virtual cql3::raw_value_view bind_and_get(const query_options& options) override { return _bytes.to_view(); } virtual sstring to_string() const override { return to_hex(*_bytes); } }; class null_literal final : public term::raw { private: class null_value final : public value { public: null_value() : value(cql3::raw_value::make_null()) {} virtual ::shared_ptr<terminal> bind(const query_options& options) override { return {}; } virtual sstring to_string() const override { return "null"; } }; static thread_local const ::shared_ptr<terminal> NULL_VALUE; public: virtual ::shared_ptr<term> prepare(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver) override { if (!is_assignable(test_assignment(db, keyspace, receiver))) { throw exceptions::invalid_request_exception("Invalid null value for counter increment/decrement"); } return NULL_VALUE; } virtual assignment_testable::test_result test_assignment(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver) override { return receiver->type->is_counter() ? assignment_testable::test_result::NOT_ASSIGNABLE : assignment_testable::test_result::WEAKLY_ASSIGNABLE; } virtual sstring to_string() const override { return "null"; } }; static thread_local const ::shared_ptr<term::raw> NULL_LITERAL; class literal : public term::raw { private: const type _type; const sstring _text; public: literal(type type_, sstring text) : _type{type_} , _text{text} { } static ::shared_ptr<literal> string(sstring text) { // This is a workaround for antlr3 not distinguishing between // calling in lexer setText() with an empty string and not calling // setText() at all. if (text.size() == 1 && text[0] == -1) { text.reset(); } return ::make_shared<literal>(type::STRING, text); } static ::shared_ptr<literal> integer(sstring text) { return ::make_shared<literal>(type::INTEGER, text); } static ::shared_ptr<literal> floating_point(sstring text) { return ::make_shared<literal>(type::FLOAT, text); } static ::shared_ptr<literal> uuid(sstring text) { return ::make_shared<literal>(type::UUID, text); } static ::shared_ptr<literal> bool_(sstring text) { return ::make_shared<literal>(type::BOOLEAN, text); } static ::shared_ptr<literal> hex(sstring text) { return ::make_shared<literal>(type::HEX, text); } virtual ::shared_ptr<term> prepare(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver); private: bytes parsed_value(data_type validator); public: const sstring& get_raw_text() { return _text; } virtual assignment_testable::test_result test_assignment(database& db, const sstring& keyspace, ::shared_ptr<column_specification> receiver); virtual sstring to_string() const override { return _type == type::STRING ? sstring(sprint("'%s'", _text)) : _text; } }; class marker : public abstract_marker { public: marker(int32_t bind_index, ::shared_ptr<column_specification> receiver) : abstract_marker{bind_index, std::move(receiver)} { assert(!_receiver->type->is_collection()); } virtual cql3::raw_value_view bind_and_get(const query_options& options) override { try { auto value = options.get_value_at(_bind_index); if (value) { _receiver->type->validate(*value); } return value; } catch (const marshal_exception& e) { throw exceptions::invalid_request_exception(e.what()); } } virtual ::shared_ptr<terminal> bind(const query_options& options) override { auto bytes = bind_and_get(options); if (!bytes) { return ::shared_ptr<terminal>{}; } return ::make_shared<constants::value>(std::move(cql3::raw_value::make_value(to_bytes(*bytes)))); } }; class setter : public operation { public: using operation::operation; virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override { auto value = _t->bind_and_get(params._options); if (value.is_null()) { m.set_cell(prefix, column, std::move(make_dead_cell(params))); } else if (value.is_value()) { m.set_cell(prefix, column, std::move(make_cell(*value, params))); } } }; #if 0 public static class Adder extends Operation { public Adder(ColumnDefinition column, Term t) { super(column, t); } public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException { ByteBuffer bytes = t.bindAndGet(params.options); if (bytes == null) throw new InvalidRequestException("Invalid null value for counter increment"); long increment = ByteBufferUtil.toLong(bytes); CellName cname = cf.getComparator().create(prefix, column); cf.addColumn(params.makeCounter(cname, increment)); } } public static class Substracter extends Operation { public Substracter(ColumnDefinition column, Term t) { super(column, t); } public void execute(ByteBuffer rowKey, ColumnFamily cf, Composite prefix, UpdateParameters params) throws InvalidRequestException { ByteBuffer bytes = t.bindAndGet(params.options); if (bytes == null) throw new InvalidRequestException("Invalid null value for counter increment"); long increment = ByteBufferUtil.toLong(bytes); if (increment == Long.MIN_VALUE) throw new InvalidRequestException("The negation of " + increment + " overflows supported counter precision (signed 8 bytes integer)"); CellName cname = cf.getComparator().create(prefix, column); cf.addColumn(params.makeCounter(cname, -increment)); } } #endif class deleter : public operation { public: deleter(const column_definition& column) : operation(column, {}) { } virtual void execute(mutation& m, const exploded_clustering_prefix& prefix, const update_parameters& params) override; }; }; std::ostream& operator<<(std::ostream&out, constants::type t); } <|endoftext|>
<commit_before>#include "objparser.hpp" #include "../src/meshoptimizer.hpp" #include <algorithm> #define NOMINMAX #include <windows.h> #include <GL/gl.h> #pragma comment(lib, "opengl32.lib") struct Options { bool wireframe; enum { Mode_Default, Mode_Texture, Mode_Normals } mode; }; struct Vertex { float px, py, pz; float nx, ny, nz; float tx, ty; }; struct Mesh { std::vector<Vertex> vertices; std::vector<unsigned int> indices; }; static Mesh parseObj(const char* path) { ObjFile file; if (!objParseFile(file, path) || !objValidate(file)) { printf("Error loading %s\n", path); return Mesh(); } objTriangulate(file); size_t total_indices = file.f.size() / 3; std::vector<Vertex> vertices; vertices.reserve(total_indices); for (size_t i = 0; i < file.f.size(); i += 3) { int vi = file.f[i + 0]; int vti = file.f[i + 1]; int vni = file.f[i + 2]; Vertex v = { file.v[vi * 3 + 0], file.v[vi * 3 + 1], file.v[vi * 3 + 2], vni >= 0 ? file.vn[vni * 3 + 0] : 0, vni >= 0 ? file.vn[vni * 3 + 1] : 0, vni >= 0 ? file.vn[vni * 3 + 2] : 0, vti >= 0 ? file.vt[vti * 3 + 0] : 0, vti >= 0 ? file.vt[vti * 3 + 1] : 0, }; vertices.push_back(v); } Mesh result; result.indices.resize(total_indices); size_t total_vertices = generateIndexBuffer(&result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); result.vertices.resize(total_vertices); generateVertexBuffer(&result.vertices[0], &result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); return result; } Mesh optimize(const Mesh& mesh, int lod) { return mesh; } void display(int width, int height, const Mesh& mesh, const Options& options) { glViewport(0, 0, width, height); glClearDepth(1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); glPolygonMode(GL_FRONT_AND_BACK, options.wireframe ? GL_LINE : GL_FILL); float centerx = 0; float centery = 0; float centerz = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; centerx += v.px; centery += v.py; centerz += v.pz; } centerx /= float(mesh.vertices.size()); centery /= float(mesh.vertices.size()); centerz /= float(mesh.vertices.size()); float extent = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; extent = std::max(extent, fabsf(v.px - centerx)); extent = std::max(extent, fabsf(v.py - centery)); extent = std::max(extent, fabsf(v.pz - centerz)); } extent *= 1.1f; float scalex = width > height ? float(height) / float(width) : 1; float scaley = height > width ? float(width) / float(height) : 1; glBegin(GL_TRIANGLES); for (size_t i = 0; i < mesh.indices.size(); ++i) { const Vertex& v = mesh.vertices[mesh.indices[i]]; switch (options.mode) { case Options::Mode_Texture: glColor3f(v.tx - floorf(v.tx), v.ty - floorf(v.ty), 0.5f); break; case Options::Mode_Normals: glColor3f(v.nx * 0.5f + 0.5f, v.ny * 0.5f + 0.5f, v.nz * 0.5f + 0.5f); break; default: float intensity = -(v.pz - centerz) / extent * 0.5f + 0.5f; glColor3f(intensity, intensity, intensity); } glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent); } glEnd(); } void stats(HWND hWnd, const char* path, const Mesh& mesh, int lod) { char title[256]; snprintf(title, sizeof(title), "%s: LOD %d - %d triangles", path, lod, int(mesh.indices.size() / 3)); SetWindowTextA(hWnd, title); } int main(int argc, char** argv) { if (argc <= 1) { printf("Usage: %s [.obj file]\n", argv[0]); return 0; } HWND hWnd = CreateWindow(L"ListBox", L"Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL); HDC hDC = GetDC(hWnd); PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, 0, 32 }; pfd.cDepthBits = 24; SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd); wglMakeCurrent(hDC, wglCreateContext(hDC)); ShowWindow(hWnd, SW_SHOWNORMAL); const char* path = argv[1]; Mesh basemesh = parseObj(path); Options options = {}; stats(hWnd, path, basemesh, 0); Mesh mesh = basemesh; MSG msg; while (GetMessage(&msg, hWnd, 0, 0) && msg.message) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_KEYDOWN) { if (msg.wParam == 'W') { options.wireframe = !options.wireframe; } else if (msg.wParam == 'T') { options.mode = options.mode == Options::Mode_Texture ? Options::Mode_Default : Options::Mode_Texture; } else if (msg.wParam == 'N') { options.mode = options.mode == Options::Mode_Normals ? Options::Mode_Default : Options::Mode_Normals; } else if (msg.wParam == '0') { mesh = basemesh; stats(hWnd, path, mesh, 0); } else if (msg.wParam >= '1' && msg.wParam <= '9') { int lod = int(msg.wParam - '0'); mesh = optimize(basemesh, lod); stats(hWnd, path, mesh, lod); } } RECT rect; GetClientRect(hWnd, &rect); display(rect.right - rect.left, rect.bottom - rect.top, mesh, options); SwapBuffers(hDC); } } <commit_msg>Implement edge collapse simplifier<commit_after>#include "objparser.hpp" #include "../src/meshoptimizer.hpp" #include <algorithm> #include <cassert> #define NOMINMAX #include <windows.h> #include <GL/gl.h> #pragma comment(lib, "opengl32.lib") struct Options { bool wireframe; enum { Mode_Default, Mode_Texture, Mode_Normals } mode; }; struct Vertex { float px, py, pz; float nx, ny, nz; float tx, ty; }; struct Mesh { std::vector<Vertex> vertices; std::vector<unsigned int> indices; }; static Mesh parseObj(const char* path) { ObjFile file; if (!objParseFile(file, path) || !objValidate(file)) { printf("Error loading %s\n", path); return Mesh(); } objTriangulate(file); size_t total_indices = file.f.size() / 3; std::vector<Vertex> vertices; vertices.reserve(total_indices); for (size_t i = 0; i < file.f.size(); i += 3) { int vi = file.f[i + 0]; int vti = file.f[i + 1]; int vni = file.f[i + 2]; // TODO vni = vti = -1; Vertex v = { file.v[vi * 3 + 0], file.v[vi * 3 + 1], file.v[vi * 3 + 2], vni >= 0 ? file.vn[vni * 3 + 0] : 0, vni >= 0 ? file.vn[vni * 3 + 1] : 0, vni >= 0 ? file.vn[vni * 3 + 2] : 0, vti >= 0 ? file.vt[vti * 3 + 0] : 0, vti >= 0 ? file.vt[vti * 3 + 1] : 0, }; vertices.push_back(v); } Mesh result; result.indices.resize(total_indices); size_t total_vertices = generateIndexBuffer(&result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); result.vertices.resize(total_vertices); generateVertexBuffer(&result.vertices[0], &result.indices[0], &vertices[0], total_indices, sizeof(Vertex)); return result; } struct Vector3 { float x, y, z; }; struct Quadric { // TODO the matrix is symmetric, so we only really need 10 floats here float m[4][4]; }; void quadricFromPlane(Quadric& Q, float a, float b, float c, float d) { Q.m[0][0] = a * a; Q.m[0][1] = a * b; Q.m[0][2] = a * c; Q.m[0][3] = a * d; Q.m[1][0] = b * a; Q.m[1][1] = b * b; Q.m[1][2] = b * c; Q.m[1][3] = b * d; Q.m[2][0] = c * a; Q.m[2][1] = c * b; Q.m[2][2] = c * c; Q.m[2][3] = c * d; Q.m[3][0] = d * a; Q.m[3][1] = d * b; Q.m[3][2] = d * c; Q.m[3][3] = d * d; } void quadricFromTriangle(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2) { Vector3 p10 = { p1.x - p0.x, p1.y - p0.y, p1.z - p0.z }; Vector3 p20 = { p2.x - p0.x, p2.y - p0.y, p2.z - p0.z }; Vector3 normal = { p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x }; // TODO: do we need to normalize here? plane eqn is the same but plane distance scale can vary float area = sqrtf(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z); normal.x /= area; normal.y /= area; normal.z /= area; float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z; quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance); } void quadricAdd(Quadric& Q, const Quadric& R) { Q.m[0][0] += R.m[0][0]; Q.m[0][1] += R.m[0][1]; Q.m[0][2] += R.m[0][2]; Q.m[0][3] += R.m[0][3]; Q.m[1][0] += R.m[1][0]; Q.m[1][1] += R.m[1][1]; Q.m[1][2] += R.m[1][2]; Q.m[1][3] += R.m[1][3]; Q.m[2][0] += R.m[2][0]; Q.m[2][1] += R.m[2][1]; Q.m[2][2] += R.m[2][2]; Q.m[2][3] += R.m[2][3]; Q.m[3][0] += R.m[3][0]; Q.m[3][1] += R.m[3][1]; Q.m[3][2] += R.m[3][2]; Q.m[3][3] += R.m[3][3]; } float quadricError(Quadric& Q, const Vector3& v) { float vTQv = (Q.m[0][0] * v.x + Q.m[0][1] * v.y + Q.m[0][2] * v.z + Q.m[0][3]) * v.x + (Q.m[1][0] * v.x + Q.m[1][1] * v.y + Q.m[1][2] * v.z + Q.m[1][3]) * v.y + (Q.m[2][0] * v.x + Q.m[2][1] * v.y + Q.m[2][2] * v.z + Q.m[2][3]) * v.z + (Q.m[3][0] * v.x + Q.m[3][1] * v.y + Q.m[3][2] * v.z + Q.m[3][3]); return fabsf(vTQv); } Mesh optimize(const Mesh& mesh, int lod) { std::vector<Vector3> vertex_positions(mesh.vertices.size()); for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; vertex_positions[i].x = v.px; vertex_positions[i].y = v.py; vertex_positions[i].z = v.pz; } std::vector<Quadric> vertex_quadrics(mesh.vertices.size()); for (size_t i = 0; i < mesh.indices.size(); i += 3) { Quadric Q; quadricFromTriangle(Q, vertex_positions[mesh.indices[i + 0]], vertex_positions[mesh.indices[i + 1]], vertex_positions[mesh.indices[i + 2]]); quadricAdd(vertex_quadrics[mesh.indices[i + 0]], Q); quadricAdd(vertex_quadrics[mesh.indices[i + 1]], Q); quadricAdd(vertex_quadrics[mesh.indices[i + 2]], Q); } struct Collapse { size_t v0; size_t v1; float error; }; std::vector<Collapse> edge_collapses(mesh.indices.size()); for (size_t i = 0; i < mesh.indices.size(); i += 3) { float cost0 = quadricError(vertex_quadrics[mesh.indices[i + 0]], vertex_positions[mesh.indices[i + 1]]); float cost1 = quadricError(vertex_quadrics[mesh.indices[i + 1]], vertex_positions[mesh.indices[i + 2]]); float cost2 = quadricError(vertex_quadrics[mesh.indices[i + 2]], vertex_positions[mesh.indices[i + 0]]); // TODO: do we need uni-directional or bi-directional cost? cost0 = std::max(cost0, quadricError(vertex_quadrics[mesh.indices[i + 1]], vertex_positions[mesh.indices[i + 0]])); cost1 = std::max(cost1, quadricError(vertex_quadrics[mesh.indices[i + 2]], vertex_positions[mesh.indices[i + 1]])); cost2 = std::max(cost2, quadricError(vertex_quadrics[mesh.indices[i + 0]], vertex_positions[mesh.indices[i + 2]])); edge_collapses[i + 0] = { mesh.indices[i + 0], mesh.indices[i + 1], cost0 }; edge_collapses[i + 1] = { mesh.indices[i + 1], mesh.indices[i + 2], cost1 }; edge_collapses[i + 2] = { mesh.indices[i + 2], mesh.indices[i + 0], cost2 }; } std::sort(edge_collapses.begin(), edge_collapses.end(), [](const Collapse& l, const Collapse& r) { return l.error < r.error; }); std::vector<unsigned int> vertex_remap(mesh.vertices.size()); for (size_t i = 0; i < mesh.vertices.size(); ++i) { vertex_remap[i] = unsigned(i); } float threshold = powf(0.9f, float(lod)); size_t edge_collapse_target_count = size_t(edge_collapses.size() * (1 - threshold)); size_t collapses = 0; float worst_error = 0; for (size_t i = 0; i < edge_collapse_target_count; ++i) { const Collapse& c = edge_collapses[i]; if (vertex_remap[c.v0] != c.v0) continue; if (vertex_remap[c.v1] != c.v1) continue; vertex_remap[c.v0] = vertex_remap[c.v1]; collapses++; worst_error = c.error; } printf("collapses: %d, worst error: %f\n", int(collapses), worst_error); std::vector<unsigned int> indices; indices.reserve(mesh.indices.size()); for (size_t i = 0; i < mesh.indices.size(); i += 3) { unsigned int v0 = vertex_remap[mesh.indices[i + 0]]; unsigned int v1 = vertex_remap[mesh.indices[i + 1]]; unsigned int v2 = vertex_remap[mesh.indices[i + 2]]; if (v0 != v1 && v0 != v2 && v1 != v2) { indices.push_back(v0); indices.push_back(v1); indices.push_back(v2); } } Mesh result = mesh; result.indices.swap(indices); return result; } void display(int width, int height, const Mesh& mesh, const Options& options) { glViewport(0, 0, width, height); glClearDepth(1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glDepthMask(GL_TRUE); glPolygonMode(GL_FRONT_AND_BACK, options.wireframe ? GL_LINE : GL_FILL); float centerx = 0; float centery = 0; float centerz = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; centerx += v.px; centery += v.py; centerz += v.pz; } centerx /= float(mesh.vertices.size()); centery /= float(mesh.vertices.size()); centerz /= float(mesh.vertices.size()); float extent = 0; for (size_t i = 0; i < mesh.vertices.size(); ++i) { const Vertex& v = mesh.vertices[i]; extent = std::max(extent, fabsf(v.px - centerx)); extent = std::max(extent, fabsf(v.py - centery)); extent = std::max(extent, fabsf(v.pz - centerz)); } extent *= 1.1f; float scalex = width > height ? float(height) / float(width) : 1; float scaley = height > width ? float(width) / float(height) : 1; glBegin(GL_TRIANGLES); for (size_t i = 0; i < mesh.indices.size(); ++i) { const Vertex& v = mesh.vertices[mesh.indices[i]]; switch (options.mode) { case Options::Mode_Texture: glColor3f(v.tx - floorf(v.tx), v.ty - floorf(v.ty), 0.5f); break; case Options::Mode_Normals: glColor3f(v.nx * 0.5f + 0.5f, v.ny * 0.5f + 0.5f, v.nz * 0.5f + 0.5f); break; default: float intensity = -(v.pz - centerz) / extent * 0.5f + 0.5f; glColor3f(intensity, intensity, intensity); } glVertex3f((v.px - centerx) / extent * scalex, (v.py - centery) / extent * scaley, (v.pz - centerz) / extent); } glEnd(); } void stats(HWND hWnd, const char* path, const Mesh& mesh, int lod) { char title[256]; snprintf(title, sizeof(title), "%s: LOD %d - %d triangles", path, lod, int(mesh.indices.size() / 3)); SetWindowTextA(hWnd, title); } int main(int argc, char** argv) { if (argc <= 1) { printf("Usage: %s [.obj file]\n", argv[0]); return 0; } HWND hWnd = CreateWindow(L"ListBox", L"Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, NULL, NULL); HDC hDC = GetDC(hWnd); PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, 0, 32 }; pfd.cDepthBits = 24; SetPixelFormat(hDC, ChoosePixelFormat(hDC, &pfd), &pfd); wglMakeCurrent(hDC, wglCreateContext(hDC)); ShowWindow(hWnd, SW_SHOWNORMAL); const char* path = argv[1]; Mesh basemesh = parseObj(path); Options options = {}; stats(hWnd, path, basemesh, 0); Mesh mesh = basemesh; MSG msg; while (GetMessage(&msg, hWnd, 0, 0) && msg.message) { TranslateMessage(&msg); DispatchMessage(&msg); if (msg.message == WM_KEYDOWN) { if (msg.wParam == 'W') { options.wireframe = !options.wireframe; } else if (msg.wParam == 'T') { options.mode = options.mode == Options::Mode_Texture ? Options::Mode_Default : Options::Mode_Texture; } else if (msg.wParam == 'N') { options.mode = options.mode == Options::Mode_Normals ? Options::Mode_Default : Options::Mode_Normals; } else if (msg.wParam == '0') { mesh = basemesh; stats(hWnd, path, mesh, 0); } else if (msg.wParam >= '1' && msg.wParam <= '9') { int lod = int(msg.wParam - '0'); mesh = optimize(basemesh, lod); stats(hWnd, path, mesh, lod); } } RECT rect; GetClientRect(hWnd, &rect); display(rect.right - rect.left, rect.bottom - rect.top, mesh, options); SwapBuffers(hDC); } } <|endoftext|>
<commit_before>/* Copyright (c) 2008-2020 the MRtrix3 contributors. * * 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/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include <algorithm> #include <cmath> #include "command.h" #include "datatype.h" #include "header.h" #include "image.h" #include "adapter/replicate.h" #include "algo/histogram.h" #include "algo/loop.h" using namespace MR; using namespace App; const char* choices[] = { "scale", "linear", "nonlinear", nullptr }; void usage () { AUTHOR = "Robert E. Smith ([email protected])"; SYNOPSIS = "Modify the intensities of one image to match the histogram of another"; ARGUMENTS + Argument ("type", "type of histogram matching to perform; options are: " + join(choices, ",")).type_choice (choices) + Argument ("input", "the input image to be modified").type_image_in () + Argument ("target", "the input image from which to derive the target histogram").type_image_in() + Argument ("output", "the output image").type_image_out(); OPTIONS + OptionGroup ("Image masking options") + Option ("mask_input", "only generate input histogram based on a specified binary mask image") + Argument ("image").type_image_in () + Option ("mask_target", "only generate target histogram based on a specified binary mask image") + Argument ("image").type_image_in () + OptionGroup ("Non-linear histogram matching options") + Option ("bins", "the number of bins to use to generate the histograms") + Argument ("num").type_integer (2); REFERENCES + "* If using inverse contrast normalization for inter-modal (DWI - T1) registration:\n" "Bhushan, C.; Haldar, J. P.; Choi, S.; Joshi, A. A.; Shattuck, D. W. & Leahy, R. M. " "Co-registration and distortion correction of diffusion and anatomical images based on inverse contrast normalization. " "NeuroImage, 2015, 115, 269-280"; } void match_linear (Image<float>& input, Image<float>& target, Image<bool>& mask_input, Image<bool>& mask_target, const bool estimate_intercept) { vector<float> input_data, target_data; { ProgressBar progress ("Loading & sorting image data", 4); auto fill = [] (Image<float>& image, Image<bool>& mask) { vector<float> data; if (mask.valid()) { Adapter::Replicate<Image<bool>> mask_replicate (mask, image); for (auto l = Loop(image) (image, mask_replicate); l; ++l) { if (mask_replicate.value() && std::isfinite (static_cast<float>(image.value()))) data.push_back (image.value()); } } else { for (auto l = Loop(image) (image); l; ++l) { if (std::isfinite (static_cast<float>(image.value()))) data.push_back (image.value()); } } return data; }; input_data = fill (input, mask_input); ++progress; target_data = fill (target, mask_target); ++progress; std::sort (input_data.begin(), input_data.end()); ++progress; std::sort (target_data.begin(), target_data.end()); } // Ax=b // A: Input data // x: Model parameters; in the "scale" case, it's a single multiplier; if "linear", include a column of ones and estimate an intercept // b: Output data (or actually, interpolated histogram-matched output data) Eigen::Matrix<default_type, Eigen::Dynamic, Eigen::Dynamic> input_matrix (input_data.size(), estimate_intercept ? 2 : 1); Eigen::Matrix<default_type, Eigen::Dynamic, 1> output_vector (input_data.size()); for (size_t input_index = 0; input_index != input_data.size()-1; ++input_index) { input_matrix(input_index, 0) = input_data[input_index]; const default_type output_position = (target_data.size()-1) * (default_type(input_index) / default_type(input_data.size()-1)); const size_t target_index_lower = std::floor (output_position); const default_type mu = output_position - default_type(target_index_lower); output_vector[input_index] = ((1.0-mu)*target_data[target_index_lower]) + (mu*target_data[target_index_lower+1]); } input_matrix(input_data.size()-1, 0) = input_data.back(); output_vector[input_data.size()-1] = target_data.back(); if (estimate_intercept) input_matrix.col(1).fill (1.0f); auto parameters = (input_matrix.transpose() * input_matrix).ldlt().solve(input_matrix.transpose() * output_vector).eval(); Header H (input); H.datatype() = DataType::Float32; H.datatype().set_byte_order_native(); H.keyval()["mrhistmatch_scale"] = str<float>(parameters[0]); if (estimate_intercept) { CONSOLE ("Estimated linear transform is: " + str(parameters[0]) + "x + " + str(parameters[1])); H.keyval()["mrhistmatch_offset"] = str<float>(parameters[1]); auto output = Image<float>::create (argument[3], H); for (auto l = Loop("Writing output image data", input) (input, output); l; ++l) { if (std::isfinite(static_cast<float>(input.value()))) { output.value() = parameters[0]*input.value() + parameters[1]; } else { output.value() = input.value(); } } } else { CONSOLE ("Estimated scale factor is " + str(parameters[0])); auto output = Image<float>::create (argument[3], H); for (auto l = Loop("Writing output image data", input) (input, output); l; ++l) { if (std::isfinite(static_cast<float>(input.value()))) { output.value() = input.value() * parameters[0]; } else { output.value() = input.value(); } } } } void match_nonlinear (Image<float>& input, Image<float>& target, Image<bool>& mask_input, Image<bool>& mask_target, const size_t nbins) { Algo::Histogram::Calibrator calib_input (nbins, true); Algo::Histogram::calibrate (calib_input, input, mask_input); INFO ("Input histogram ranges from " + str(calib_input.get_min()) + " to " + str(calib_input.get_max()) + "; using " + str(calib_input.get_num_bins()) + " bins"); Algo::Histogram::Data hist_input = Algo::Histogram::generate (calib_input, input, mask_input); Algo::Histogram::Calibrator calib_target (nbins, true); Algo::Histogram::calibrate (calib_target, target, mask_target); INFO ("Target histogram ranges from " + str(calib_target.get_min()) + " to " + str(calib_target.get_max()) + "; using " + str(calib_target.get_num_bins()) + " bins"); Algo::Histogram::Data hist_target = Algo::Histogram::generate (calib_target, target, mask_target); // Non-linear intensity mapping determined within this class Algo::Histogram::Matcher matcher (hist_input, hist_target); Header H (input); H.datatype() = DataType::Float32; H.datatype().set_byte_order_native(); auto output = Image<float>::create (argument[3], H); for (auto l = Loop("Writing output data", input) (input, output); l; ++l) { if (std::isfinite (static_cast<float>(input.value()))) { output.value() = matcher (input.value()); } else { output.value() = input.value(); } } } void run () { auto input = Image<float>::open (argument[1]); auto target = Image<float>::open (argument[2]); Image<bool> mask_input, mask_target; auto opt = get_options ("mask_input"); if (opt.size()) { mask_input = Image<bool>::open (opt[0][0]); check_dimensions (input, mask_input, 0, 3); } opt = get_options ("mask_target"); if (opt.size()) { mask_target = Image<bool>::open (opt[0][0]); check_dimensions (target, mask_target, 0, 3); } switch (int(argument[0])) { case 0: // Scale match_linear (input, target, mask_input, mask_target, false); break; case 1: // Linear match_linear (input, target, mask_input, mask_target, true); break; case 2: // Non-linear match_nonlinear (input, target, mask_input, mask_target, get_option_value ("bins", 0)); break; default: throw Exception ("Undefined histogram matching type"); } } <commit_msg>mrhistmatch: Use LLT rather than LDLT<commit_after>/* Copyright (c) 2008-2020 the MRtrix3 contributors. * * 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/. * * Covered Software is provided under this License on an "as is" * basis, without warranty of any kind, either expressed, implied, or * statutory, including, without limitation, warranties that the * Covered Software is free of defects, merchantable, fit for a * particular purpose or non-infringing. * See the Mozilla Public License v. 2.0 for more details. * * For more details, see http://www.mrtrix.org/. */ #include <algorithm> #include <cmath> #include "command.h" #include "datatype.h" #include "header.h" #include "image.h" #include "adapter/replicate.h" #include "algo/histogram.h" #include "algo/loop.h" using namespace MR; using namespace App; const char* choices[] = { "scale", "linear", "nonlinear", nullptr }; void usage () { AUTHOR = "Robert E. Smith ([email protected])"; SYNOPSIS = "Modify the intensities of one image to match the histogram of another"; ARGUMENTS + Argument ("type", "type of histogram matching to perform; options are: " + join(choices, ",")).type_choice (choices) + Argument ("input", "the input image to be modified").type_image_in () + Argument ("target", "the input image from which to derive the target histogram").type_image_in() + Argument ("output", "the output image").type_image_out(); OPTIONS + OptionGroup ("Image masking options") + Option ("mask_input", "only generate input histogram based on a specified binary mask image") + Argument ("image").type_image_in () + Option ("mask_target", "only generate target histogram based on a specified binary mask image") + Argument ("image").type_image_in () + OptionGroup ("Non-linear histogram matching options") + Option ("bins", "the number of bins to use to generate the histograms") + Argument ("num").type_integer (2); REFERENCES + "* If using inverse contrast normalization for inter-modal (DWI - T1) registration:\n" "Bhushan, C.; Haldar, J. P.; Choi, S.; Joshi, A. A.; Shattuck, D. W. & Leahy, R. M. " "Co-registration and distortion correction of diffusion and anatomical images based on inverse contrast normalization. " "NeuroImage, 2015, 115, 269-280"; } void match_linear (Image<float>& input, Image<float>& target, Image<bool>& mask_input, Image<bool>& mask_target, const bool estimate_intercept) { vector<float> input_data, target_data; { ProgressBar progress ("Loading & sorting image data", 4); auto fill = [] (Image<float>& image, Image<bool>& mask) { vector<float> data; if (mask.valid()) { Adapter::Replicate<Image<bool>> mask_replicate (mask, image); for (auto l = Loop(image) (image, mask_replicate); l; ++l) { if (mask_replicate.value() && std::isfinite (static_cast<float>(image.value()))) data.push_back (image.value()); } } else { for (auto l = Loop(image) (image); l; ++l) { if (std::isfinite (static_cast<float>(image.value()))) data.push_back (image.value()); } } return data; }; input_data = fill (input, mask_input); ++progress; target_data = fill (target, mask_target); ++progress; std::sort (input_data.begin(), input_data.end()); ++progress; std::sort (target_data.begin(), target_data.end()); } // Ax=b // A: Input data // x: Model parameters; in the "scale" case, it's a single multiplier; if "linear", include a column of ones and estimate an intercept // b: Output data (or actually, interpolated histogram-matched output data) Eigen::Matrix<default_type, Eigen::Dynamic, Eigen::Dynamic> input_matrix (input_data.size(), estimate_intercept ? 2 : 1); Eigen::Matrix<default_type, Eigen::Dynamic, 1> output_vector (input_data.size()); for (size_t input_index = 0; input_index != input_data.size()-1; ++input_index) { input_matrix(input_index, 0) = input_data[input_index]; const default_type output_position = (target_data.size()-1) * (default_type(input_index) / default_type(input_data.size()-1)); const size_t target_index_lower = std::floor (output_position); const default_type mu = output_position - default_type(target_index_lower); output_vector[input_index] = ((1.0-mu)*target_data[target_index_lower]) + (mu*target_data[target_index_lower+1]); } input_matrix(input_data.size()-1, 0) = input_data.back(); output_vector[input_data.size()-1] = target_data.back(); if (estimate_intercept) input_matrix.col(1).fill (1.0f); auto parameters = (input_matrix.transpose() * input_matrix).llt().solve(input_matrix.transpose() * output_vector).eval(); Header H (input); H.datatype() = DataType::Float32; H.datatype().set_byte_order_native(); H.keyval()["mrhistmatch_scale"] = str<float>(parameters[0]); if (estimate_intercept) { CONSOLE ("Estimated linear transform is: " + str(parameters[0]) + "x + " + str(parameters[1])); H.keyval()["mrhistmatch_offset"] = str<float>(parameters[1]); auto output = Image<float>::create (argument[3], H); for (auto l = Loop("Writing output image data", input) (input, output); l; ++l) { if (std::isfinite(static_cast<float>(input.value()))) { output.value() = parameters[0]*input.value() + parameters[1]; } else { output.value() = input.value(); } } } else { CONSOLE ("Estimated scale factor is " + str(parameters[0])); auto output = Image<float>::create (argument[3], H); for (auto l = Loop("Writing output image data", input) (input, output); l; ++l) { if (std::isfinite(static_cast<float>(input.value()))) { output.value() = input.value() * parameters[0]; } else { output.value() = input.value(); } } } } void match_nonlinear (Image<float>& input, Image<float>& target, Image<bool>& mask_input, Image<bool>& mask_target, const size_t nbins) { Algo::Histogram::Calibrator calib_input (nbins, true); Algo::Histogram::calibrate (calib_input, input, mask_input); INFO ("Input histogram ranges from " + str(calib_input.get_min()) + " to " + str(calib_input.get_max()) + "; using " + str(calib_input.get_num_bins()) + " bins"); Algo::Histogram::Data hist_input = Algo::Histogram::generate (calib_input, input, mask_input); Algo::Histogram::Calibrator calib_target (nbins, true); Algo::Histogram::calibrate (calib_target, target, mask_target); INFO ("Target histogram ranges from " + str(calib_target.get_min()) + " to " + str(calib_target.get_max()) + "; using " + str(calib_target.get_num_bins()) + " bins"); Algo::Histogram::Data hist_target = Algo::Histogram::generate (calib_target, target, mask_target); // Non-linear intensity mapping determined within this class Algo::Histogram::Matcher matcher (hist_input, hist_target); Header H (input); H.datatype() = DataType::Float32; H.datatype().set_byte_order_native(); auto output = Image<float>::create (argument[3], H); for (auto l = Loop("Writing output data", input) (input, output); l; ++l) { if (std::isfinite (static_cast<float>(input.value()))) { output.value() = matcher (input.value()); } else { output.value() = input.value(); } } } void run () { auto input = Image<float>::open (argument[1]); auto target = Image<float>::open (argument[2]); Image<bool> mask_input, mask_target; auto opt = get_options ("mask_input"); if (opt.size()) { mask_input = Image<bool>::open (opt[0][0]); check_dimensions (input, mask_input, 0, 3); } opt = get_options ("mask_target"); if (opt.size()) { mask_target = Image<bool>::open (opt[0][0]); check_dimensions (target, mask_target, 0, 3); } switch (int(argument[0])) { case 0: // Scale match_linear (input, target, mask_input, mask_target, false); break; case 1: // Linear match_linear (input, target, mask_input, mask_target, true); break; case 2: // Non-linear match_nonlinear (input, target, mask_input, mask_target, get_option_value ("bins", 0)); break; default: throw Exception ("Undefined histogram matching type"); } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /// /// \class AliMUONPayloadTracker /// Decodes rawdata from buffer and stores in TClonesArray. /// First version implement for Tracker /// /// \author Christian Finck #include "AliMUONPayloadTracker.h" #include "AliMUONDspHeader.h" #include "AliMUONBlockHeader.h" #include "AliMUONBusStruct.h" #include "AliMUONDDLTracker.h" #include "AliLog.h" /// \cond CLASSIMP ClassImp(AliMUONPayloadTracker) /// \endcond AliMUONPayloadTracker::AliMUONPayloadTracker() : TObject(), fBusPatchId(0), fDspId(0), fBlkId(0), fMaxDDL(20), fMaxBlock(2), fMaxDsp(5), fMaxBus(5), fDDLTracker(new AliMUONDDLTracker()), fBusStruct(new AliMUONBusStruct()), fBlockHeader(new AliMUONBlockHeader()), fDspHeader(new AliMUONDspHeader()), fParityErrBus(), fGlitchErrors(0) { /// /// create an object to decode MUON payload /// } //___________________________________ AliMUONPayloadTracker::~AliMUONPayloadTracker() { /// /// clean up /// delete fDDLTracker; delete fBusStruct; delete fBlockHeader; delete fDspHeader; } //______________________________________________________ Bool_t AliMUONPayloadTracker::Decode(UInt_t* buffer, Int_t totalDDLSize) { /// Each DDL is made with 2 Blocks each of which consists of 5 DSP's at most /// and each of DSP has at most 5 buspatches. /// The different structures, Block (CRT), DSP (FRT) and Buspatch, /// are identified by a key word 0xFC0000FC, 0xF000000F and 0xB000000B respectively. /// (fBusPatchManager no more needed !) //Read Header Size of DDL,Block,DSP and BusPatch static Int_t kBlockHeaderSize = fBlockHeader->GetHeaderLength(); static Int_t kDspHeaderSize = fDspHeader->GetHeaderLength(); static Int_t kBusPatchHeaderSize = fBusStruct->GetHeaderLength(); // size structures Int_t totalBlockSize; Int_t totalDspSize; Int_t totalBusPatchSize; Int_t dataSize; Int_t bufSize; // indexes Int_t indexBlk; Int_t indexDsp; Int_t indexBusPatch; Int_t index = 0; Int_t iBlock = 0; // CROCUS CRT while (buffer[index] == fBlockHeader->GetDefaultDataKey()) { if (iBlock > fMaxBlock) break; // copy within padding words memcpy(fBlockHeader->GetHeader(),&buffer[index], (kBlockHeaderSize)*4); totalBlockSize = fBlockHeader->GetTotalLength(); indexBlk = index; index += kBlockHeaderSize; // copy in TClonesArray fDDLTracker->AddBlkHeader(*fBlockHeader); // Crocus FRT Int_t iDsp = 0; while (buffer[index] == fDspHeader->GetDefaultDataKey()) { if (iDsp > fMaxDsp) break; // if ever... memcpy(fDspHeader->GetHeader(),&buffer[index], kDspHeaderSize*4); totalDspSize = fDspHeader->GetTotalLength(); if (fDspHeader->GetErrorWord()) { fDspHeader->Print(""); if (fDspHeader->GetErrorWord() == (0x000000B1 | fBlockHeader->GetDspId())){ // an event with a glitch in the readout has been detected // it means that somewhere a 1 byte word has been randomly inserted // all the readout sequence is shifted untill the next event AliWarning(Form("Glitch in data detected, skipping event ")); fGlitchErrors++; return kFALSE ; } } indexDsp = index; index += kDspHeaderSize; // copy in TClonesArray fDDLTracker->AddDspHeader(*fDspHeader, iBlock); // buspatch structure Int_t iBusPatch = 0; while (buffer[index] == fBusStruct->GetDefaultDataKey()) { if (iBusPatch > fMaxBus) break; // if ever //copy buffer into header structure memcpy(fBusStruct->GetHeader(), &buffer[index], kBusPatchHeaderSize*4); totalBusPatchSize = fBusStruct->GetTotalLength(); indexBusPatch = index; //Check Buspatch header, not empty events if(totalBusPatchSize > kBusPatchHeaderSize) { index += kBusPatchHeaderSize; dataSize = fBusStruct->GetLength(); bufSize = fBusStruct->GetBufSize(); if(dataSize > 0) { // check data present if (dataSize > bufSize) // check buffer size fBusStruct->SetAlloc(dataSize); //copy buffer into data structure memcpy(fBusStruct->GetData(), &buffer[index], dataSize*4); fBusStruct->SetBlockId(iBlock); // could be usefull in future applications ? fBusStruct->SetDspId(iDsp); // check parity if(!CheckDataParity()) AddParityErrBus(fBusStruct->GetBusPatchId()); // copy in TClonesArray fDDLTracker->AddBusPatch(*fBusStruct, iBlock, iDsp); } // dataSize test } // testing buspatch index = indexBusPatch + totalBusPatchSize; if (index >= totalDDLSize) {// check the end of DDL index = totalDDLSize - 1; // point to the last element of buffer break; } iBusPatch++; } // buspatch loop // skipping additionnal word if padding if (fDspHeader->GetPaddingWord() == 1) { if (buffer[index++] != fDspHeader->GetDefaultPaddingWord()) AliError(Form("Error in padding word for iBlock %d, iDsp %d, iBus %d\n", iBlock, iDsp, iBusPatch)); } index = indexDsp + totalDspSize; if (index >= totalDDLSize) { index = totalDDLSize - 1; break; } iDsp++; } // dsp loop index = indexBlk + totalBlockSize; if (index >= totalDDLSize) { index = totalDDLSize - 1; break; } iBlock++; } // block loop return kTRUE; } //______________________________________________________ void AliMUONPayloadTracker::ResetDDL() { /// reseting TClonesArray /// after each DDL /// fDDLTracker->GetBlkHeaderArray()->Delete(); fGlitchErrors = 0; fParityErrBus.Reset(); } //______________________________________________________ void AliMUONPayloadTracker::SetMaxBlock(Int_t blk) { /// set regional card number if (blk > 2) blk = 2; fMaxBlock = blk; } //______________________________________________________ Bool_t AliMUONPayloadTracker::CheckDataParity() { /// parity check /// taken from MuTrkBusPatch.cxx (sotfware test for CROCUS) /// A. Baldisseri Int_t parity; UInt_t data; Int_t dataSize = fBusStruct->GetLength(); for (int idata = 0; idata < dataSize; idata++) { data = fBusStruct->GetData(idata); // Compute the parity for each data word parity = data & 0x1; for (Int_t i = 1; i <= 30; i++) parity ^= ((data >> i) & 0x1); // Check if (parity != fBusStruct->GetParity(idata)) { AliWarning(Form("Parity error in word %d for manuId %d and channel %d\n", idata, fBusStruct->GetManuId(idata), fBusStruct->GetChannelId(idata))); return kFALSE; } } return kTRUE; } //______________________________________________________ void AliMUONPayloadTracker::AddParityErrBus(Int_t buspatch) { // adding bus with at least on parity error fParityErrBus.Set(fParityErrBus.GetSize() + 1); fParityErrBus.AddAt(buspatch, fParityErrBus.GetSize() - 1); } <commit_msg>Corrected comments for Doxygen<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /// /// \class AliMUONPayloadTracker /// Decodes rawdata from buffer and stores in TClonesArray. /// First version implement for Tracker /// /// \author Christian Finck #include "AliMUONPayloadTracker.h" #include "AliMUONDspHeader.h" #include "AliMUONBlockHeader.h" #include "AliMUONBusStruct.h" #include "AliMUONDDLTracker.h" #include "AliLog.h" /// \cond CLASSIMP ClassImp(AliMUONPayloadTracker) /// \endcond AliMUONPayloadTracker::AliMUONPayloadTracker() : TObject(), fBusPatchId(0), fDspId(0), fBlkId(0), fMaxDDL(20), fMaxBlock(2), fMaxDsp(5), fMaxBus(5), fDDLTracker(new AliMUONDDLTracker()), fBusStruct(new AliMUONBusStruct()), fBlockHeader(new AliMUONBlockHeader()), fDspHeader(new AliMUONDspHeader()), fParityErrBus(), fGlitchErrors(0) { /// /// create an object to decode MUON payload /// } //___________________________________ AliMUONPayloadTracker::~AliMUONPayloadTracker() { /// /// clean up /// delete fDDLTracker; delete fBusStruct; delete fBlockHeader; delete fDspHeader; } //______________________________________________________ Bool_t AliMUONPayloadTracker::Decode(UInt_t* buffer, Int_t totalDDLSize) { /// Each DDL is made with 2 Blocks each of which consists of 5 DSP's at most /// and each of DSP has at most 5 buspatches. /// The different structures, Block (CRT), DSP (FRT) and Buspatch, /// are identified by a key word 0xFC0000FC, 0xF000000F and 0xB000000B respectively. /// (fBusPatchManager no more needed !) //Read Header Size of DDL,Block,DSP and BusPatch static Int_t kBlockHeaderSize = fBlockHeader->GetHeaderLength(); static Int_t kDspHeaderSize = fDspHeader->GetHeaderLength(); static Int_t kBusPatchHeaderSize = fBusStruct->GetHeaderLength(); // size structures Int_t totalBlockSize; Int_t totalDspSize; Int_t totalBusPatchSize; Int_t dataSize; Int_t bufSize; // indexes Int_t indexBlk; Int_t indexDsp; Int_t indexBusPatch; Int_t index = 0; Int_t iBlock = 0; // CROCUS CRT while (buffer[index] == fBlockHeader->GetDefaultDataKey()) { if (iBlock > fMaxBlock) break; // copy within padding words memcpy(fBlockHeader->GetHeader(),&buffer[index], (kBlockHeaderSize)*4); totalBlockSize = fBlockHeader->GetTotalLength(); indexBlk = index; index += kBlockHeaderSize; // copy in TClonesArray fDDLTracker->AddBlkHeader(*fBlockHeader); // Crocus FRT Int_t iDsp = 0; while (buffer[index] == fDspHeader->GetDefaultDataKey()) { if (iDsp > fMaxDsp) break; // if ever... memcpy(fDspHeader->GetHeader(),&buffer[index], kDspHeaderSize*4); totalDspSize = fDspHeader->GetTotalLength(); if (fDspHeader->GetErrorWord()) { fDspHeader->Print(""); if (fDspHeader->GetErrorWord() == (0x000000B1 | fBlockHeader->GetDspId())){ // an event with a glitch in the readout has been detected // it means that somewhere a 1 byte word has been randomly inserted // all the readout sequence is shifted untill the next event AliWarning(Form("Glitch in data detected, skipping event ")); fGlitchErrors++; return kFALSE ; } } indexDsp = index; index += kDspHeaderSize; // copy in TClonesArray fDDLTracker->AddDspHeader(*fDspHeader, iBlock); // buspatch structure Int_t iBusPatch = 0; while (buffer[index] == fBusStruct->GetDefaultDataKey()) { if (iBusPatch > fMaxBus) break; // if ever //copy buffer into header structure memcpy(fBusStruct->GetHeader(), &buffer[index], kBusPatchHeaderSize*4); totalBusPatchSize = fBusStruct->GetTotalLength(); indexBusPatch = index; //Check Buspatch header, not empty events if(totalBusPatchSize > kBusPatchHeaderSize) { index += kBusPatchHeaderSize; dataSize = fBusStruct->GetLength(); bufSize = fBusStruct->GetBufSize(); if(dataSize > 0) { // check data present if (dataSize > bufSize) // check buffer size fBusStruct->SetAlloc(dataSize); //copy buffer into data structure memcpy(fBusStruct->GetData(), &buffer[index], dataSize*4); fBusStruct->SetBlockId(iBlock); // could be usefull in future applications ? fBusStruct->SetDspId(iDsp); // check parity if(!CheckDataParity()) AddParityErrBus(fBusStruct->GetBusPatchId()); // copy in TClonesArray fDDLTracker->AddBusPatch(*fBusStruct, iBlock, iDsp); } // dataSize test } // testing buspatch index = indexBusPatch + totalBusPatchSize; if (index >= totalDDLSize) {// check the end of DDL index = totalDDLSize - 1; // point to the last element of buffer break; } iBusPatch++; } // buspatch loop // skipping additionnal word if padding if (fDspHeader->GetPaddingWord() == 1) { if (buffer[index++] != fDspHeader->GetDefaultPaddingWord()) AliError(Form("Error in padding word for iBlock %d, iDsp %d, iBus %d\n", iBlock, iDsp, iBusPatch)); } index = indexDsp + totalDspSize; if (index >= totalDDLSize) { index = totalDDLSize - 1; break; } iDsp++; } // dsp loop index = indexBlk + totalBlockSize; if (index >= totalDDLSize) { index = totalDDLSize - 1; break; } iBlock++; } // block loop return kTRUE; } //______________________________________________________ void AliMUONPayloadTracker::ResetDDL() { /// reseting TClonesArray /// after each DDL /// fDDLTracker->GetBlkHeaderArray()->Delete(); fGlitchErrors = 0; fParityErrBus.Reset(); } //______________________________________________________ void AliMUONPayloadTracker::SetMaxBlock(Int_t blk) { /// set regional card number if (blk > 2) blk = 2; fMaxBlock = blk; } //______________________________________________________ Bool_t AliMUONPayloadTracker::CheckDataParity() { /// parity check /// taken from MuTrkBusPatch.cxx (sotfware test for CROCUS) /// A. Baldisseri Int_t parity; UInt_t data; Int_t dataSize = fBusStruct->GetLength(); for (int idata = 0; idata < dataSize; idata++) { data = fBusStruct->GetData(idata); // Compute the parity for each data word parity = data & 0x1; for (Int_t i = 1; i <= 30; i++) parity ^= ((data >> i) & 0x1); // Check if (parity != fBusStruct->GetParity(idata)) { AliWarning(Form("Parity error in word %d for manuId %d and channel %d\n", idata, fBusStruct->GetManuId(idata), fBusStruct->GetChannelId(idata))); return kFALSE; } } return kTRUE; } //______________________________________________________ void AliMUONPayloadTracker::AddParityErrBus(Int_t buspatch) { /// adding bus with at least on parity error fParityErrBus.Set(fParityErrBus.GetSize() + 1); fParityErrBus.AddAt(buspatch, fParityErrBus.GetSize() - 1); } <|endoftext|>
<commit_before>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "app.h" #include "progressbar.h" #include "image/buffer.h" #include "image/voxel.h" #include "image/interp/nearest.h" #include "image/interp/linear.h" #include "image/interp/cubic.h" #include "image/interp/sinc.h" #include "image/filter/reslice.h" #include "image/utils.h" #include "image/loop.h" #include "image/copy.h" MRTRIX_APPLICATION using namespace MR; using namespace App; const char* interp_choices[] = { "nearest", "linear", "cubic", "sinc", NULL }; void usage () { DESCRIPTION + "apply spatial transformations or reslice images." + "In most cases, this command will only modify the transform matrix, " "without reslicing the image. Only the \"reslice\" option will " "actually modify the image data."; ARGUMENTS + Argument ("input", "input image to be transformed.").type_image_in () + Argument ("output", "the output image.").type_image_out (); OPTIONS + Option ("transform", "specify the 4x4 transform to apply, in the form of a 4x4 ascii file.") + Argument ("transform").type_file () + Option ("replace", "replace the transform of the original image by that specified, " "rather than applying it to the original image.") + Option ("inverse", "invert the specified transform before using it.") + Option ("reslice", "reslice the input image to match the specified template image.") + Argument ("template").type_image_in () + Option ("interp", "set the interpolation method to use when reslicing (default: linear).") + Argument ("method").type_choice (interp_choices) + Option ("oversample", "set the oversampling factor to use when reslicing (i.e. the " "number of samples to take per voxel along each spatial dimension). " "This should be supplied as a vector of 3 integers. By default, the " "oversampling factor is determined based on the differences between " "input and output voxel sizes.") + Argument ("factors").type_sequence_int() + DataType::options (); } typedef float value_type; void run () { Math::Matrix<float> operation; Options opt = get_options ("transform"); if (opt.size()) { operation.load (opt[0][0]); if (operation.rows() != 4 || operation.columns() != 4) throw Exception ("transform matrix supplied in file \"" + opt[0][0] + "\" is not 4x4"); } Image::Buffer<value_type> data_in (argument[0]); Image::Header header_out (data_in); header_out.datatype() = DataType::from_command_line (header_out.datatype()); bool inverse = get_options ("inverse").size(); bool replace = get_options ("replace").size(); if (inverse) { if (!operation.is_set()) throw Exception ("no transform provided for option '-inverse' (specify using '-transform' option)"); Math::Matrix<float> I; Math::LU::inv (I, operation); operation.swap (I); } if (replace) if (!operation.is_set()) throw Exception ("no transform provided for option '-replace' (specify using '-transform' option)"); opt = get_options ("reslice"); // need to reslice if (opt.size()) { std::string name = opt[0][0]; Image::ConstHeader template_header (name); header_out.dim(0) = template_header.dim (0); header_out.dim(1) = template_header.dim (1); header_out.dim(2) = template_header.dim (2); header_out.vox(0) = template_header.vox (0); header_out.vox(1) = template_header.vox (1); header_out.vox(2) = template_header.vox (2); header_out.transform() = template_header.transform(); header_out.comments().push_back ("resliced to reference image \"" + template_header.name() + "\""); int interp = 1; opt = get_options ("interp"); if (opt.size()) interp = opt[0][0]; std::vector<int> oversample; opt = get_options ("oversample"); if (opt.size()) { oversample = opt[0][0]; if (oversample.size() != 3) throw Exception ("option \"oversample\" expects a vector of 3 values"); if (oversample[0] < 1 || oversample[1] < 1 || oversample[2] < 1) throw Exception ("oversample factors must be greater than zero"); } if (replace) { Image::Info& info_in (data_in); info_in.transform().swap (operation); operation.clear(); } Image::Buffer<float>::voxel_type in (data_in); Image::Buffer<float> data_out (argument[1], header_out); Image::Buffer<float>::voxel_type out (data_out); switch (interp) { case 0: Image::Filter::reslice<Image::Interp::Nearest> (in, out, operation, oversample); break; case 1: Image::Filter::reslice<Image::Interp::Linear> (in, out, operation, oversample); break; case 2: Image::Filter::reslice<Image::Interp::Cubic> (in, out, operation, oversample); break; case 3: error ("FIXME: sinc interpolation needs a lot of work!"); Image::Filter::reslice<Image::Interp::Sinc> (in, out, operation, oversample); break; default: assert (0); } } else { // straight copy: if (operation.is_set()) { header_out.comments().push_back ("transform modified"); if (replace) header_out.transform().swap (operation); else { Math::Matrix<float> M (header_out.transform()); Math::mult (header_out.transform(), operation, M); } } Image::Buffer<float>::voxel_type in (data_in); Image::Buffer<float> data_out (argument[1], header_out); Image::Buffer<float>::voxel_type out (data_out); Image::copy_with_progress (in, out); } } <commit_msg>added new -vox option to mrtransform to allow resampling, etc.<commit_after>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include "app.h" #include "progressbar.h" #include "image/buffer.h" #include "image/voxel.h" #include "image/interp/nearest.h" #include "image/interp/linear.h" #include "image/interp/cubic.h" #include "image/interp/sinc.h" #include "image/filter/reslice.h" #include "image/utils.h" #include "image/loop.h" #include "image/copy.h" MRTRIX_APPLICATION using namespace MR; using namespace App; const char* interp_choices[] = { "nearest", "linear", "cubic", "sinc", NULL }; void usage () { DESCRIPTION + "apply spatial transformations or reslice images." + "In most cases, this command will only modify the transform matrix, " "without reslicing the image. Only the \"reslice\" option will " "actually modify the image data."; ARGUMENTS + Argument ("input", "input image to be transformed.").type_image_in () + Argument ("output", "the output image.").type_image_out (); OPTIONS + Option ("transform", "specify the 4x4 transform to apply, in the form of a 4x4 ascii file.") + Argument ("transform").type_file () + Option ("replace", "replace the transform of the original image by that specified, " "rather than applying it to the original image.") + Option ("inverse", "invert the specified transform before using it.") + Option ("reslice", "reslice the input image to match the specified template image.") + Argument ("template").type_image_in () + Option ("vox", "reslice the input image to match the specified voxel sizes, " "provided either as a single floating-point value to signify an " "isotropic voxel, or a comma-separated list of 3 values, one for " "each spatial axis. When the -reslice option has not also been " "speficied, the input image is used as template.") + Argument ("sizes").type_sequence_float () + Option ("interp", "set the interpolation method to use when reslicing (default: linear).") + Argument ("method").type_choice (interp_choices) + Option ("oversample", "set the oversampling factor to use when reslicing (i.e. the " "number of samples to take per voxel along each spatial dimension). " "This should be supplied as a vector of 3 integers. By default, the " "oversampling factor is determined based on the differences between " "input and output voxel sizes.") + Argument ("factors").type_sequence_int() + DataType::options (); } typedef float value_type; void run () { Math::Matrix<float> operation; Options opt = get_options ("transform"); if (opt.size()) { operation.load (opt[0][0]); if (operation.rows() != 4 || operation.columns() != 4) throw Exception ("transform matrix supplied in file \"" + opt[0][0] + "\" is not 4x4"); } Image::Buffer<value_type> data_in (argument[0]); Image::Header header_out (data_in); header_out.datatype() = DataType::from_command_line (header_out.datatype()); bool inverse = get_options ("inverse").size(); bool replace = get_options ("replace").size(); if (inverse) { if (!operation.is_set()) throw Exception ("no transform provided for option '-inverse' (specify using '-transform' option)"); Math::Matrix<float> I; Math::LU::inv (I, operation); operation.swap (I); } if (replace) if (!operation.is_set()) throw Exception ("no transform provided for option '-replace' (specify using '-transform' option)"); std::vector<float> new_voxel_sizes; opt = get_options ("vox"); if (opt.size()) { new_voxel_sizes = opt[0][0]; if (new_voxel_sizes.size() != 1 && new_voxel_sizes.size() != 3) throw Exception ("voxel sizes should be specified as a comma-separated list of 1 or 3 floating-point values"); for (size_t n = 0; n < new_voxel_sizes.size(); ++n) if (new_voxel_sizes[n] < 0.0) throw Exception ("voxel size must be positive"); if (new_voxel_sizes.size() == 1) { new_voxel_sizes.push_back (new_voxel_sizes[0]); new_voxel_sizes.push_back (new_voxel_sizes[0]); } } opt = get_options ("reslice"); // need to reslice if (opt.size() || new_voxel_sizes.size()) { if (opt.size()) { std::string name = opt[0][0]; Image::ConstHeader template_header (name); header_out.dim(0) = template_header.dim (0); header_out.dim(1) = template_header.dim (1); header_out.dim(2) = template_header.dim (2); header_out.vox(0) = template_header.vox (0); header_out.vox(1) = template_header.vox (1); header_out.vox(2) = template_header.vox (2); header_out.transform() = template_header.transform(); header_out.comments().push_back ("resliced to reference image \"" + template_header.name() + "\""); } if (new_voxel_sizes.size()) { float extent [] = { header_out.dim(0) * header_out.vox(0), header_out.dim(1) * header_out.vox(1), header_out.dim(2) * header_out.vox(2) }; header_out.vox(0) = new_voxel_sizes[0]; header_out.vox(1) = new_voxel_sizes[1]; header_out.vox(2) = new_voxel_sizes[2]; header_out.dim(0) = Math::ceil (extent[0] / new_voxel_sizes[0]); header_out.dim(1) = Math::ceil (extent[1] / new_voxel_sizes[1]); header_out.dim(2) = Math::ceil (extent[2] / new_voxel_sizes[2]); } int interp = 1; opt = get_options ("interp"); if (opt.size()) interp = opt[0][0]; std::vector<int> oversample; opt = get_options ("oversample"); if (opt.size()) { oversample = opt[0][0]; if (oversample.size() != 3) throw Exception ("option \"oversample\" expects a vector of 3 values"); if (oversample[0] < 1 || oversample[1] < 1 || oversample[2] < 1) throw Exception ("oversample factors must be greater than zero"); } if (replace) { Image::Info& info_in (data_in); info_in.transform().swap (operation); operation.clear(); } Image::Buffer<float>::voxel_type in (data_in); Image::Buffer<float> data_out (argument[1], header_out); Image::Buffer<float>::voxel_type out (data_out); switch (interp) { case 0: Image::Filter::reslice<Image::Interp::Nearest> (in, out, operation, oversample); break; case 1: Image::Filter::reslice<Image::Interp::Linear> (in, out, operation, oversample); break; case 2: Image::Filter::reslice<Image::Interp::Cubic> (in, out, operation, oversample); break; case 3: error ("FIXME: sinc interpolation needs a lot of work!"); Image::Filter::reslice<Image::Interp::Sinc> (in, out, operation, oversample); break; default: assert (0); } } else { // straight copy: if (operation.is_set()) { header_out.comments().push_back ("transform modified"); if (replace) header_out.transform().swap (operation); else { Math::Matrix<float> M (header_out.transform()); Math::mult (header_out.transform(), operation, M); } } Image::Buffer<float>::voxel_type in (data_in); Image::Buffer<float> data_out (argument[1], header_out); Image::Buffer<float>::voxel_type out (data_out); Image::copy_with_progress (in, out); } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMpManuList.h" #include "AliMpDEIterator.h" #include "AliMpDEManager.h" #include "AliMpSegmentation.h" #include "AliMpStationType.h" #include "AliMpCathodType.h" #include "AliMpVSegmentation.h" #include "TArrayI.h" #include "TList.h" /// /// \class AliMpManuList /// /// A sort of cache for mapping information we use often (or that are /// time consuming to recompute). /// /// \author Laurent Aphecetche /// \cond CLASSIMP ClassImp(AliMpManuList) /// \endcond //_____________________________________________________________________________ AliMpManuList::AliMpManuList() { /// ctor } //_____________________________________________________________________________ AliMpManuList::~AliMpManuList() { /// dtor } //_____________________________________________________________________________ Bool_t AliMpManuList::DoesChannelExist(Int_t detElemId, Int_t manuID, Int_t manuChannel) { /// Whether a given (detElemId,manuID,manuChannel) combination is a valid one const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentationByElectronics(detElemId,manuID); if (!seg) return kFALSE; if ( seg->PadByLocation(AliMpIntPair(manuID,manuChannel),kFALSE).IsValid() ) { return kTRUE; } else { return kFALSE; } } //_____________________________________________________________________________ TList* AliMpManuList::ManuList() { /// Create a TList of AliMpIntPair<detElemId,manuID> of all MUON TRK manus /// The returned list must be deleted by the client TList* manuList = new TList; manuList->SetOwner(kTRUE); AliMpDEIterator it; it.First(); while ( !it.IsDone() ) { Int_t detElemId = it.CurrentDEId(); AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId); if ( stationType != AliMp::kStationTrigger ) { for ( Int_t cath = AliMp::kCath0; cath <=AliMp::kCath1 ; ++cath ) { const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentation(detElemId,AliMp::GetCathodType(cath)); TArrayI manus; seg->GetAllElectronicCardIDs(manus); for ( Int_t im = 0; im < manus.GetSize(); ++im ) { manuList->Add(new AliMpIntPair(detElemId,manus[im])); } } } it.Next(); } return manuList; } //_____________________________________________________________________________ Int_t AliMpManuList::NumberOfChannels(Int_t detElemId, Int_t manuId) { /// Returns the number of channels in that manuID. Answer should be <=64 /// whatever happens. const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentationByElectronics(detElemId,manuId); Int_t n(0); for ( Int_t i = 0; i < 64; ++i ) { AliMpPad pad = seg->PadByLocation(AliMpIntPair(manuId,i),kFALSE); if (pad.IsValid()) ++n; } return n; } //_____________________________________________________________________________ Int_t AliMpManuList::NumberOfManus(Int_t detElemId) { /// Returns the number of manus contained in the given detection element. Int_t n(0); for ( Int_t i = AliMp::kCath0; i <= AliMp::kCath1; ++i ) { const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentation(detElemId,AliMp::GetCathodType(i)); TArrayI manus; seg->GetAllElectronicCardIDs(manus); n += manus.GetSize(); } return n; } <commit_msg>Remove one hard-coded constant (Laurent)<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMpManuList.h" #include "AliMpCathodType.h" #include "AliMpConstants.h" #include "AliMpDEIterator.h" #include "AliMpDEManager.h" #include "AliMpSegmentation.h" #include "AliMpStationType.h" #include "AliMpVSegmentation.h" #include "TArrayI.h" #include "TList.h" /// /// \class AliMpManuList /// /// A sort of cache for mapping information we use often (or that are /// time consuming to recompute). /// /// \author Laurent Aphecetche /// \cond CLASSIMP ClassImp(AliMpManuList) /// \endcond //_____________________________________________________________________________ AliMpManuList::AliMpManuList() { /// ctor } //_____________________________________________________________________________ AliMpManuList::~AliMpManuList() { /// dtor } //_____________________________________________________________________________ Bool_t AliMpManuList::DoesChannelExist(Int_t detElemId, Int_t manuID, Int_t manuChannel) { /// Whether a given (detElemId,manuID,manuChannel) combination is a valid one const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentationByElectronics(detElemId,manuID); if (!seg) return kFALSE; if ( seg->PadByLocation(AliMpIntPair(manuID,manuChannel),kFALSE).IsValid() ) { return kTRUE; } else { return kFALSE; } } //_____________________________________________________________________________ TList* AliMpManuList::ManuList() { /// Create a TList of AliMpIntPair<detElemId,manuID> of all MUON TRK manus /// The returned list must be deleted by the client TList* manuList = new TList; manuList->SetOwner(kTRUE); AliMpDEIterator it; it.First(); while ( !it.IsDone() ) { Int_t detElemId = it.CurrentDEId(); AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId); if ( stationType != AliMp::kStationTrigger ) { for ( Int_t cath = AliMp::kCath0; cath <=AliMp::kCath1 ; ++cath ) { const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentation(detElemId,AliMp::GetCathodType(cath)); TArrayI manus; seg->GetAllElectronicCardIDs(manus); for ( Int_t im = 0; im < manus.GetSize(); ++im ) { manuList->Add(new AliMpIntPair(detElemId,manus[im])); } } } it.Next(); } return manuList; } //_____________________________________________________________________________ Int_t AliMpManuList::NumberOfChannels(Int_t detElemId, Int_t manuId) { /// Returns the number of channels in that manuID. Answer should be <=64 /// whatever happens. const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentationByElectronics(detElemId,manuId); Int_t n(0); for ( Int_t i = 0; i < AliMpConstants::ManuNofChannels(); ++i ) { AliMpPad pad = seg->PadByLocation(AliMpIntPair(manuId,i),kFALSE); if (pad.IsValid()) ++n; } return n; } //_____________________________________________________________________________ Int_t AliMpManuList::NumberOfManus(Int_t detElemId) { /// Returns the number of manus contained in the given detection element. Int_t n(0); for ( Int_t i = AliMp::kCath0; i <= AliMp::kCath1; ++i ) { const AliMpVSegmentation* seg = AliMpSegmentation::Instance() ->GetMpSegmentation(detElemId,AliMp::GetCathodType(i)); TArrayI manus; seg->GetAllElectronicCardIDs(manus); n += manus.GetSize(); } return n; } <|endoftext|>
<commit_before>// Copyright (C) 2018 Egor Pugin <[email protected]> // // 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 <primitives/executor.h> #include <primitives/debug.h> #include <primitives/exceptions.h> #include <primitives/thread.h> #include <atomic> #include <iostream> #include <string> #ifdef _WIN32 #include <windows.h> #endif //#include "log.h" //DECLARE_STATIC_LOGGER(logger, "executor"); size_t get_max_threads(int N) { return std::max<size_t>(N, std::thread::hardware_concurrency()); } size_t select_number_of_threads(int N) { if (N > 0) return N; N = std::thread::hardware_concurrency(); if (N == 1) N = 2; else if (N <= 8) N += 2; else if (N <= 64) N += 4; else N += 8; return N; } SW_DEFINE_GLOBAL_STATIC_FUNCTION(Executor, getExecutor) Executor::Executor(const std::string &name, size_t nThreads) : Executor(nThreads, name) { } Executor::Executor(size_t nThreads, const std::string &name) : nThreads(nThreads) { // we keep this lock until all threads created and assigned to thread_pool var // this is to prevent races on data objects std::unique_lock<std::mutex> lk(m); std::atomic<decltype(nThreads)> barrier{ 0 }; thread_pool.resize(nThreads); for (size_t i = 0; i < nThreads; i++) { thread_pool[i].t = make_thread([this, i, name = name, &barrier, nThreads]() mutable { // set tids early { std::unique_lock<std::mutex> lk(m); thread_ids[std::this_thread::get_id()] = i; ++barrier; } // wait when all threads set their tids while (barrier != nThreads) std::this_thread::sleep_for(std::chrono::microseconds(1)); // proceed run(i, name); }); } // allow threads to run lk.unlock(); // wait when all threads set their tids while (barrier != nThreads) std::this_thread::sleep_for(std::chrono::microseconds(1)); } Executor::~Executor() { join(); } size_t Executor::get_n() const { return thread_ids.find(std::this_thread::get_id())->second; } bool Executor::is_in_executor() const { return thread_ids.find(std::this_thread::get_id()) != thread_ids.end(); } bool Executor::try_run_one() { auto t = try_pop(); if (t) run_task(t); return !!t; } void Executor::run(size_t i, const std::string &name) { auto n = name; if (!n.empty()) n += " "; n += std::to_string(i); primitives::setThreadName(n); while (!stopped_) { if (!run_task()) break; } } bool Executor::run_task() { return run_task(get_n()); } bool Executor::run_task(Task &t) { run_task(get_n(), t); return true; } bool Executor::run_task(size_t i) { auto t = get_task(i); // double check if (stopped_) return false; run_task(i, t); return true; } void Executor::run_task(size_t i, Task &t) noexcept { primitives::ScopedThreadName stn(std::to_string(i) + " busy"); auto &thr = thread_pool[i]; t(); thr.busy = false; } Task Executor::get_task() { return get_task(get_n()); } Task Executor::get_task(size_t i) { auto &thr = thread_pool[i]; Task t = try_pop(i); // no task popped, probably shutdown command was issues if (!t && !thr.q.pop(t, thr.busy)) return Task(); return t; } Task Executor::get_task_non_stealing() { return get_task_non_stealing(get_n()); } Task Executor::get_task_non_stealing(size_t i) { auto &thr = thread_pool[i]; Task t; if (thr.q.pop(t, thr.busy)) return t; return Task(); } void Executor::join() { wait(); stop(); for (auto &t : thread_pool) { if (t.t.joinable()) t.t.join(); } } void Executor::stop() { stopped_ = true; for (auto &t : thread_pool) t.q.done(); } void Executor::wait(WaitStatus p) { std::unique_lock<std::mutex> lk(m_wait, std::try_to_lock); if (!lk.owns_lock()) { std::unique_lock<std::mutex> lk(m_wait); return; } waiting_ = p; bool run_again = is_in_executor(); // wait for empty queues for (auto &t : thread_pool) { while (!t.q.empty() && !stopped_) { if (run_again) { // finish everything for (auto &t : thread_pool) { Task ta; if (t.q.try_pop(ta, thread_pool[get_n()].busy)) run_task(get_n(), ta); } } else std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } // free self if (run_again) thread_pool[get_n()].busy = false; // wait for end of execution for (auto &t : thread_pool) { while (t.busy && !stopped_) std::this_thread::sleep_for(std::chrono::milliseconds(100)); } waiting_ = WaitStatus::Running; cv_wait.notify_all(); } void Executor::push(Task &&t) { if (waiting_ == WaitStatus::RejectIncoming) throw SW_RUNTIME_ERROR("Executor is in the wait state and rejects new jobs"); if (waiting_ == WaitStatus::BlockIncoming) { std::unique_lock<std::mutex> lk(m_wait); cv_wait.wait(lk, [this] { return waiting_ == WaitStatus::Running; }); } auto i = index++; for (size_t n = 0; n != nThreads; ++n) { if (thread_pool[(i + n) % nThreads].q.try_push(std::move(t))) return; } thread_pool[i % nThreads].q.push(std::move(t)); } Task Executor::try_pop() { return try_pop(get_n()); } Task Executor::try_pop(size_t i) { Task t; const size_t spin_count = nThreads * 4; for (auto n = 0; n != spin_count; ++n) { if (thread_pool[(i + n) % nThreads].q.try_pop(t, thread_pool[i].busy)) break; } return t; } bool Executor::empty() const { return std::all_of(thread_pool.begin(), thread_pool.end(), [](const auto &t) { return t.empty(); }); } <commit_msg>[executor] Better data race fix.<commit_after>// Copyright (C) 2018 Egor Pugin <[email protected]> // // 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 <primitives/executor.h> #include <primitives/debug.h> #include <primitives/exceptions.h> #include <primitives/thread.h> #include <atomic> #include <iostream> #include <string> #ifdef _WIN32 #include <windows.h> #endif //#include "log.h" //DECLARE_STATIC_LOGGER(logger, "executor"); size_t get_max_threads(int N) { return std::max<size_t>(N, std::thread::hardware_concurrency()); } size_t select_number_of_threads(int N) { if (N > 0) return N; N = std::thread::hardware_concurrency(); if (N == 1) N = 2; else if (N <= 8) N += 2; else if (N <= 64) N += 4; else N += 8; return N; } SW_DEFINE_GLOBAL_STATIC_FUNCTION(Executor, getExecutor) Executor::Executor(const std::string &name, size_t nThreads) : Executor(nThreads, name) { } Executor::Executor(size_t nThreads, const std::string &name) : nThreads(nThreads) { // we keep this lock until all threads created and assigned to thread_pool var // this is to prevent races on data objects std::unique_lock<std::mutex> lk(m); std::atomic<decltype(nThreads)> barrier{ 0 }; std::atomic<decltype(nThreads)> barrier2{ 0 }; thread_pool.resize(nThreads); for (size_t i = 0; i < nThreads; i++) { thread_pool[i].t = make_thread([this, i, name = name, &barrier, &barrier2, nThreads]() mutable { // set tids early { std::unique_lock<std::mutex> lk(m); thread_ids[std::this_thread::get_id()] = i; ++barrier; } // wait when all threads set their tids while (barrier != nThreads) std::this_thread::sleep_for(std::chrono::microseconds(1)); // allow to proceed main thread ++barrier2; // proceed run(i, name); }); } // allow threads to run lk.unlock(); // wait when all threads set their tids while (barrier2 != nThreads) std::this_thread::sleep_for(std::chrono::microseconds(1)); } Executor::~Executor() { join(); } size_t Executor::get_n() const { return thread_ids.find(std::this_thread::get_id())->second; } bool Executor::is_in_executor() const { return thread_ids.find(std::this_thread::get_id()) != thread_ids.end(); } bool Executor::try_run_one() { auto t = try_pop(); if (t) run_task(t); return !!t; } void Executor::run(size_t i, const std::string &name) { auto n = name; if (!n.empty()) n += " "; n += std::to_string(i); primitives::setThreadName(n); while (!stopped_) { if (!run_task()) break; } } bool Executor::run_task() { return run_task(get_n()); } bool Executor::run_task(Task &t) { run_task(get_n(), t); return true; } bool Executor::run_task(size_t i) { auto t = get_task(i); // double check if (stopped_) return false; run_task(i, t); return true; } void Executor::run_task(size_t i, Task &t) noexcept { primitives::ScopedThreadName stn(std::to_string(i) + " busy"); auto &thr = thread_pool[i]; t(); thr.busy = false; } Task Executor::get_task() { return get_task(get_n()); } Task Executor::get_task(size_t i) { auto &thr = thread_pool[i]; Task t = try_pop(i); // no task popped, probably shutdown command was issues if (!t && !thr.q.pop(t, thr.busy)) return Task(); return t; } Task Executor::get_task_non_stealing() { return get_task_non_stealing(get_n()); } Task Executor::get_task_non_stealing(size_t i) { auto &thr = thread_pool[i]; Task t; if (thr.q.pop(t, thr.busy)) return t; return Task(); } void Executor::join() { wait(); stop(); for (auto &t : thread_pool) { if (t.t.joinable()) t.t.join(); } } void Executor::stop() { stopped_ = true; for (auto &t : thread_pool) t.q.done(); } void Executor::wait(WaitStatus p) { std::unique_lock<std::mutex> lk(m_wait, std::try_to_lock); if (!lk.owns_lock()) { std::unique_lock<std::mutex> lk(m_wait); return; } waiting_ = p; bool run_again = is_in_executor(); // wait for empty queues for (auto &t : thread_pool) { while (!t.q.empty() && !stopped_) { if (run_again) { // finish everything for (auto &t : thread_pool) { Task ta; if (t.q.try_pop(ta, thread_pool[get_n()].busy)) run_task(get_n(), ta); } } else std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } // free self if (run_again) thread_pool[get_n()].busy = false; // wait for end of execution for (auto &t : thread_pool) { while (t.busy && !stopped_) std::this_thread::sleep_for(std::chrono::milliseconds(100)); } waiting_ = WaitStatus::Running; cv_wait.notify_all(); } void Executor::push(Task &&t) { if (waiting_ == WaitStatus::RejectIncoming) throw SW_RUNTIME_ERROR("Executor is in the wait state and rejects new jobs"); if (waiting_ == WaitStatus::BlockIncoming) { std::unique_lock<std::mutex> lk(m_wait); cv_wait.wait(lk, [this] { return waiting_ == WaitStatus::Running; }); } auto i = index++; for (size_t n = 0; n != nThreads; ++n) { if (thread_pool[(i + n) % nThreads].q.try_push(std::move(t))) return; } thread_pool[i % nThreads].q.push(std::move(t)); } Task Executor::try_pop() { return try_pop(get_n()); } Task Executor::try_pop(size_t i) { Task t; const size_t spin_count = nThreads * 4; for (auto n = 0; n != spin_count; ++n) { if (thread_pool[(i + n) % nThreads].q.try_pop(t, thread_pool[i].busy)) break; } return t; } bool Executor::empty() const { return std::all_of(thread_pool.begin(), thread_pool.end(), [](const auto &t) { return t.empty(); }); } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. 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. // testing #include "open_spiel/games/amazons.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/spiel_utils.h" #include "open_spiel/utils/tensor_view.h" namespace open_spiel { namespace amazons { namespace { // Facts about the game. const GameType kGameType{ /*short_name=*/"amazons", /*long_name=*/"Amazons", GameType::Dynamics::kSequential, GameType::ChanceMode::kDeterministic, GameType::Information::kPerfectInformation, GameType::Utility::kZeroSum, GameType::RewardModel::kTerminal, /*max_num_players=*/2, /*min_num_players=*/2, /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/false, /*provides_observation_string=*/true, /*provides_observation_tensor=*/true, /*parameter_specification=*/{} // no parameters }; std::shared_ptr<const Game> Factory(const GameParameters &params) { return std::shared_ptr<const Game>(new AmazonsGame(params)); } REGISTER_SPIEL_GAME(kGameType, Factory); } // namespace CellState PlayerToState(Player player) { switch (player) { case 0: return CellState::kCross; case 1: return CellState::kNought; default: SpielFatalError(absl::StrCat("Invalid player id ", player)); return CellState::kEmpty; } } std::string StateToString(CellState state) { switch (state) { case CellState::kEmpty: return "."; case CellState::kNought: return "O"; case CellState::kCross: return "X"; case CellState::kBlock: return "#"; default: SpielFatalError("Unknown state."); } } /* Move generation functions */ std::vector<Action> AmazonsState::GetHorizontalMoves(Action cell) const { std::vector<Action> horizontalMoves; unsigned char col = cell % kNumRows; // The column the cell is in unsigned char left = col; // The maximum amount of spaces to check left of given cell unsigned char right = kNumCols - col - 1; // The maximal amount of spaces to check right of given cell Action focus; // <-----X // Walk until we encounter a blocking piece or end of row int count = 1; while (count <= left) { focus = cell - count; if (board_[focus] == CellState::kEmpty) { horizontalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // X----> // Walk until we encounter a blocking piece or end of row count = 1; while (count <= right) { focus = cell + count; if (board_[focus] == CellState::kEmpty) { horizontalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return horizontalMoves; } std::vector<Action> AmazonsState::GetVerticalMoves(Action cell) const { std::vector<Action> verticalMoves; unsigned char row = cell / kNumRows; // The row the cell is in unsigned char up = row; // The maximum amount of spaces to check up of given cell unsigned char down = kNumRows - row - 1; // The maximal amount of spaces to check down of given cell Action focus; // ^ // | // | // X // Walk until we encounter a blocking piece or end of column int count = 1; focus = cell; while (count <= up) { focus -= kNumRows; if (board_[focus] == CellState::kEmpty) { verticalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // X // | // | // V // Walk until we encounter a blocking piece or end of column count = 1; focus = cell; while (count <= down) { focus += kNumRows; if (board_[focus] == CellState::kEmpty) { verticalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return verticalMoves; } std::vector<Action> AmazonsState::GetDiagonalMoves(Action cell) const { std::vector<Action> diagonalMoves; unsigned char col = cell % kNumCols; // The column the cell is in unsigned char row = cell / kNumRows; // The row the cell is in unsigned char upLeft = std::min( row, col); // The maximum amount of spaces to check up and left of given cell unsigned char upRight = std::min( row, (unsigned char)(kNumCols - col - 1)); // The maximum amount of spaces to // check up and right of given cell // The maximum amount of spaces to check // down and left of given cell unsigned char downLeft = std::min(static_cast<unsigned char>(kNumRows - row - 1), col); // The maximum amount of spaces to check down // and right of given cell unsigned char downRight = std::min(static_cast<unsigned char>(kNumRows - row - 1), static_cast<unsigned char>(kNumCols - col - 1)); Action focus; // Up and left int count = 1; focus = cell; while (count <= upLeft) { focus -= (kNumRows + 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Up and right count = 1; focus = cell; while (count <= upRight) { focus -= (kNumRows - 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Down and left count = 1; focus = cell; while (count <= downLeft) { focus += (kNumRows - 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Down and right count = 1; focus = cell; while (count <= downRight) { focus += (kNumRows + 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return diagonalMoves; } std::vector<Action> AmazonsState::GetAllMoves(Action cell) const { std::vector<Action> horizontals = GetHorizontalMoves(cell); std::vector<Action> verticals = GetVerticalMoves(cell); std::vector<Action> diagonals = GetDiagonalMoves(cell); std::vector<Action> acc = horizontals; acc.insert(acc.end(), verticals.begin(), verticals.end()); acc.insert(acc.end(), diagonals.begin(), diagonals.end()); return acc; } void AmazonsState::DoApplyAction(Action action) { switch (state_) { case amazon_select: { SPIEL_CHECK_EQ(board_[action], PlayerToState(CurrentPlayer())); from_ = action; board_[from_] = CellState::kEmpty; state_ = destination_select; } break; case destination_select: { SPIEL_CHECK_EQ(board_[action], CellState::kEmpty); to_ = action; board_[to_] = PlayerToState(CurrentPlayer()); state_ = shot_select; break; } case shot_select: { SPIEL_CHECK_EQ(board_[action], CellState::kEmpty); shoot_ = action; board_[shoot_] = CellState::kBlock; current_player_ = 1 - current_player_; state_ = amazon_select; // Check if game is over if (LegalActions().empty()) { // outcome = winner outcome_ = 1 - current_player_; } } break; } ++num_moves_; } void AmazonsState::UndoAction(Player player, Action move) { switch (state_) { case amazon_select: { shoot_ = move; board_[shoot_] = CellState::kEmpty; current_player_ = player; outcome_ = kInvalidPlayer; state_ = shot_select; } break; case destination_select: { from_ = move; board_[from_] = PlayerToState(player); state_ = amazon_select; } break; case shot_select: { to_ = move; board_[to_] = CellState::kEmpty; state_ = destination_select; } break; } --num_moves_; --move_number_; history_.pop_back(); } std::vector<Action> AmazonsState::LegalActions() const { if (IsTerminal()) return {}; std::vector<Action> actions; switch (state_) { case amazon_select: for (int i = 0; i < board_.size(); i++) { if (board_[i] == PlayerToState(CurrentPlayer())) { // check if the selected amazon has a possible move if (GetAllMoves(i).empty()) continue; actions.push_back(i); } } break; case destination_select: actions = GetAllMoves(from_); break; case shot_select: actions = GetAllMoves(to_); break; } sort(actions.begin(), actions.end()); return actions; } std::string AmazonsState::ActionToString(Player player, Action action) const { std::string str = absl::StrCat("(", (action / kNumRows) + 1, ", ", (action % kNumRows) + 1, ")"); switch (state_) { case amazon_select: return absl::StrCat(StateToString(PlayerToState(player)), " From ", str); case destination_select: return absl::StrCat(StateToString(PlayerToState(player)), " To ", str); case shot_select: return absl::StrCat(StateToString(PlayerToState(player)), " Shoot: ", str); } } // Looks okay AmazonsState::AmazonsState(std::shared_ptr<const Game> game) : State(game) { std::fill(begin(board_), end(board_), CellState::kEmpty); switch (kNumRows) { case 6: board_[1] = board_[4] = board_[6] = board_[11] = CellState::kCross; board_[24] = board_[29] = board_[31] = board_[34] = CellState::kNought; break; case 8: board_[2] = board_[5] = board_[16] = board_[23] = CellState::kCross; board_[40] = board_[47] = board_[58] = board_[61] = CellState::kNought; break; } } void AmazonsState::SetState(int cur_player, MoveState move_state, const std::array<CellState, kNumCells>& board) { current_player_ = cur_player; state_ = move_state; board_ = board; } std::string AmazonsState::ToString() const { std::string str; for (int r = 0; r < kNumRows; ++r) { for (int c = 0; c < kNumCols; ++c) { absl::StrAppend(&str, StateToString(BoardAt(r, c))); } if (r < (kNumRows - 1)) { absl::StrAppend(&str, "\n"); } } return str; } bool AmazonsState::IsTerminal() const { return outcome_ != kInvalidPlayer; } std::vector<double> AmazonsState::Returns() const { if (outcome_ == (Player{0})) { return {1.0, -1.0}; } else if (outcome_ == (Player{1})) { return {-1.0, 1.0}; } else { return {0.0, 0.0}; } } std::string AmazonsState::InformationStateString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return HistoryString(); } std::string AmazonsState::ObservationString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return ToString(); } void AmazonsState::ObservationTensor(Player player, absl::Span<float> values) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); // Treat `values` as a 2-d tensor. TensorView<2> view(values, {kCellStates, kNumCells}, true); for (int cell = 0; cell < kNumCells; ++cell) { view[{static_cast<int>(board_[cell]), cell}] = 1.0; } } std::unique_ptr<State> AmazonsState::Clone() const { return std::unique_ptr<State>(new AmazonsState(*this)); } AmazonsGame::AmazonsGame(const GameParameters &params) : Game(kGameType, params) {} } // namespace amazons } // namespace open_spiel <commit_msg>Update amazons.cc<commit_after>// Copyright 2019 DeepMind Technologies Ltd. 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. // testing #include "open_spiel/games/amazons.h" #include <algorithm> #include <memory> #include <utility> #include <vector> #include "open_spiel/abseil-cpp/absl/strings/str_cat.h" #include "open_spiel/spiel_utils.h" #include "open_spiel/utils/tensor_view.h" namespace open_spiel { namespace amazons { namespace { // Facts about the game. const GameType kGameType{ /*short_name=*/"amazons", /*long_name=*/"Amazons", GameType::Dynamics::kSequential, GameType::ChanceMode::kDeterministic, GameType::Information::kPerfectInformation, GameType::Utility::kZeroSum, GameType::RewardModel::kTerminal, /*max_num_players=*/2, /*min_num_players=*/2, /*provides_information_state_string=*/true, /*provides_information_state_tensor=*/false, /*provides_observation_string=*/true, /*provides_observation_tensor=*/true, /*parameter_specification=*/{} // no parameters }; std::shared_ptr<const Game> Factory(const GameParameters &params) { return std::shared_ptr<const Game>(new AmazonsGame(params)); } REGISTER_SPIEL_GAME(kGameType, Factory); } // namespace CellState PlayerToState(Player player) { switch (player) { case 0: return CellState::kCross; case 1: return CellState::kNought; default: SpielFatalError(absl::StrCat("Invalid player id ", player)); return CellState::kEmpty; } } std::string StateToString(CellState state) { switch (state) { case CellState::kEmpty: return "."; case CellState::kNought: return "O"; case CellState::kCross: return "X"; case CellState::kBlock: return "#"; default: SpielFatalError("Unknown state."); } } /* Move generation functions */ std::vector<Action> AmazonsState::GetHorizontalMoves(Action cell) const { std::vector<Action> horizontalMoves; unsigned char col = cell % kNumRows; // The column the cell is in unsigned char left = col; // The maximum amount of spaces to check left of given cell unsigned char right = kNumCols - col - 1; // The maximal amount of spaces to check right of given cell Action focus; // <-----X // Walk until we encounter a blocking piece or end of row int count = 1; while (count <= left) { focus = cell - count; if (board_[focus] == CellState::kEmpty) { horizontalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // X----> // Walk until we encounter a blocking piece or end of row count = 1; while (count <= right) { focus = cell + count; if (board_[focus] == CellState::kEmpty) { horizontalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return horizontalMoves; } std::vector<Action> AmazonsState::GetVerticalMoves(Action cell) const { std::vector<Action> verticalMoves; unsigned char row = cell / kNumRows; // The row the cell is in unsigned char up = row; // The maximum amount of spaces to check up of given cell unsigned char down = kNumRows - row - 1; // The maximal amount of spaces to check down of given cell Action focus; // ^ // | // | // X // Walk until we encounter a blocking piece or end of column int count = 1; focus = cell; while (count <= up) { focus -= kNumRows; if (board_[focus] == CellState::kEmpty) { verticalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // X // | // | // V // Walk until we encounter a blocking piece or end of column count = 1; focus = cell; while (count <= down) { focus += kNumRows; if (board_[focus] == CellState::kEmpty) { verticalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return verticalMoves; } std::vector<Action> AmazonsState::GetDiagonalMoves(Action cell) const { std::vector<Action> diagonalMoves; unsigned char col = cell % kNumCols; // The column the cell is in unsigned char row = cell / kNumRows; // The row the cell is in unsigned char upLeft = std::min( row, col); // The maximum amount of spaces to check up and left of given cell unsigned char upRight = std::min( row, (unsigned char)(kNumCols - col - 1)); // The maximum amount of spaces to // check up and right of given cell // The maximum amount of spaces to check // down and left of given cell unsigned char downLeft = std::min(static_cast<unsigned char>(kNumRows - row - 1), col); // The maximum amount of spaces to check down // and right of given cell unsigned char downRight = std::min(static_cast<unsigned char>(kNumRows - row - 1), static_cast<unsigned char>(kNumCols - col - 1)); Action focus; // Up and left int count = 1; focus = cell; while (count <= upLeft) { focus -= (kNumRows + 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Up and right count = 1; focus = cell; while (count <= upRight) { focus -= (kNumRows - 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Down and left count = 1; focus = cell; while (count <= downLeft) { focus += (kNumRows - 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } // Down and right count = 1; focus = cell; while (count <= downRight) { focus += (kNumRows + 1); if (board_[focus] == CellState::kEmpty) { diagonalMoves.push_back(focus); count++; } else { // We have encountered a blocking piece break; } } return diagonalMoves; } std::vector<Action> AmazonsState::GetAllMoves(Action cell) const { std::vector<Action> horizontals = GetHorizontalMoves(cell); std::vector<Action> verticals = GetVerticalMoves(cell); std::vector<Action> diagonals = GetDiagonalMoves(cell); std::vector<Action> acc = horizontals; acc.insert(acc.end(), verticals.begin(), verticals.end()); acc.insert(acc.end(), diagonals.begin(), diagonals.end()); return acc; } void AmazonsState::DoApplyAction(Action action) { switch (state_) { case amazon_select: { SPIEL_CHECK_EQ(board_[action], PlayerToState(CurrentPlayer())); from_ = action; board_[from_] = CellState::kEmpty; state_ = destination_select; } break; case destination_select: { SPIEL_CHECK_EQ(board_[action], CellState::kEmpty); to_ = action; board_[to_] = PlayerToState(CurrentPlayer()); state_ = shot_select; break; } case shot_select: { SPIEL_CHECK_EQ(board_[action], CellState::kEmpty); shoot_ = action; board_[shoot_] = CellState::kBlock; current_player_ = 1 - current_player_; state_ = amazon_select; // Check if game is over if (LegalActions().empty()) { // outcome = winner outcome_ = 1 - current_player_; } } break; } ++num_moves_; } void AmazonsState::UndoAction(Player player, Action move) { switch (state_) { case amazon_select: { shoot_ = move; board_[shoot_] = CellState::kEmpty; current_player_ = player; outcome_ = kInvalidPlayer; state_ = shot_select; } break; case destination_select: { from_ = move; board_[from_] = PlayerToState(player); state_ = amazon_select; } break; case shot_select: { to_ = move; board_[to_] = CellState::kEmpty; state_ = destination_select; } break; } --num_moves_; --move_number_; history_.pop_back(); } std::vector<Action> AmazonsState::LegalActions() const { if (IsTerminal()) return {}; std::vector<Action> actions; switch (state_) { case amazon_select: for (int i = 0; i < board_.size(); i++) { if (board_[i] == PlayerToState(CurrentPlayer())) { // check if the selected amazon has a possible move if (GetAllMoves(i).empty()) continue; actions.push_back(i); } } break; case destination_select: actions = GetAllMoves(from_); break; case shot_select: actions = GetAllMoves(to_); break; } sort(actions.begin(), actions.end()); return actions; } std::string AmazonsState::ActionToString(Player player, Action action) const { std::string str = absl::StrCat("(", (action / kNumRows) + 1, ", ", (action % kNumRows) + 1, ")"); switch (state_) { case amazon_select: return absl::StrCat(StateToString(PlayerToState(player)), " From ", str); case destination_select: return absl::StrCat(StateToString(PlayerToState(player)), " To ", str); case shot_select: return absl::StrCat(StateToString(PlayerToState(player)), " Shoot: ", str); } std::cerr << "Unhandled case in AmazonState::ActionToString, " << "returning empty string." << std::endl; return ""; } // Looks okay AmazonsState::AmazonsState(std::shared_ptr<const Game> game) : State(game) { std::fill(begin(board_), end(board_), CellState::kEmpty); switch (kNumRows) { case 6: board_[1] = board_[4] = board_[6] = board_[11] = CellState::kCross; board_[24] = board_[29] = board_[31] = board_[34] = CellState::kNought; break; case 8: board_[2] = board_[5] = board_[16] = board_[23] = CellState::kCross; board_[40] = board_[47] = board_[58] = board_[61] = CellState::kNought; break; } } void AmazonsState::SetState(int cur_player, MoveState move_state, const std::array<CellState, kNumCells>& board) { current_player_ = cur_player; state_ = move_state; board_ = board; } std::string AmazonsState::ToString() const { std::string str; for (int r = 0; r < kNumRows; ++r) { for (int c = 0; c < kNumCols; ++c) { absl::StrAppend(&str, StateToString(BoardAt(r, c))); } if (r < (kNumRows - 1)) { absl::StrAppend(&str, "\n"); } } return str; } bool AmazonsState::IsTerminal() const { return outcome_ != kInvalidPlayer; } std::vector<double> AmazonsState::Returns() const { if (outcome_ == (Player{0})) { return {1.0, -1.0}; } else if (outcome_ == (Player{1})) { return {-1.0, 1.0}; } else { return {0.0, 0.0}; } } std::string AmazonsState::InformationStateString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return HistoryString(); } std::string AmazonsState::ObservationString(Player player) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); return ToString(); } void AmazonsState::ObservationTensor(Player player, absl::Span<float> values) const { SPIEL_CHECK_GE(player, 0); SPIEL_CHECK_LT(player, num_players_); // Treat `values` as a 2-d tensor. TensorView<2> view(values, {kCellStates, kNumCells}, true); for (int cell = 0; cell < kNumCells; ++cell) { view[{static_cast<int>(board_[cell]), cell}] = 1.0; } } std::unique_ptr<State> AmazonsState::Clone() const { return std::unique_ptr<State>(new AmazonsState(*this)); } AmazonsGame::AmazonsGame(const GameParameters &params) : Game(kGameType, params) {} } // namespace amazons } // namespace open_spiel <|endoftext|>
<commit_before>/* Copyright (c) 2010 Ariya Hidayat <[email protected]> Copyright (c) 2009 Einar Lielmanis Copyright (c) 2010 Nicolas Ferrero <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <v8.h> #include <string.h> #include "beautify.h" using namespace v8; Handle<String> readFile(const char* name) { FILE* file = fopen(name, "rb"); if (file == NULL) { return Handle<String>(); } fseek(file, 0, SEEK_END); int len = ftell(file); rewind(file); char* buf = new char[len + 1]; buf[len] = '\0'; fread(buf, 1, len, file); fclose(file); Handle<String> result = String::New(buf); delete[] buf; return result; } void writeFile(Handle<Value> result, const char* name) { if (result.IsEmpty() || result->IsUndefined()) return; FILE* file = stdout; if (name) { file = fopen(name, "wt"); if (file == NULL) return; } String::Utf8Value str(result); fprintf(file, "%s\n", *str); if (name) fclose(file); } static void usage(char* progname) { printf("Usage: %s [options] source-file\n", progname); printf("[options]\n"); printf(" --overwrite : Overwrite source-file (use with care!)\n"); printf(" --indent-size or -s: Indentation size. (default 4)\n"); printf(" --indent-char or -c: Character to indent with. (default space)\n"); printf(" --disable-preserve-newlines or -d: Do not preserve existing line breaks.\n"); printf(" --indent-level or -l: Initial indentation level, you probably won't need this ever. (default 0)\n"); printf(" --space-after-anon-function or -f: Space is added between \"function ()\", otherwise the common \"function()\" output is used.\n"); printf(" --braces-on-own-line or -b: ANSI / Allman brace style, each opening/closing brace gets its own line.\n"); printf(" --keep-array-indentation or -k: Keep array indentation.\n"); printf(" --help or -h: Prints this help statement.\n"); } int main(int argc, char* argv[]) { Handle<String> source; HandleScope handle_scope; Handle<ObjectTemplate> global = ObjectTemplate::New(); Handle<ObjectTemplate> options = ObjectTemplate::New(); bool overwrite = false; const char* output = 0; for (int argpos = 1; argpos < argc; ++argpos) { if (argv[argpos][0] != '-') { source = readFile(argv[argpos]); output = argv[argpos]; } else if (strcmp(argv[argpos], "--overwrite") == 0) { overwrite = true; } else if (strcmp(argv[argpos], "--indent-size") == 0 || strcmp(argv[argpos], "-s") == 0) { options->Set("indent_size", String::New(argv[argpos+1])); } else if (strcmp(argv[argpos], "--indent-char") == 0 || strcmp(argv[argpos], "-c") == 0) { options->Set("indent_char", String::New(argv[argpos+1])); } else if (strcmp(argv[argpos], "--disable-preserve-newlines") == 0 || strcmp(argv[argpos], "-d") == 0) { options->Set("preserve_newlines", Boolean::New(false)); } else if (strcmp(argv[argpos], "--indent-level") == 0 || strcmp(argv[argpos], "-l") == 0) { options->Set("indent_level", String::New(argv[argpos+1])); } else if (strcmp(argv[argpos], "--space-after-anon-function") == 0 || strcmp(argv[argpos], "-f") == 0) { options->Set("space_after_anon_function", Boolean::New(true)); } else if (strcmp(argv[argpos], "--braces-on-own-line") == 0 || strcmp(argv[argpos], "-b") == 0) { options->Set("braces_on_own_line", Boolean::New(true)); } else if (strcmp(argv[argpos], "--keep-array-indentation") == 0 || strcmp(argv[argpos], "-k") == 0) { options->Set("keep_array_indentation", Boolean::New(true)); } else if (strcmp(argv[argpos], "--help") == 0 || strcmp(argv[argpos], "-h") == 0) { usage(argv[0]); return -1; } } if (source.IsEmpty()) { usage(argv[0]); return -1; } global->Set("source", source); global->Set("options", options); Handle<Context> context = Context::New(NULL, global); Context::Scope context_scope(context); Handle<Script> beautifyScript = Script::Compile(String::New(beautify_code)); beautifyScript->Run(); Handle<Script> runnerScript = Script::Compile(String::New("js_beautify(source, options);")); Handle<Value> result = runnerScript->Run(); writeFile(result, overwrite ? output : 0); return 0; } <commit_msg>added ability to read from stdin for use with vim autocmd<commit_after>/* Copyright (c) 2010 Ariya Hidayat <[email protected]> Copyright (c) 2009 Einar Lielmanis Copyright (c) 2010 Nicolas Ferrero <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <v8.h> #include <string.h> #include <stdlib.h> #include "beautify.h" #define BUF_SIZE 1024 using namespace v8; Handle<String> readFile(const char* name) { FILE *file = stdin; int len = 0; char *buf; Handle<String> result; if (name) { file = fopen(name, "rb"); if (file == NULL) { return Handle<String>(); } fseek(file, 0, SEEK_END); len = ftell(file); rewind(file); buf = new char[len + 1]; buf[len] = '\0'; fread(buf, 1, len, file); fclose(file); result = String::New(buf); delete[] buf; } else { char c; buf = (char*)malloc(BUF_SIZE + 1); int buf_size = BUF_SIZE + 1; while ((c = getchar()) != EOF) { buf[len++] = c; if (len == buf_size) { buf_size <<= 1; buf = (char*)realloc(buf, buf_size); } } buf[len] = '\0'; result = String::New(buf); free(buf); } return result; } void writeFile(Handle<Value> result, const char* name) { if (result.IsEmpty() || result->IsUndefined()) return; FILE* file = stdout; if (name) { file = fopen(name, "wt"); if (file == NULL) return; } String::Utf8Value str(result); fprintf(file, "%s\n", *str); if (name) fclose(file); } static void usage(char* progname) { printf("Usage: %s [options] source-file\n", progname); printf("[options]\n"); printf(" --overwrite : Overwrite source-file (use with care!)\n"); printf(" --indent-size or -s: Indentation size. (default 4)\n"); printf(" --indent-char or -c: Character to indent with. (default space)\n"); printf(" --disable-preserve-newlines or -d: Do not preserve existing line breaks.\n"); printf(" --indent-level or -l: Initial indentation level, you probably won't need this ever. (default 0)\n"); printf(" --space-after-anon-function or -f: Space is added between \"function ()\", otherwise the common \"function()\" output is used.\n"); printf(" --braces-on-own-line or -b: ANSI / Allman brace style, each opening/closing brace gets its own line.\n"); printf(" --keep-array-indentation or -k: Keep array indentation.\n"); printf(" --help or -h: Prints this help statement.\n"); } int main(int argc, char* argv[]) { Handle<String> source; HandleScope handle_scope; Handle<ObjectTemplate> global = ObjectTemplate::New(); Handle<ObjectTemplate> options = ObjectTemplate::New(); bool overwrite = false; const char* output = 0; for (int argpos = 1; argpos < argc; ++argpos) { if (argv[argpos][0] != '-') { source = readFile(argv[argpos]); output = argv[argpos]; } else if (strcmp(argv[argpos], "--overwrite") == 0) { overwrite = true; } else if (strcmp(argv[argpos], "--indent-size") == 0 || strcmp(argv[argpos], "-s") == 0) { options->Set("indent_size", String::New(argv[argpos+1])); } else if (strcmp(argv[argpos], "--indent-char") == 0 || strcmp(argv[argpos], "-c") == 0) { options->Set("indent_char", String::New(argv[argpos+1])); } else if (strcmp(argv[argpos], "--disable-preserve-newlines") == 0 || strcmp(argv[argpos], "-d") == 0) { options->Set("preserve_newlines", Boolean::New(false)); } else if (strcmp(argv[argpos], "--indent-level") == 0 || strcmp(argv[argpos], "-l") == 0) { options->Set("indent_level", String::New(argv[argpos+1])); } else if (strcmp(argv[argpos], "--space-after-anon-function") == 0 || strcmp(argv[argpos], "-f") == 0) { options->Set("space_after_anon_function", Boolean::New(true)); } else if (strcmp(argv[argpos], "--braces-on-own-line") == 0 || strcmp(argv[argpos], "-b") == 0) { options->Set("braces_on_own_line", Boolean::New(true)); } else if (strcmp(argv[argpos], "--keep-array-indentation") == 0 || strcmp(argv[argpos], "-k") == 0) { options->Set("keep_array_indentation", Boolean::New(true)); } else if (strcmp(argv[argpos], "--help") == 0 || strcmp(argv[argpos], "-h") == 0) { usage(argv[0]); return -1; } } if (source.IsEmpty()) source = readFile(0); global->Set("source", source); global->Set("options", options); Handle<Context> context = Context::New(NULL, global); Context::Scope context_scope(context); Handle<Script> beautifyScript = Script::Compile(String::New(beautify_code)); beautifyScript->Run(); Handle<Script> runnerScript = Script::Compile(String::New("js_beautify(source, options);")); Handle<Value> result = runnerScript->Run(); writeFile(result, overwrite ? output : 0); return 0; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #include <gtest/gtest.h> #include "opencv/cxcore.h" #include "opencv/cvwimage.h" #include "opencv/cv.h" #include "opencv/highgui.h" #include "cv_bridge/CvBridge.h" #include "sensor_msgs/Image.h" TEST(OpencvTests, testCase_encode_decode) { int fmts[] = { IPL_DEPTH_8U, -1, IPL_DEPTH_8S, IPL_DEPTH_16U, IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F, IPL_DEPTH_64F, -1 }; for (int w = 100; w < 800; w += 100) { for (int h = 100; h < 800; h += 100) { for (int fi = 0; fmts[fi] != -1; fi++) { for (int channels = 1; channels <= 4; channels++) { IplImage *original = cvCreateImage(cvSize(w, h), fmts[fi], channels); #if 0 // XXX OpenCV bug, change this when opencv_latest next moves CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); #else cvSet(original, cvScalar(1,2,3,4)); #endif sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message); ASSERT_TRUE(success); IplImage *final = img_bridge_.toIpl(); // cvSaveImage("final.png", final); IplImage *diff = cvCloneImage(original); cvAbsDiff(original, final, diff); CvScalar sum = cvSum(diff); for (int c = 0; c < channels; c++) { EXPECT_TRUE(sum.val[c] == 0); } } } } } } TEST(OpencvTests, testCase_decode_8u) { IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message, "passthrough"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 1); success = img_bridge_.fromImage(image_message, "mono8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 1); success = img_bridge_.fromImage(image_message, "rgb8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); success = img_bridge_.fromImage(image_message, "bgr8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); } TEST(OpencvTests, testCase_decode_16u) { IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message, "mono16"); ASSERT_TRUE(success); printf("%d\n", cvGetElemType(img_bridge_.toIpl())); EXPECT_TRUE(cvGetElemType(img_bridge_.toIpl()) == CV_16UC1); } TEST(OpencvTests, testCase_decode_8uc3) { IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message, "passthrough"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); success = img_bridge_.fromImage(image_message, "mono8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 1); success = img_bridge_.fromImage(image_message, "rgb8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); success = img_bridge_.fromImage(image_message, "bgr8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); } TEST(OpencvTests, testCase_new_methods) { int channels = 3; IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, channels); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::CvBridge img_bridge_; sensor_msgs::Image::Ptr rosimg = img_bridge_.cvToImgMsg(original); IplImage *final = img_bridge_.imgMsgToCv(rosimg); IplImage *diff = cvCloneImage(original); cvAbsDiff(original, final, diff); CvScalar sum = cvSum(diff); for (int c = 0; c < channels; c++) { EXPECT_TRUE(sum.val[c] == 0); } } TEST(OpencvTests, testCase_16u_bgr) { int channels = 1; IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_16U, channels); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::CvBridge img_bridge_; sensor_msgs::Image::Ptr image_message = img_bridge_.cvToImgMsg(original, "mono16"); int success; success = img_bridge_.fromImage(*image_message, "mono16"); ASSERT_TRUE(success); EXPECT_TRUE(cvGetElemType(img_bridge_.toIpl()) == CV_16UC1); success = img_bridge_.fromImage(*image_message, "bgr8"); ASSERT_TRUE(success); EXPECT_TRUE(cvGetElemType(img_bridge_.toIpl()) == CV_8UC3); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Minor change to test.<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #include <gtest/gtest.h> #include "opencv/cxcore.h" #include "opencv/cvwimage.h" #include "opencv/cv.h" #include "opencv/highgui.h" #include "cv_bridge/CvBridge.h" #include "sensor_msgs/Image.h" TEST(OpencvTests, testCase_encode_decode) { int fmts[] = { IPL_DEPTH_8U, -1, IPL_DEPTH_8S, IPL_DEPTH_16U, IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F, IPL_DEPTH_64F, -1 }; for (int w = 100; w < 800; w += 100) { for (int h = 100; h < 800; h += 100) { for (int fi = 0; fmts[fi] != -1; fi++) { for (int channels = 1; channels <= 4; channels++) { IplImage *original = cvCreateImage(cvSize(w, h), fmts[fi], channels); #if 0 // XXX OpenCV bug, change this when opencv_latest next moves CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); #else cvSet(original, cvScalar(1,2,3,4)); #endif sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message); ASSERT_TRUE(success); IplImage *final = img_bridge_.toIpl(); // cvSaveImage("final.png", final); IplImage *diff = cvCloneImage(original); cvAbsDiff(original, final, diff); CvScalar sum = cvSum(diff); for (int c = 0; c < channels; c++) { EXPECT_TRUE(sum.val[c] == 0); } } } } } } TEST(OpencvTests, testCase_decode_8u) { IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 1); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message, "passthrough"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 1); success = img_bridge_.fromImage(image_message, "mono8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 1); success = img_bridge_.fromImage(image_message, "rgb8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); success = img_bridge_.fromImage(image_message, "bgr8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); } TEST(OpencvTests, testCase_decode_16u) { IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_16U, 1); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message, "mono16"); ASSERT_TRUE(success); printf("%d\n", cvGetElemType(img_bridge_.toIpl())); EXPECT_TRUE(cvGetElemType(img_bridge_.toIpl()) == CV_16UC1); } TEST(OpencvTests, testCase_decode_8uc3) { IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::Image image_message; sensor_msgs::CvBridge img_bridge_; int success; success = img_bridge_.fromIpltoRosImage(original, image_message); ASSERT_TRUE(success); success = img_bridge_.fromImage(image_message, "passthrough"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); success = img_bridge_.fromImage(image_message, "mono8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 1); success = img_bridge_.fromImage(image_message, "rgb8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); success = img_bridge_.fromImage(image_message, "bgr8"); ASSERT_TRUE(success); EXPECT_TRUE(CV_MAT_CN(cvGetElemType(img_bridge_.toIpl())) == 3); } TEST(OpencvTests, testCase_new_methods) { int channels = 3; IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, channels); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::CvBridge img_bridge_; sensor_msgs::Image::Ptr rosimg = img_bridge_.cvToImgMsg(original); IplImage *final = img_bridge_.imgMsgToCv(rosimg); IplImage *diff = cvCloneImage(original); cvAbsDiff(original, final, diff); CvScalar sum = cvSum(diff); for (int c = 0; c < channels; c++) { EXPECT_TRUE(sum.val[c] == 0); } } TEST(OpencvTests, testCase_16u_bgr) { int channels = 1; IplImage *original = cvCreateImage(cvSize(640, 480), IPL_DEPTH_16U, channels); CvRNG r = cvRNG(77); cvRandArr(&r, original, CV_RAND_UNI, cvScalar(0,0,0,0), cvScalar(255,255,255,255)); sensor_msgs::CvBridge img_bridge_; sensor_msgs::Image::Ptr image_message = img_bridge_.cvToImgMsg(original, "mono16"); int success; success = img_bridge_.fromImage(*image_message, "mono16"); ASSERT_TRUE(success); EXPECT_TRUE(cvGetElemType(img_bridge_.toIpl()) == CV_16UC1); success = img_bridge_.fromImage(*image_message, "bgr8"); ASSERT_TRUE(success); EXPECT_TRUE(cvGetElemType(img_bridge_.toIpl()) == CV_8UC3); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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 Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server_util.hpp" #include <glog/logging.h> #include <iostream> #include "../common/util.hpp" #include "../common/cmdline.h" #include "../common/exception.hpp" #include "../common/membership.hpp" #define SET_PROGNAME(s) \ static const std::string PROGNAME(JUBATUS_APPNAME "_" s); namespace jubatus { namespace framework { static const std::string VERSION(JUBATUS_VERSION); void print_version(const std::string& progname){ std::cout << "jubatus-" << VERSION << " (" << progname << ")" << std::endl; } server_argv::server_argv(int args, char** argv){ google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 2); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("zookeeper", 'z', "zookeeper location", false); p.add<std::string>("name", 'n', "learning machine instance name", false); p.add<std::string>("tmpdir", 'd', "directory to place plugins", false, "/tmp"); p.add("join", 'j', "join to the existing cluster"); p.add<int>("interval_sec", 's', "mix interval by seconds", false, 16); p.add<int>("interval_count", 'i', "mix interval by update count", false, 512); p.add("version", 'v', "version"); p.parse_check(args, argv); std::cout<< "program name = " << jubatus::util::get_program_name() << std::endl; if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); program_name = jubatus::util::get_program_name(); z = p.get<std::string>("zookeeper"); name = p.get<std::string>("name"); tmpdir = p.get<std::string>("tmpdir"); // eth = "localhost"; eth = jubatus::util::get_ip("eth0"); join = p.exist("join"); interval_sec = p.get<int>("interval_sec"); interval_count = p.get<int>("interval_count"); if(z != "" and name == ""){ throw argv_error("can't start multinode mode without name specified"); } LOG(INFO) << boot_message(jubatus::util::get_program_name()); }; server_argv::server_argv(): join(false), port(9199), timeout(10), threadnum(2), z(""), name(""), tmpdir("/tmp"), eth("localhost"), interval_sec(5), interval_count(1024) { }; std::string server_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; keeper_argv::keeper_argv(int args, char** argv){ google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 16); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("zookeeper", 'z', "zookeeper location", false, "localhost:2181"); p.add("version", 'v', "version"); p.parse_check(args, argv); if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); z = p.get<std::string>("zookeeper"); eth = jubatus::util::get_ip("eth0"); }; keeper_argv::keeper_argv(): port(9199), timeout(10), threadnum(16), z("localhost:2181"), eth("") { }; std::string keeper_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; #ifdef HAVE_ZOOKEEPER_H common::cshared_ptr<jubatus::common::lock_service> ls; void atexit(void){ if(ls) ls->force_close(); } void exit_on_term(int){ exit(0); } void exit_on_term2(int, siginfo_t*, void*){ exit(0); } void set_exit_on_term(){ struct sigaction sigact; sigact.sa_handler = exit_on_term; sigact.sa_sigaction = exit_on_term2; sigact.sa_flags = SA_RESTART; if(sigaction(SIGTERM, &sigact, NULL) != 0) throw std::runtime_error("can't set SIGTERM handler"); if(sigaction(SIGINT, &sigact, NULL) != 0) throw std::runtime_error("can't set SIGINT handler"); ::atexit(jubatus::framework::atexit); } #endif } } <commit_msg>Fixed remove debug msg<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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 Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server_util.hpp" #include <glog/logging.h> #include <iostream> #include "../common/util.hpp" #include "../common/cmdline.h" #include "../common/exception.hpp" #include "../common/membership.hpp" #define SET_PROGNAME(s) \ static const std::string PROGNAME(JUBATUS_APPNAME "_" s); namespace jubatus { namespace framework { static const std::string VERSION(JUBATUS_VERSION); void print_version(const std::string& progname){ std::cout << "jubatus-" << VERSION << " (" << progname << ")" << std::endl; } server_argv::server_argv(int args, char** argv){ google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 2); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("zookeeper", 'z', "zookeeper location", false); p.add<std::string>("name", 'n', "learning machine instance name", false); p.add<std::string>("tmpdir", 'd', "directory to place plugins", false, "/tmp"); p.add("join", 'j', "join to the existing cluster"); p.add<int>("interval_sec", 's', "mix interval by seconds", false, 16); p.add<int>("interval_count", 'i', "mix interval by update count", false, 512); p.add("version", 'v', "version"); p.parse_check(args, argv); if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); program_name = jubatus::util::get_program_name(); z = p.get<std::string>("zookeeper"); name = p.get<std::string>("name"); tmpdir = p.get<std::string>("tmpdir"); // eth = "localhost"; eth = jubatus::util::get_ip("eth0"); join = p.exist("join"); interval_sec = p.get<int>("interval_sec"); interval_count = p.get<int>("interval_count"); if(z != "" and name == ""){ throw argv_error("can't start multinode mode without name specified"); } LOG(INFO) << boot_message(jubatus::util::get_program_name()); }; server_argv::server_argv(): join(false), port(9199), timeout(10), threadnum(2), z(""), name(""), tmpdir("/tmp"), eth("localhost"), interval_sec(5), interval_count(1024) { }; std::string server_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; keeper_argv::keeper_argv(int args, char** argv){ google::InitGoogleLogging(argv[0]); google::LogToStderr(); // only when debug cmdline::parser p; p.add<int>("rpc-port", 'p', "port number", false, 9199); p.add<int>("thread", 'c', "concurrency = thread number", false, 16); p.add<int>("timeout", 't', "time out (sec)", false, 10); p.add<std::string>("zookeeper", 'z', "zookeeper location", false, "localhost:2181"); p.add("version", 'v', "version"); p.parse_check(args, argv); if( p.exist("version") ){ print_version(jubatus::util::get_program_name()); exit(0); } port = p.get<int>("rpc-port"); threadnum = p.get<int>("thread"); timeout = p.get<int>("timeout"); z = p.get<std::string>("zookeeper"); eth = jubatus::util::get_ip("eth0"); }; keeper_argv::keeper_argv(): port(9199), timeout(10), threadnum(16), z("localhost:2181"), eth("") { }; std::string keeper_argv::boot_message(const std::string& progname) const { std::stringstream ret; ret << "starting " << progname << VERSION << " RPC server at " << eth << ":" << port << " with timeout: " << timeout; return ret.str(); }; #ifdef HAVE_ZOOKEEPER_H common::cshared_ptr<jubatus::common::lock_service> ls; void atexit(void){ if(ls) ls->force_close(); } void exit_on_term(int){ exit(0); } void exit_on_term2(int, siginfo_t*, void*){ exit(0); } void set_exit_on_term(){ struct sigaction sigact; sigact.sa_handler = exit_on_term; sigact.sa_sigaction = exit_on_term2; sigact.sa_flags = SA_RESTART; if(sigaction(SIGTERM, &sigact, NULL) != 0) throw std::runtime_error("can't set SIGTERM handler"); if(sigaction(SIGINT, &sigact, NULL) != 0) throw std::runtime_error("can't set SIGINT handler"); ::atexit(jubatus::framework::atexit); } #endif } } <|endoftext|>
<commit_before>/* * Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (cURLpp), 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. */ #ifndef CURLPP_HPP #define CURLPP_HPP #define LIBCURLPP_VERSION "0.6.0-pre5" #define LIBCURLPP_VERSION_NUM 0x000600 #include <string> #include <curl/curl.h> #include "dllfct.h" namespace cURLpp { /** * This function takes care of initializing cURLpp ( also libcURL). If you want * to cleanup cURL before your application quits just call cURLpp::terminate(). * This function should only be called once (no matter how many threads or * libcurl sessions that'll be used) by every application that uses libcurl, * it will throw a logic_error if you call it twice. * * The flags option is a bit pattern that tells libcurl exact what features * to init, as described below. Set the desired bits by ORing the values together. * * CURL_GLOBAL_ALL * Initialize everything possible. This sets all known bits. * * CURL_GLOBAL_SSL * Initialize SSL * * CURL_GLOBAL_WIN32 * Initialize the Win32 socket libraries. * * CURL_GLOBAL_NOTHING * Initialise nothing extra. This sets no bit. * * NOTE: you cannot call this function twice without first terminating it first. * it will throw a logic_error if you do this. */ void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL); /** * This function takes care of cleaning up cURLpp ( also libcURL). See * cURLpp::initialize( long flags ) for momre documentation. * * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a * logic_error if you do this. */ void CURLPPAPI terminate(); /** * This class takes care of initialization and cleaning up cURLpp ( also libcURL ) * (it will call cURLpp:terminate() in his destructor). If you want to be sure that * cURLpp is cleanup after you reached the end of scope of a specific function using * cURLpp, instatiate this class. This function call cURLpp::initialize() in his * constructor, so you don't have to call it by yourself, when you have decided to * use it. * * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation. */ class CURLPPAPI Cleanup { public: Cleanup(); ~Cleanup(); }; /** * This function will convert the given input string to an URL encoded * string and return that as a new allocated string. All input characters * that are not a-z, A-Z or 0-9 will be converted to their "URL escaped" * version (%NN where NN is a two-digit hexadecimal number). */ std::string CURLPPAPI escape( const std::string& url ); /** * This function will convert the given URL encoded input string to a * "plain string" and return that as a new allocated string. All input * characters that are URL encoded (%XX) where XX is a two-digit * hexadecimal number, or +) will be converted to their plain text versions * (up to a ? letter, no + letters to the right of a ? letter will be * converted). */ std::string CURLPPAPI unescape( const std::string &url ); /** * this is a portable wrapper for the getenv() function, meant to emulate * its behaviour and provide an identical interface for all operating * systems libcurl builds on (including win32). Under unix operating * systems, there isn't any point in returning an allocated memory, * although other systems won't work properly if this isn't done. The unix * implementation thus have to suffer slightly from the drawbacks of other * systems. */ std::string CURLPPAPI getenv( const std::string &name ); /** * Returns a human readable string with the version number of libcurl and * some of its important components (like OpenSSL version). * * Note: this returns the actual running lib's version, you might have * installed a newer lib's include files in your system which may turn * your LIBCURL_VERSION #define value to differ from this result. */ std::string CURLPPAPI libcurlVersion(); /** * This function returns the number of seconds since January 1st 1970, * for the date and time that the datestring parameter specifies. The now * parameter is there and should hold the current time to allow the * datestring to specify relative dates/times. Read further in the date * string parser section below. * * PARSING DATES AND TIMES * A "date" is a string, possibly empty, containing many items separated * by whitespace. The whitespace may be omitted when no ambiguity * arises. The empty string means the beginning of today (i.e., midnight). * Order of the items is immaterial. A date string may contain many * flavors of items: * * calendar date items * This can be specified in a number of different ways. Including * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72, * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72. The year can also be * omitted, for example: 9/17 or "sep 17". * * time of the day items * This string specifies the time on a given day. Syntax supported * includes: 18:19:0, 18:19, 6:19pm, 18:19-0500 (for specifying the time * zone as well). * * time zone items * Specifies international time zone. There are a few acronyms * supported, but in general you should instead use the specific * realtive time compared to UTC. Supported formats include: -1200, MST, * +0100. * * day of the week items * Specifies a day of the week. If this is mentioned alone it means that * day of the week in the future. Days of the week may be spelled out in * full: `Sunday', `Monday', etc or they may be abbreviated to their * first three letters, optionally followed by a period. The special * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur' * or `Thurs' for `Thursday' are also allowed. A number may precede a day * of the week item to move forward supplementary weeks. It is best * used in expression like `third monday'. In this context, `last DAY' * or `next DAY' is also acceptable; they move one week before or after * the day that DAY by itself would represent. * * relative items * A relative item adjusts a date (or the current date if none) forward * or backward. Example syntax includes: "1 year", "1 year ago", * "2 days", "4 weeks". The string `tomorrow' is worth one day in the * future (equivalent to `day'), the string `yesterday' is worth one * day in the past (equivalent to `day ago'). * * pure numbers * If the decimal number is of the form YYYYMMDD and no other calendar date * item appears before it in the date string, then YYYY is read as * the year, MM as the month number and DD as the day of the month, for the * specified calendar date. */ time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 ); } #endif <commit_msg>[curlpp-svn @ 21] forgot to commit the new version changes<commit_after>/* * Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files * (cURLpp), 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. */ #ifndef CURLPP_HPP #define CURLPP_HPP #define LIBCURLPP_VERSION "0.6.0" #define LIBCURLPP_VERSION_NUM 0x000600 #include <string> #include <curl/curl.h> #include "dllfct.h" namespace cURLpp { /** * This function takes care of initializing cURLpp ( also libcURL). If you want * to cleanup cURL before your application quits just call cURLpp::terminate(). * This function should only be called once (no matter how many threads or * libcurl sessions that'll be used) by every application that uses libcurl, * it will throw a logic_error if you call it twice. * * The flags option is a bit pattern that tells libcurl exact what features * to init, as described below. Set the desired bits by ORing the values together. * * CURL_GLOBAL_ALL * Initialize everything possible. This sets all known bits. * * CURL_GLOBAL_SSL * Initialize SSL * * CURL_GLOBAL_WIN32 * Initialize the Win32 socket libraries. * * CURL_GLOBAL_NOTHING * Initialise nothing extra. This sets no bit. * * NOTE: you cannot call this function twice without first terminating it first. * it will throw a logic_error if you do this. */ void CURLPPAPI initialize(long flags = CURL_GLOBAL_ALL); /** * This function takes care of cleaning up cURLpp ( also libcURL). See * cURLpp::initialize( long flags ) for momre documentation. * * NOTE: you cannot call this function if cURLpp is not loaded. it will throw a * logic_error if you do this. */ void CURLPPAPI terminate(); /** * This class takes care of initialization and cleaning up cURLpp ( also libcURL ) * (it will call cURLpp:terminate() in his destructor). If you want to be sure that * cURLpp is cleanup after you reached the end of scope of a specific function using * cURLpp, instatiate this class. This function call cURLpp::initialize() in his * constructor, so you don't have to call it by yourself, when you have decided to * use it. * * See cURLpp::initialize( long flags ) and cURLpp:terminate() for more documentation. */ class CURLPPAPI Cleanup { public: Cleanup(); ~Cleanup(); }; /** * This function will convert the given input string to an URL encoded * string and return that as a new allocated string. All input characters * that are not a-z, A-Z or 0-9 will be converted to their "URL escaped" * version (%NN where NN is a two-digit hexadecimal number). */ std::string CURLPPAPI escape( const std::string& url ); /** * This function will convert the given URL encoded input string to a * "plain string" and return that as a new allocated string. All input * characters that are URL encoded (%XX) where XX is a two-digit * hexadecimal number, or +) will be converted to their plain text versions * (up to a ? letter, no + letters to the right of a ? letter will be * converted). */ std::string CURLPPAPI unescape( const std::string &url ); /** * this is a portable wrapper for the getenv() function, meant to emulate * its behaviour and provide an identical interface for all operating * systems libcurl builds on (including win32). Under unix operating * systems, there isn't any point in returning an allocated memory, * although other systems won't work properly if this isn't done. The unix * implementation thus have to suffer slightly from the drawbacks of other * systems. */ std::string CURLPPAPI getenv( const std::string &name ); /** * Returns a human readable string with the version number of libcurl and * some of its important components (like OpenSSL version). * * Note: this returns the actual running lib's version, you might have * installed a newer lib's include files in your system which may turn * your LIBCURL_VERSION #define value to differ from this result. */ std::string CURLPPAPI libcurlVersion(); /** * This function returns the number of seconds since January 1st 1970, * for the date and time that the datestring parameter specifies. The now * parameter is there and should hold the current time to allow the * datestring to specify relative dates/times. Read further in the date * string parser section below. * * PARSING DATES AND TIMES * A "date" is a string, possibly empty, containing many items separated * by whitespace. The whitespace may be omitted when no ambiguity * arises. The empty string means the beginning of today (i.e., midnight). * Order of the items is immaterial. A date string may contain many * flavors of items: * * calendar date items * This can be specified in a number of different ways. Including * 1970-09-17, 70-9-17, 70-09-17, 9/17/72, 24 September 1972, 24 Sept 72, * 24 Sep 72, Sep 24, 1972, 24-sep-72, 24sep72. The year can also be * omitted, for example: 9/17 or "sep 17". * * time of the day items * This string specifies the time on a given day. Syntax supported * includes: 18:19:0, 18:19, 6:19pm, 18:19-0500 (for specifying the time * zone as well). * * time zone items * Specifies international time zone. There are a few acronyms * supported, but in general you should instead use the specific * realtive time compared to UTC. Supported formats include: -1200, MST, * +0100. * * day of the week items * Specifies a day of the week. If this is mentioned alone it means that * day of the week in the future. Days of the week may be spelled out in * full: `Sunday', `Monday', etc or they may be abbreviated to their * first three letters, optionally followed by a period. The special * abbreviations `Tues' for `Tuesday', `Wednes' for `Wednesday' and `Thur' * or `Thurs' for `Thursday' are also allowed. A number may precede a day * of the week item to move forward supplementary weeks. It is best * used in expression like `third monday'. In this context, `last DAY' * or `next DAY' is also acceptable; they move one week before or after * the day that DAY by itself would represent. * * relative items * A relative item adjusts a date (or the current date if none) forward * or backward. Example syntax includes: "1 year", "1 year ago", * "2 days", "4 weeks". The string `tomorrow' is worth one day in the * future (equivalent to `day'), the string `yesterday' is worth one * day in the past (equivalent to `day ago'). * * pure numbers * If the decimal number is of the form YYYYMMDD and no other calendar date * item appears before it in the date string, then YYYY is read as * the year, MM as the month number and DD as the day of the month, for the * specified calendar date. */ time_t CURLPPAPI getdate( const std::string&date, time_t *now = 0 ); } #endif <|endoftext|>
<commit_before>/* * Clever programming language * Copyright (c) 2011 Clever Team * * 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. * * $Id: std.cc 299 2011-01-16 23:06:11Z felipensp $ */ #include <cmath> #include "module.h" #include "std/math.h" namespace clever { namespace std_pkg { Module* g_math_module = new Math; /** * sqrt(double x) * Returns the square root of a number x */ static CLEVER_FUNCTION(sqrt) { retval->setDouble(std::sqrt(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * cos(double x) * Returns the cosine of an angle of x radians */ static CLEVER_FUNCTION(cos) { retval->setDouble(std::cos(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * sin(double x) * Returns the sine of an angle of x radians */ static CLEVER_FUNCTION(sin) { retval->setDouble(std::sin(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * tan(double x) * Returns the tangent of an angle of x radians */ static CLEVER_FUNCTION(tan) { retval->setDouble(std::tan(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * atan(double x) * Returns the arc tangent of an angle of x radians */ static CLEVER_FUNCTION(atan) { retval->setDouble(std::atan(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * pow(double x, double y) * Returns x raised to the power y */ static CLEVER_FUNCTION(pow) { retval->setDouble(std::pow(args->at(0)->getDouble(), args->at(1)->getDouble())); retval->set_type(Value::DOUBLE); } /** * ceil(double x) * Returns the smallest integral value that is not less than x */ static CLEVER_FUNCTION(ceil) { retval->setDouble(std::ceil(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * abs(double x) * abs(int x) * Returns the absolute value of a number x */ static CLEVER_FUNCTION(abs) { if (args->at(0)->get_type() == Value::DOUBLE) { retval->setDouble(std::abs(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } else { retval->setInteger(std::labs(args->at(0)->getInteger())); retval->set_type(Value::INTEGER); } } /** * Load module data */ void Math::Init() throw() { addFunction("sqrt", &CLEVER_FUNC_NAME(sqrt)); addFunction("sin", &CLEVER_FUNC_NAME(sin)); addFunction("cos", &CLEVER_FUNC_NAME(cos)); addFunction("tan", &CLEVER_FUNC_NAME(tan)); addFunction("atan", &CLEVER_FUNC_NAME(atan)); addFunction("pow", &CLEVER_FUNC_NAME(pow)); addFunction("ceil", &CLEVER_FUNC_NAME(ceil)); addFunction("abs", &CLEVER_FUNC_NAME(abs)); } }} // clever::std_package<commit_msg>Still fixing abs() function for integer numbers - part 2<commit_after>/* * Clever programming language * Copyright (c) 2011 Clever Team * * 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. * * $Id: std.cc 299 2011-01-16 23:06:11Z felipensp $ */ #include <cmath> #include <cstdlib> #include "module.h" #include "std/math.h" namespace clever { namespace std_pkg { Module* g_math_module = new Math; /** * sqrt(double x) * Returns the square root of a number x */ static CLEVER_FUNCTION(sqrt) { retval->setDouble(std::sqrt(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * cos(double x) * Returns the cosine of an angle of x radians */ static CLEVER_FUNCTION(cos) { retval->setDouble(std::cos(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * sin(double x) * Returns the sine of an angle of x radians */ static CLEVER_FUNCTION(sin) { retval->setDouble(std::sin(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * tan(double x) * Returns the tangent of an angle of x radians */ static CLEVER_FUNCTION(tan) { retval->setDouble(std::tan(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * atan(double x) * Returns the arc tangent of an angle of x radians */ static CLEVER_FUNCTION(atan) { retval->setDouble(std::atan(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * pow(double x, double y) * Returns x raised to the power y */ static CLEVER_FUNCTION(pow) { retval->setDouble(std::pow(args->at(0)->getDouble(), args->at(1)->getDouble())); retval->set_type(Value::DOUBLE); } /** * ceil(double x) * Returns the smallest integral value that is not less than x */ static CLEVER_FUNCTION(ceil) { retval->setDouble(std::ceil(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } /** * abs(double x) * abs(int x) * Returns the absolute value of a number x */ static CLEVER_FUNCTION(abs) { if (args->at(0)->get_type() == Value::DOUBLE) { retval->setDouble(std::abs(args->at(0)->getDouble())); retval->set_type(Value::DOUBLE); } else { retval->setInteger(std::labs(args->at(0)->getInteger())); retval->set_type(Value::INTEGER); } } /** * Load module data */ void Math::Init() throw() { addFunction("sqrt", &CLEVER_FUNC_NAME(sqrt)); addFunction("sin", &CLEVER_FUNC_NAME(sin)); addFunction("cos", &CLEVER_FUNC_NAME(cos)); addFunction("tan", &CLEVER_FUNC_NAME(tan)); addFunction("atan", &CLEVER_FUNC_NAME(atan)); addFunction("pow", &CLEVER_FUNC_NAME(pow)); addFunction("ceil", &CLEVER_FUNC_NAME(ceil)); addFunction("abs", &CLEVER_FUNC_NAME(abs)); } }} // clever::std_package<|endoftext|>
<commit_before>#include <fstream> #include <sstream> #include <vector> #include <iostream> #include <utility> #include <optional> #include "core/argparse.h" #include "core/io.h" #include "core/image.h" #include "core/image_draw.h" #include "core/pack.h" using namespace euphoria::core; struct ImageAndFile { ImageAndFile() {} ImageAndFile(const std::string& f, const Image& i) : file(f) , image(i) {} std::string file; Image image; }; std::vector<Sizei> CollectSizes ( const std::vector<ImageAndFile>& images, int padding ) { auto sizes = std::vector<Sizei>{}; for(const auto& img: images) { sizes.emplace_back(Sizei::FromWidthHeight ( img.image.GetWidth() + padding, img.image.GetHeight() + padding )); } return sizes; } std::vector<ImageAndFile> LoadImages(const std::vector<std::string>& files) { auto images = std::vector<ImageAndFile>{}; for(const auto& f: files) { auto chunk = io::FileToChunk(f); if(chunk == nullptr) { std::cerr << "failed to read " << f << "\n"; return {}; } auto loaded_image = LoadImage(chunk, f, AlphaLoad::Keep); if(loaded_image.error.empty() == false) { std::cerr << "failed to read image " << loaded_image.error << "\n"; return {}; } images.emplace_back(f, loaded_image.image); } return images; } struct PackedImage { PackedImage() : position{0,0} {} PackedImage(const std::string& f, const Image& i, const vec2i& p) : file(f) , image(i) , position(p) {} std::string file; Image image; vec2i position; }; std::vector<PackedImage> PackImage ( const Sizei& image_size, const std::vector<ImageAndFile>& images, int padding ) { const auto image_sizes = CollectSizes(images, padding); const auto packed = Pack(image_size, image_sizes); auto ret = std::vector<PackedImage>{}; int i = 0; for(const auto& rect: packed) { const auto& src = images[i]; i += 1; if(rect.has_value() == false) { std::cerr << "failed to pack " << src.file << "\n"; } else { ret.emplace_back(src.file, src.image, rect->BottomLeft()); } } return ret; } Sizei PackTight ( const Sizei& default_size, std::vector<PackedImage>* images, int padding ) { std::optional<Recti> bb = std::nullopt; for(const auto& img: *images) { const auto image_width = img.image.GetWidth(); const auto image_height = img.image.GetHeight(); const auto& rect = Recti::FromBottomLeftWidthHeight ( vec2i(img.position.x, img.position.y), image_width + padding, image_height + padding ); if(bb.has_value()) { bb->Include(rect); } else { bb = rect; } } if(!bb) { return default_size; } const auto size = bb->GetSize(); const auto dx = -bb->left; const auto dy = -bb->bottom; for(auto& img: *images) { img.position += vec2i(dx, dy); } return Sizei::FromWidthHeight(size.width + padding, size.height+padding); } Image DrawImage ( const std::vector<PackedImage>& images, const Sizei& size, const Rgbi& background_color ) { auto composed_image = Image{}; composed_image.SetupWithAlphaSupport ( size.width, size.height ); Clear(&composed_image, background_color); for(const auto& image: images) { PasteImage ( &composed_image, image.position, image.image, PixelsOutside::Discard ); } return composed_image; } std::pair<std::vector<PackedImage>, Sizei> GridLayout ( const std::vector<ImageAndFile>& images, int padding, bool top_to_bottom ) { const auto images_per_row = Ceil(Sqrt(images.size())); auto ret = std::vector<PackedImage>{}; int x = padding; int y = padding; int current_height = 0; int column = 0; int max_x = 0; auto new_row = [&] { max_x = Max(max_x, x); column = 0; x = padding; y += current_height + padding; current_height = 0; }; for(const auto& src: images) { const auto width = src.image.GetWidth(); const auto height = src.image.GetHeight(); ret.emplace_back ( src.file, src.image, vec2i(x, y) ); x += width + padding; current_height = Max(current_height, height); column += 1; if(column >= images_per_row) { new_row(); } } if(column != 0) { new_row(); } const auto image_width = max_x; const auto image_height = y; // we lay out left->right, bottom->top since that is easer // but top->bottom is ieasier to read, so we provide a option // to switch to that, and we do that by inverting it at the end if(top_to_bottom) { for(auto& r: ret) { r.position.y = image_height - (r.position.y + r.image.GetHeight()); } } return {ret, Sizei::FromWidthHeight(image_width, image_height)}; } bool HandleGrid ( const std::string& output_file, int padding, Rgbi background_color, const std::vector<std::string>& files, bool top_to_bottom ) { // load images const auto images = LoadImages(files); if(images.empty()) { return false; } // layout images in grid and calculate image size from grid const auto [image_grid, size] = GridLayout(images, padding, top_to_bottom); // draw new image auto composed_image = DrawImage(image_grid, size, background_color); // save image to out auto saved_chunk = composed_image.Write(ImageWriteFormat::PNG); io::ChunkToFile(saved_chunk, output_file); return true; } bool HandlePack ( const std::string& output_file, const Sizei& requested_size, int padding, Rgbi background_color, bool pack_image, const std::vector<std::string>& files ) { if( requested_size.width < padding || requested_size.height < padding) { std::cerr << "padding too large\n"; return false; } const auto image_size = Sizei::FromWidthHeight ( requested_size.width - padding, requested_size.height - padding ); // load images const auto images = LoadImages(files); if(images.empty()) { return false; } // pack images auto packed = PackImage(image_size, images, padding); if(packed.empty()) { return false; } // optionally reduce image size const auto size = pack_image ? PackTight(requested_size, &packed, padding) : requested_size ; // border-theory: // reuqested_size is decreased with padding // the tighlty packed size is increased with padding // the packed image-sizes is increased with padding // and finally all the images are offseted by padding // all to keep padding-sized border between the images for(auto& img: packed) { img.position += vec2i(padding, padding); } // draw new image auto composed_image = DrawImage(packed, size, background_color); // save image to out auto saved_chunk = composed_image.Write(ImageWriteFormat::PNG); io::ChunkToFile(saved_chunk, output_file); return true; } int main(int argc, char* argv[]) { auto parser = argparse::Parser { "pack smaller images into a bigger one" }; auto subs = parser.AddSubParsers(); subs->Add ( "grid", "lay put images in a grid", [](argparse::SubParser* sub) { Rgbi background_color = Color::Gray; std::string output_file = "collage.png"; int padding = 5; bool top_to_bottom = true; std::vector<std::string> files; sub->Add("--bg", &background_color) .AllowBeforePositionals() .Nargs("C") .Help("change the background color") ; sub->Add("--padding", &padding) .AllowBeforePositionals() .Nargs("P") .Help("change the space (in pixels) between images") ; sub->Add("-o, --output", &output_file) .AllowBeforePositionals() .Nargs("FILE") .Help("change where to save the output") ; sub->AddVector("files", &files) .Nargs("F") .Help("the files to pack") ; sub->SetFalse("--invert", &top_to_bottom) .AllowBeforePositionals() .Help("switch from top-to-bottom to bottom-to-top layout") ; return sub->OnComplete([&] { const auto was_packed = HandleGrid ( output_file, padding, background_color, files, top_to_bottom ); return was_packed ? argparse::ParseResult::Ok : argparse::ParseResult::Error ; }); } ); subs->Add ( "pack", "pack images according to the stb rect-pack algorithm", [](argparse::SubParser* sub) { auto image_size = Sizei::FromWidthHeight(1024, 1024); Rgbi background_color = Color::Gray; std::string output_file = "collage.png"; int padding = 5; bool pack_image = true; std::vector<std::string> files; sub->Add("--size", &image_size) .AllowBeforePositionals() .Nargs("S") .Help("change the image size") ; sub->Add("--bg", &background_color) .AllowBeforePositionals() .Nargs("C") .Help("change the background color") ; sub->Add("--padding", &padding) .AllowBeforePositionals() .Nargs("P") .Help("change the space (in pixels) between images") ; sub->Add("-o, --output", &output_file) .AllowBeforePositionals() .Nargs("FILE") .Help("change where to save the output") ; sub->SetFalse("--no-pack", &pack_image) .AllowBeforePositionals() .Help("don't pack the resulting image and keep the whitespace") ; sub->AddVector("files", &files) .Nargs("F") .Help("the files to pack") ; return sub->OnComplete([&] { const auto was_packed = HandlePack ( output_file, image_size, padding, background_color, pack_image, files ); return was_packed ? argparse::ParseResult::Ok : argparse::ParseResult::Error ; }); } ); return ParseFromMain(&parser, argc, argv); } <commit_msg>option to sort images before laying out in grid<commit_after>#include <fstream> #include <sstream> #include <vector> #include <iostream> #include <utility> #include <optional> #include "core/argparse.h" #include "core/io.h" #include "core/image.h" #include "core/image_draw.h" #include "core/pack.h" #include "core/stringutils.h" using namespace euphoria::core; struct ImageAndFile { ImageAndFile() {} ImageAndFile(const std::string& f, const Image& i) : file(f) , image(i) {} std::string file; Image image; }; std::vector<Sizei> CollectSizes ( const std::vector<ImageAndFile>& images, int padding ) { auto sizes = std::vector<Sizei>{}; for(const auto& img: images) { sizes.emplace_back(Sizei::FromWidthHeight ( img.image.GetWidth() + padding, img.image.GetHeight() + padding )); } return sizes; } std::vector<ImageAndFile> LoadImages(const std::vector<std::string>& files) { auto images = std::vector<ImageAndFile>{}; for(const auto& f: files) { auto chunk = io::FileToChunk(f); if(chunk == nullptr) { std::cerr << "failed to read " << f << "\n"; return {}; } auto loaded_image = LoadImage(chunk, f, AlphaLoad::Keep); if(loaded_image.error.empty() == false) { std::cerr << "failed to read image " << loaded_image.error << "\n"; return {}; } images.emplace_back(f, loaded_image.image); } return images; } struct PackedImage { PackedImage() : position{0,0} {} PackedImage(const std::string& f, const Image& i, const vec2i& p) : file(f) , image(i) , position(p) {} std::string file; Image image; vec2i position; }; std::vector<PackedImage> PackImage ( const Sizei& image_size, const std::vector<ImageAndFile>& images, int padding ) { const auto image_sizes = CollectSizes(images, padding); const auto packed = Pack(image_size, image_sizes); auto ret = std::vector<PackedImage>{}; int i = 0; for(const auto& rect: packed) { const auto& src = images[i]; i += 1; if(rect.has_value() == false) { std::cerr << "failed to pack " << src.file << "\n"; } else { ret.emplace_back(src.file, src.image, rect->BottomLeft()); } } return ret; } Sizei PackTight ( const Sizei& default_size, std::vector<PackedImage>* images, int padding ) { std::optional<Recti> bb = std::nullopt; for(const auto& img: *images) { const auto image_width = img.image.GetWidth(); const auto image_height = img.image.GetHeight(); const auto& rect = Recti::FromBottomLeftWidthHeight ( vec2i(img.position.x, img.position.y), image_width + padding, image_height + padding ); if(bb.has_value()) { bb->Include(rect); } else { bb = rect; } } if(!bb) { return default_size; } const auto size = bb->GetSize(); const auto dx = -bb->left; const auto dy = -bb->bottom; for(auto& img: *images) { img.position += vec2i(dx, dy); } return Sizei::FromWidthHeight(size.width + padding, size.height+padding); } Image DrawImage ( const std::vector<PackedImage>& images, const Sizei& size, const Rgbi& background_color ) { auto composed_image = Image{}; composed_image.SetupWithAlphaSupport ( size.width, size.height ); Clear(&composed_image, background_color); for(const auto& image: images) { PasteImage ( &composed_image, image.position, image.image, PixelsOutside::Discard ); } return composed_image; } std::pair<std::vector<PackedImage>, Sizei> GridLayout ( const std::vector<ImageAndFile>& images, int padding, bool top_to_bottom ) { const auto images_per_row = Ceil(Sqrt(images.size())); auto ret = std::vector<PackedImage>{}; int x = padding; int y = padding; int current_height = 0; int column = 0; int max_x = 0; auto new_row = [&] { max_x = Max(max_x, x); column = 0; x = padding; y += current_height + padding; current_height = 0; }; for(const auto& src: images) { const auto width = src.image.GetWidth(); const auto height = src.image.GetHeight(); ret.emplace_back ( src.file, src.image, vec2i(x, y) ); x += width + padding; current_height = Max(current_height, height); column += 1; if(column >= images_per_row) { new_row(); } } if(column != 0) { new_row(); } const auto image_width = max_x; const auto image_height = y; // we lay out left->right, bottom->top since that is easer // but top->bottom is ieasier to read, so we provide a option // to switch to that, and we do that by inverting it at the end if(top_to_bottom) { for(auto& r: ret) { r.position.y = image_height - (r.position.y + r.image.GetHeight()); } } return {ret, Sizei::FromWidthHeight(image_width, image_height)}; } bool HandleGrid ( const std::string& output_file, int padding, Rgbi background_color, const std::vector<std::string>& src_files, bool top_to_bottom, bool sort_files ) { auto files = src_files; if(sort_files) { std::sort ( files.begin(), files.end(), [](const std::string& lhs, const std::string& rhs) { return StringCompare(lhs, rhs) < 0; } ); } // load images const auto images = LoadImages(files); if(images.empty()) { return false; } // layout images in grid and calculate image size from grid const auto [image_grid, size] = GridLayout(images, padding, top_to_bottom); // draw new image auto composed_image = DrawImage(image_grid, size, background_color); // save image to out auto saved_chunk = composed_image.Write(ImageWriteFormat::PNG); io::ChunkToFile(saved_chunk, output_file); return true; } bool HandlePack ( const std::string& output_file, const Sizei& requested_size, int padding, Rgbi background_color, bool pack_image, const std::vector<std::string>& files ) { if( requested_size.width < padding || requested_size.height < padding) { std::cerr << "padding too large\n"; return false; } const auto image_size = Sizei::FromWidthHeight ( requested_size.width - padding, requested_size.height - padding ); // load images const auto images = LoadImages(files); if(images.empty()) { return false; } // pack images auto packed = PackImage(image_size, images, padding); if(packed.empty()) { return false; } // optionally reduce image size const auto size = pack_image ? PackTight(requested_size, &packed, padding) : requested_size ; // border-theory: // reuqested_size is decreased with padding // the tighlty packed size is increased with padding // the packed image-sizes is increased with padding // and finally all the images are offseted by padding // all to keep padding-sized border between the images for(auto& img: packed) { img.position += vec2i(padding, padding); } // draw new image auto composed_image = DrawImage(packed, size, background_color); // save image to out auto saved_chunk = composed_image.Write(ImageWriteFormat::PNG); io::ChunkToFile(saved_chunk, output_file); return true; } int main(int argc, char* argv[]) { auto parser = argparse::Parser { "pack smaller images into a bigger one" }; auto subs = parser.AddSubParsers(); subs->Add ( "grid", "lay put images in a grid", [](argparse::SubParser* sub) { Rgbi background_color = Color::Gray; std::string output_file = "collage.png"; int padding = 5; bool top_to_bottom = true; std::vector<std::string> files; bool sort_files = false; sub->Add("--bg", &background_color) .AllowBeforePositionals() .Nargs("C") .Help("change the background color") ; sub->Add("--padding", &padding) .AllowBeforePositionals() .Nargs("P") .Help("change the space (in pixels) between images") ; sub->Add("-o, --output", &output_file) .AllowBeforePositionals() .Nargs("FILE") .Help("change where to save the output") ; sub->AddVector("files", &files) .Nargs("F") .Help("the files to pack") ; sub->SetFalse("--invert", &top_to_bottom) .AllowBeforePositionals() .Help("switch from top-to-bottom to bottom-to-top layout") ; sub->SetTrue("--sort", &sort_files) .AllowBeforePositionals() .Help("sort image files before laying them out in the grid") ; return sub->OnComplete([&] { const auto was_packed = HandleGrid ( output_file, padding, background_color, files, top_to_bottom, sort_files ); return was_packed ? argparse::ParseResult::Ok : argparse::ParseResult::Error ; }); } ); subs->Add ( "pack", "pack images according to the stb rect-pack algorithm", [](argparse::SubParser* sub) { auto image_size = Sizei::FromWidthHeight(1024, 1024); Rgbi background_color = Color::Gray; std::string output_file = "collage.png"; int padding = 5; bool pack_image = true; std::vector<std::string> files; sub->Add("--size", &image_size) .AllowBeforePositionals() .Nargs("S") .Help("change the image size") ; sub->Add("--bg", &background_color) .AllowBeforePositionals() .Nargs("C") .Help("change the background color") ; sub->Add("--padding", &padding) .AllowBeforePositionals() .Nargs("P") .Help("change the space (in pixels) between images") ; sub->Add("-o, --output", &output_file) .AllowBeforePositionals() .Nargs("FILE") .Help("change where to save the output") ; sub->SetFalse("--no-pack", &pack_image) .AllowBeforePositionals() .Help("don't pack the resulting image and keep the whitespace") ; sub->AddVector("files", &files) .Nargs("F") .Help("the files to pack") ; return sub->OnComplete([&] { const auto was_packed = HandlePack ( output_file, image_size, padding, background_color, pack_image, files ); return was_packed ? argparse::ParseResult::Ok : argparse::ParseResult::Error ; }); } ); return ParseFromMain(&parser, argc, argv); } <|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_XMLOFF_INC_MULTIPROPERTYSETHELPER_HXX #define INCLUDED_XMLOFF_INC_MULTIPROPERTYSETHELPER_HXX #include <rtl/ustring.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <tools/debug.hxx> namespace com { namespace sun { namespace star { namespace beans { class XMultiPropertySet; } namespace beans { class XPropertySet; } namespace beans { class XPropertySetInfo; } } } } /** * The MultiPropertySetHelper performs the following functions: * * Given a list of property names (as sal_Char** or OUString*), it can * query an XMultiPropertySet (or XPropertySet) which of these properties * it supports (method hasProperties(...)). The properties *MUST* be * sorted alphabetically. * * Then, the X(Multi)PropertySet can be queried for values, and only * the supported properties are queried. (method getValues(...)) The * values are stored in the helper itself. * * Finally, each property can be queried for existence * (method hasProperty(...)) or its value (method (getValue(...))). * * After some initial preparation (hasProperties, getValues) the * MultiPropertySetHelper can be used similarly to an * XPropertySet in that you can query the values in the places where you * need them. However, if an XMultiPropertySet is supplied, the queries * are more efficient, often significantly so. */ class MultiPropertySetHelper { /// names of all properties OUString* pPropertyNames; /// length of pPropertyNames array sal_Int16 nLength; /// the sequence of property names that the current (multi) /// property set implementation supports ::com::sun::star::uno::Sequence< OUString > aPropertySequence; /// an array of indices that maps from pPropertyNames indices to /// aPropertySequence indices sal_Int16* pSequenceIndex; /// the last set of values retrieved by getValues ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aValues; /// result of aValues.getConstArray() const ::com::sun::star::uno::Any* pValues; /// an empty Any ::com::sun::star::uno::Any aEmptyAny; public: MultiPropertySetHelper( const sal_Char** pNames ); ~MultiPropertySetHelper(); /** * Call hasPropertiesByName for the provided XPropertySetInfo and build * list of allowed properties. */ void hasProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> & ); /** * Return whether hasProperties was called * (i.e. if we are ready to call getValues) */ bool checkedProperties(); /** * Get values from the XMultiPropertySet. * * May only be called after hasProperties() was called for the * appropriate XPropertySetInfo. */ void getValues( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet> & ); /** * Get values from the XPropertySet. This can be much slower than * getValues( const Reference<XMultiPropertySet& ) and hence * should be avoided. * * May only be called after hasProperties() was called for the * appropriate XPropertySetInfo. */ void getValues( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> & ); /** * Get a value from the values array. * * May only be called after getValues() was called. */ inline const ::com::sun::star::uno::Any& getValue( sal_Int16 nIndex ); /** * Find out if this property is supported. * * May only be called after hasProperties() was called. */ inline bool hasProperty( sal_Int16 nIndex ); /** * Get a value from the XPropertySet on demand. * * If neither getValues nor getValueOnDemand has been called already * after the last call to resetValues, the values are retrieved * using getValues. Otherwise the value already retrieved is returned. * In case XMultiPropertySet is supported by the XPropertySet and * bTryMult is set, the XMultiPropertySet is used to get the values. * */ const ::com::sun::star::uno::Any& getValue( sal_Int16 nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> &, bool bTryMulti = false ); /** * Get a value from the XMultiPropertySet on demand. * * If neither getValues nor getValueOnDemand has been called already * after the last call to resetValues, the values are retrieved * using getValues. Otherwise the value already retrieved is returned. * In case XMultiPropertySet is supported by the XPropertySet, * XMultiPropertySet is used to get the values. * */ const ::com::sun::star::uno::Any& getValue( sal_Int16 nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet> & ); inline void resetValues() { pValues = 0; } }; // inline implementations of the often-called methods getValue and hasProperty: const ::com::sun::star::uno::Any& MultiPropertySetHelper::getValue( sal_Int16 nValueNo ) { DBG_ASSERT( pValues != NULL, "called getValue() without calling getValues() before"); DBG_ASSERT( pSequenceIndex != NULL, "called getValue() without calling hasProperties() before" ); DBG_ASSERT( nValueNo < nLength, "index out of range" ); sal_Int16 nIndex = pSequenceIndex[ nValueNo ]; return ( nIndex != -1 ) ? pValues[ nIndex ] : aEmptyAny; } bool MultiPropertySetHelper::hasProperty( sal_Int16 nValueNo ) { DBG_ASSERT( pSequenceIndex != NULL, "called getValue() without calling hasProperties() before" ); DBG_ASSERT( nValueNo < nLength, "index out of range" ); return pSequenceIndex[ nValueNo ] != -1; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>xmloff: convert legacy asserts in MultiPropertySetHelper<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_XMLOFF_INC_MULTIPROPERTYSETHELPER_HXX #define INCLUDED_XMLOFF_INC_MULTIPROPERTYSETHELPER_HXX #include <rtl/ustring.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <tools/debug.hxx> namespace com { namespace sun { namespace star { namespace beans { class XMultiPropertySet; } namespace beans { class XPropertySet; } namespace beans { class XPropertySetInfo; } } } } /** * The MultiPropertySetHelper performs the following functions: * * Given a list of property names (as sal_Char** or OUString*), it can * query an XMultiPropertySet (or XPropertySet) which of these properties * it supports (method hasProperties(...)). The properties *MUST* be * sorted alphabetically. * * Then, the X(Multi)PropertySet can be queried for values, and only * the supported properties are queried. (method getValues(...)) The * values are stored in the helper itself. * * Finally, each property can be queried for existence * (method hasProperty(...)) or its value (method (getValue(...))). * * After some initial preparation (hasProperties, getValues) the * MultiPropertySetHelper can be used similarly to an * XPropertySet in that you can query the values in the places where you * need them. However, if an XMultiPropertySet is supplied, the queries * are more efficient, often significantly so. */ class MultiPropertySetHelper { /// names of all properties OUString* pPropertyNames; /// length of pPropertyNames array sal_Int16 nLength; /// the sequence of property names that the current (multi) /// property set implementation supports ::com::sun::star::uno::Sequence< OUString > aPropertySequence; /// an array of indices that maps from pPropertyNames indices to /// aPropertySequence indices sal_Int16* pSequenceIndex; /// the last set of values retrieved by getValues ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aValues; /// result of aValues.getConstArray() const ::com::sun::star::uno::Any* pValues; /// an empty Any ::com::sun::star::uno::Any aEmptyAny; public: MultiPropertySetHelper( const sal_Char** pNames ); ~MultiPropertySetHelper(); /** * Call hasPropertiesByName for the provided XPropertySetInfo and build * list of allowed properties. */ void hasProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> & ); /** * Return whether hasProperties was called * (i.e. if we are ready to call getValues) */ bool checkedProperties(); /** * Get values from the XMultiPropertySet. * * May only be called after hasProperties() was called for the * appropriate XPropertySetInfo. */ void getValues( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet> & ); /** * Get values from the XPropertySet. This can be much slower than * getValues( const Reference<XMultiPropertySet& ) and hence * should be avoided. * * May only be called after hasProperties() was called for the * appropriate XPropertySetInfo. */ void getValues( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> & ); /** * Get a value from the values array. * * May only be called after getValues() was called. */ inline const ::com::sun::star::uno::Any& getValue( sal_Int16 nIndex ); /** * Find out if this property is supported. * * May only be called after hasProperties() was called. */ inline bool hasProperty( sal_Int16 nIndex ); /** * Get a value from the XPropertySet on demand. * * If neither getValues nor getValueOnDemand has been called already * after the last call to resetValues, the values are retrieved * using getValues. Otherwise the value already retrieved is returned. * In case XMultiPropertySet is supported by the XPropertySet and * bTryMult is set, the XMultiPropertySet is used to get the values. * */ const ::com::sun::star::uno::Any& getValue( sal_Int16 nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> &, bool bTryMulti = false ); /** * Get a value from the XMultiPropertySet on demand. * * If neither getValues nor getValueOnDemand has been called already * after the last call to resetValues, the values are retrieved * using getValues. Otherwise the value already retrieved is returned. * In case XMultiPropertySet is supported by the XPropertySet, * XMultiPropertySet is used to get the values. * */ const ::com::sun::star::uno::Any& getValue( sal_Int16 nIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet> & ); inline void resetValues() { pValues = 0; } }; // inline implementations of the often-called methods getValue and hasProperty: const ::com::sun::star::uno::Any& MultiPropertySetHelper::getValue( sal_Int16 nValueNo ) { assert(pValues && "called getValue() without calling getValues()"); assert(pSequenceIndex && "called getValue() without calling hasProperties()"); assert(nValueNo < nLength); sal_Int16 nIndex = pSequenceIndex[ nValueNo ]; return ( nIndex != -1 ) ? pValues[ nIndex ] : aEmptyAny; } bool MultiPropertySetHelper::hasProperty( sal_Int16 nValueNo ) { assert(pSequenceIndex && "called hasProperty() without calling hasProperties()"); assert(nValueNo < nLength); return pSequenceIndex[ nValueNo ] != -1; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/** Copyright (c) 2013, Philip Deegan. 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 Philip Deegan 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 _KUL_OS_OS_HPP_ #define _KUL_OS_OS_HPP_ #include <pwd.h> #include <thread> #include <fstream> #include <stdio.h> #include <dirent.h> #include <stdlib.h> #include <unistd.h> #include <algorithm> #include <sys/stat.h> #include <sys/types.h> namespace kul{ class Dir; namespace fs { class KulTimeStampsResolver{ private: static void GET(const char*const p, uint16_t& a, uint16_t& c, uint16_t& m){ struct stat att; if(stat(p, &att) != -1){ a = att.st_atime; m = att.st_mtime; } } friend class kul::Dir; }; } // END NAMESPACE fs } // END NAMESPACE kul #endif /* _KUL_OS_OS_HPP_ */ <commit_msg>gtest/gbench initial<commit_after>/** Copyright (c) 2013, Philip Deegan. 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 Philip Deegan 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 _KUL_OS_OS_HPP_ #define _KUL_OS_OS_HPP_ #include <pwd.h> #include <thread> #include <fstream> #include <stdio.h> #include <dirent.h> #include <stdlib.h> #include <unistd.h> #include <algorithm> #include <sys/stat.h> #include <sys/types.h> namespace kul{ class Dir; namespace fs { class KulTimeStampsResolver{ private: static void GET(const char*const p, uint64_t& a, uint64_t& c, uint64_t& m){ struct stat att; if(stat(p, &att) != -1){ a = att.st_atime; m = att.st_mtime; } } friend class kul::Dir; }; } // END NAMESPACE fs } // END NAMESPACE kul #endif /* _KUL_OS_OS_HPP_ */ <|endoftext|>
<commit_before>// cvt.c - IEEE floating point formatting routines for FreeBSD // from GNU libc-4.6.27 // // Copyright (C) 2002 Michael Ringgaard. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the project nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. #include <math.h> #define CVTBUFSIZE 500 static char* cvt(double arg, int ndigits, int *decpt, int *sign, char *buf, int eflag) { int r2; double fi, fj; char* p,* p1; if (ndigits < 0) ndigits = 0; if (ndigits >= CVTBUFSIZE - 1) ndigits = CVTBUFSIZE - 2; r2 = 0; *sign = 0; p = &buf[0]; if (arg < 0) { *sign = 1; arg = -arg; } arg = modf(arg, &fi); p1 = &buf[CVTBUFSIZE]; if (fi != 0) { p1 = &buf[CVTBUFSIZE]; while (fi != 0) { fj = modf(fi / 10, &fi); *--p1 = (int)((fj + .03) * 10) + '0'; r2++; } while (p1 < &buf[CVTBUFSIZE]) *p++ = *p1++; } else if (arg > 0) while ((fj = arg * 10) < 1) { arg = fj; r2--; } p1 = &buf[ndigits]; if (eflag == 0) p1 += r2; *decpt = r2; if (p1 < &buf[0]) { buf[0] = '\0'; return buf; } while (p <= p1 && p < &buf[CVTBUFSIZE]) { arg *= 10; arg = modf(arg, &fj); *p++ = (int) fj + '0'; } if (p1 >= &buf[CVTBUFSIZE]) { buf[CVTBUFSIZE - 1] = '\0'; return buf; } p = p1; *p1 += 5; while (*p1 > '9') { *p1 = '0'; if (p1 > buf) ++*--p1; else { *p1 = '1'; (*decpt)++; if (eflag == 0) { if (p > buf) *p = '0'; p++; } } } *p = '\0'; return buf; } char *ecvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf) { return cvt(arg, ndigits, decpt, sign, buf, 1); } char *fcvtbuf(double arg, int ndigits, int *decpt, int *sign, char *buf) { return cvt(arg, ndigits, decpt, sign, buf, 0); } <commit_msg>Formatting.<commit_after>// cvt.c - IEEE floating point formatting routines for FreeBSD // from GNU libc-4.6.27 // // Copyright (C) 2002 Michael Ringgaard. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the project nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. #include <math.h> #define CVTBUFSIZE 500 namespace fixfmt { char* cvt(double arg, int ndigits, int* decpt, int* sign, char* buf, int eflag) { int r2; double fi, fj; char* p,* p1; if (ndigits < 0) ndigits = 0; if (ndigits >= CVTBUFSIZE - 1) ndigits = CVTBUFSIZE - 2; r2 = 0; *sign = 0; p = &buf[0]; if (arg < 0) { *sign = 1; arg = -arg; } arg = modf(arg, &fi); p1 = &buf[CVTBUFSIZE]; if (fi != 0) { p1 = &buf[CVTBUFSIZE]; while (fi != 0) { fj = modf(fi / 10, &fi); *--p1 = (int)((fj + .03) * 10) + '0'; r2++; } while (p1 < &buf[CVTBUFSIZE]) *p++ = *p1++; } else if (arg > 0) while ((fj = arg * 10) < 1) { arg = fj; r2--; } p1 = &buf[ndigits]; if (eflag == 0) p1 += r2; *decpt = r2; if (p1 < &buf[0]) { buf[0] = '\0'; return buf; } while (p <= p1 && p < &buf[CVTBUFSIZE]) { arg *= 10; arg = modf(arg, &fj); *p++ = (int) fj + '0'; } if (p1 >= &buf[CVTBUFSIZE]) { buf[CVTBUFSIZE - 1] = '\0'; return buf; } p = p1; *p1 += 5; while (*p1 > '9') { *p1 = '0'; if (p1 > buf) ++*--p1; else { *p1 = '1'; (*decpt)++; if (eflag == 0) { if (p > buf) *p = '0'; p++; } } } *p = '\0'; return buf; } char* ecvtbuf(double arg, int ndigits, int* decpt, int* sign, char* buf) { return cvt(arg, ndigits, decpt, sign, buf, 1); } char* fcvtbuf(double arg, int ndigits, int* decpt, int* sign, char* buf) { return cvt(arg, ndigits, decpt, sign, buf, 0); } } // namespace fixfmt <|endoftext|>
<commit_before>#include "DiagPrinterFancyUnix.hpp" using namespace Mond; DiagPrinterFancy::DiagPrinterFancy(Source &source) : DiagPrinterFancyCore(source) { } void DiagPrinterFancy::SetColor(Severity s) { } void DiagPrinterFancy::ResetColor() { }<commit_msg>Added color to Unix fancy printer.<commit_after>#include "DiagPrinterFancyUnix.hpp" using namespace Mond; DiagPrinterFancy::DiagPrinterFancy(Source &source) : DiagPrinterFancyCore(source) { } void DiagPrinterFancy::SetColor(Severity s) { switch (s) { case Info: printf("\x1B[1;36m"); break; case Warning: printf("\x1B[1;33m"); break; case Error: printf("\x1B[1;31m"); break; } } void DiagPrinterFancy::ResetColor() { printf("\x1B[0m"); }<|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. #if defined(OS_MACOSX) #include <signal.h> #include <unistd.h> #endif // OS_MACOSX #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/i18n/rtl.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/metrics/field_trial.h" #include "base/message_loop.h" #include "base/metrics/histogram.h" #include "base/metrics/stats_counters.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gfx_resource_provider.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/net/net_resource_provider.h" #include "chrome/common/pepper_plugin_registry.h" #include "chrome/renderer/renderer_main_platform_delegate.h" #include "chrome/renderer/render_process_impl.h" #include "chrome/renderer/render_thread.h" #include "content/common/main_function_params.h" #include "content/common/hi_res_timer_manager.h" #include "grit/generated_resources.h" #include "net/base/net_module.h" #include "ui/base/system_monitor/system_monitor.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/gfx_module.h" #if defined(OS_MACOSX) #include "base/eintr_wrapper.h" #include "chrome/app/breakpad_mac.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #endif // OS_MACOSX #if defined(OS_MACOSX) namespace { // TODO(viettrungluu): crbug.com/28547: The following signal handling is needed, // as a stopgap, to avoid leaking due to not releasing Breakpad properly. // Without this problem, this could all be eliminated. Remove when Breakpad is // fixed? // TODO(viettrungluu): Code taken from browser_main.cc (with a bit of editing). // The code should be properly shared (or this code should be eliminated). int g_shutdown_pipe_write_fd = -1; void SIGTERMHandler(int signal) { RAW_CHECK(signal == SIGTERM); RAW_LOG(INFO, "Handling SIGTERM in renderer."); // Reinstall the default handler. We had one shot at graceful shutdown. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIG_DFL; CHECK(sigaction(signal, &action, NULL) == 0); RAW_CHECK(g_shutdown_pipe_write_fd != -1); size_t bytes_written = 0; do { int rv = HANDLE_EINTR( write(g_shutdown_pipe_write_fd, reinterpret_cast<const char*>(&signal) + bytes_written, sizeof(signal) - bytes_written)); RAW_CHECK(rv >= 0); bytes_written += rv; } while (bytes_written < sizeof(signal)); RAW_LOG(INFO, "Wrote signal to shutdown pipe."); } class ShutdownDetector : public base::PlatformThread::Delegate { public: explicit ShutdownDetector(int shutdown_fd) : shutdown_fd_(shutdown_fd) { CHECK(shutdown_fd_ != -1); } virtual void ThreadMain() { int signal; size_t bytes_read = 0; ssize_t ret; do { ret = HANDLE_EINTR( read(shutdown_fd_, reinterpret_cast<char*>(&signal) + bytes_read, sizeof(signal) - bytes_read)); if (ret < 0) { NOTREACHED() << "Unexpected error: " << strerror(errno); break; } else if (ret == 0) { NOTREACHED() << "Unexpected closure of shutdown pipe."; break; } bytes_read += ret; } while (bytes_read < sizeof(signal)); if (bytes_read == sizeof(signal)) VLOG(1) << "Handling shutdown for signal " << signal << "."; else VLOG(1) << "Handling shutdown for unknown signal."; // Clean up Breakpad if necessary. if (IsCrashReporterEnabled()) { VLOG(1) << "Cleaning up Breakpad."; DestructCrashReporter(); } else { VLOG(1) << "Breakpad not enabled; no clean-up needed."; } // Something went seriously wrong, so get out. if (bytes_read != sizeof(signal)) { LOG(WARNING) << "Failed to get signal. Quitting ungracefully."; _exit(1); } // Re-raise the signal. kill(getpid(), signal); // The signal may be handled on another thread. Give that a chance to // happen. sleep(3); // We really should be dead by now. For whatever reason, we're not. Exit // immediately, with the exit status set to the signal number with bit 8 // set. On the systems that we care about, this exit status is what is // normally used to indicate an exit by this signal's default handler. // This mechanism isn't a de jure standard, but even in the worst case, it // should at least result in an immediate exit. LOG(WARNING) << "Still here, exiting really ungracefully."; _exit(signal | (1 << 7)); } private: const int shutdown_fd_; DISALLOW_COPY_AND_ASSIGN(ShutdownDetector); }; } // namespace #endif // OS_MACOSX // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } #if !defined(OFFICIAL_BUILD) // This parameter causes an assertion too. if (command_line.HasSwitch(switches::kRendererCheckFalseTest)) { CHECK(false); } #endif // !defined(OFFICIAL_BUILD) // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { ChildProcess::WaitForDebugger("Renderer"); } } // mainline routine for running as the Renderer process int RendererMain(const MainFunctionParams& parameters) { TRACE_EVENT_BEGIN("RendererMain", 0, ""); const CommandLine& parsed_command_line = parameters.command_line_; base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_; #if defined(OS_MACOSX) // TODO(viettrungluu): Code taken from browser_main.cc. int pipefd[2]; int ret = pipe(pipefd); if (ret < 0) { PLOG(DFATAL) << "Failed to create pipe"; } else { int shutdown_pipe_read_fd = pipefd[0]; g_shutdown_pipe_write_fd = pipefd[1]; const size_t kShutdownDetectorThreadStackSize = 4096; if (!base::PlatformThread::CreateNonJoinable( kShutdownDetectorThreadStackSize, new ShutdownDetector(shutdown_pipe_read_fd))) { LOG(DFATAL) << "Failed to create shutdown detector task."; } } // crbug.com/28547: When Breakpad is in use, handle SIGTERM to avoid leaking // Mach ports. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGTERMHandler; CHECK(sigaction(SIGTERM, &action, NULL) == 0); #endif // OS_MACOSX #if defined(OS_CHROMEOS) // As Zygote process starts up earlier than browser process gets its own // locale (at login time for Chrome OS), we have to set the ICU default // locale for renderer process here. // ICU locale will be used for fallback font selection etc. if (parsed_command_line.HasSwitch(switches::kLang)) { const std::string locale = parsed_command_line.GetSwitchValueASCII(switches::kLang); base::i18n::SetICUDefaultLocale(locale); } #endif // Configure modules that need access to resources. net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider); gfx::GfxModule::SetResourceProvider(chrome::GfxResourceProvider); // This function allows pausing execution using the --renderer-startup-dialog // flag allowing us to attach a debugger. // Do not move this function down since that would mean we can't easily debug // whatever occurs before it. HandleRendererErrorTestParameters(parsed_command_line); RendererMainPlatformDelegate platform(parameters); base::StatsScope<base::StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); #if defined(OS_MACOSX) // As long as we use Cocoa in the renderer (for the forseeable future as of // now; see http://crbug.com/13890 for info) we need to have a UI loop. MessageLoop main_message_loop(MessageLoop::TYPE_UI); #else // The main message loop of the renderer services doesn't have IO or UI tasks, // unless in-process-plugins is used. MessageLoop main_message_loop(RenderProcessImpl::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT); #endif base::PlatformThread::SetName("CrRendererMain"); ui::SystemMonitor system_monitor; HighResolutionTimerManager hi_res_timer_manager; platform.PlatformInitialize(); bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); platform.InitSandboxTests(no_sandbox); // Initialize histogram statistics gathering system. // Don't create StatisticsRecorder in the single process mode. scoped_ptr<base::StatisticsRecorder> statistics; if (!base::StatisticsRecorder::IsActive()) { statistics.reset(new base::StatisticsRecorder()); } // Initialize statistical testing infrastructure. base::FieldTrialList field_trial; // Ensure any field trials in browser are reflected into renderer. if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) { std::string persistent = parsed_command_line.GetSwitchValueASCII( switches::kForceFieldTestNameAndValue); bool ret = field_trial.CreateTrialsInChildProcess(persistent); DCHECK(ret); } // Load pepper plugins before engaging the sandbox. PepperPluginRegistry::GetInstance(); { #if !defined(OS_LINUX) // TODO(markus): Check if it is OK to unconditionally move this // instruction down. RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif bool run_loop = true; if (!no_sandbox) { run_loop = platform.EnableSandbox(); } else { LOG(ERROR) << "Running without renderer sandbox"; } #if defined(OS_LINUX) RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif platform.RunSandboxTests(); startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { if (pool) pool->Recycle(); TRACE_EVENT_BEGIN("RendererMain.START_MSG_LOOP", 0, 0); MessageLoop::current()->Run(); TRACE_EVENT_END("RendererMain.START_MSG_LOOP", 0, 0); } } platform.PlatformUninitialize(); TRACE_EVENT_END("RendererMain", 0, ""); return 0; } <commit_msg>Add a histogram to measure task execution time for the render thread.<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. #if defined(OS_MACOSX) #include <signal.h> #include <unistd.h> #endif // OS_MACOSX #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/i18n/rtl.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/metrics/field_trial.h" #include "base/message_loop.h" #include "base/metrics/histogram.h" #include "base/metrics/stats_counters.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/ref_counted.h" #include "base/string_util.h" #include "base/threading/platform_thread.h" #include "base/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gfx_resource_provider.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/net/net_resource_provider.h" #include "chrome/common/pepper_plugin_registry.h" #include "chrome/renderer/renderer_main_platform_delegate.h" #include "chrome/renderer/render_process_impl.h" #include "chrome/renderer/render_thread.h" #include "content/common/main_function_params.h" #include "content/common/hi_res_timer_manager.h" #include "grit/generated_resources.h" #include "net/base/net_module.h" #include "ui/base/system_monitor/system_monitor.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/gfx_module.h" #if defined(OS_MACOSX) #include "base/eintr_wrapper.h" #include "chrome/app/breakpad_mac.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #endif // OS_MACOSX #if defined(OS_MACOSX) namespace { // TODO(viettrungluu): crbug.com/28547: The following signal handling is needed, // as a stopgap, to avoid leaking due to not releasing Breakpad properly. // Without this problem, this could all be eliminated. Remove when Breakpad is // fixed? // TODO(viettrungluu): Code taken from browser_main.cc (with a bit of editing). // The code should be properly shared (or this code should be eliminated). int g_shutdown_pipe_write_fd = -1; void SIGTERMHandler(int signal) { RAW_CHECK(signal == SIGTERM); RAW_LOG(INFO, "Handling SIGTERM in renderer."); // Reinstall the default handler. We had one shot at graceful shutdown. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIG_DFL; CHECK(sigaction(signal, &action, NULL) == 0); RAW_CHECK(g_shutdown_pipe_write_fd != -1); size_t bytes_written = 0; do { int rv = HANDLE_EINTR( write(g_shutdown_pipe_write_fd, reinterpret_cast<const char*>(&signal) + bytes_written, sizeof(signal) - bytes_written)); RAW_CHECK(rv >= 0); bytes_written += rv; } while (bytes_written < sizeof(signal)); RAW_LOG(INFO, "Wrote signal to shutdown pipe."); } class ShutdownDetector : public base::PlatformThread::Delegate { public: explicit ShutdownDetector(int shutdown_fd) : shutdown_fd_(shutdown_fd) { CHECK(shutdown_fd_ != -1); } virtual void ThreadMain() { int signal; size_t bytes_read = 0; ssize_t ret; do { ret = HANDLE_EINTR( read(shutdown_fd_, reinterpret_cast<char*>(&signal) + bytes_read, sizeof(signal) - bytes_read)); if (ret < 0) { NOTREACHED() << "Unexpected error: " << strerror(errno); break; } else if (ret == 0) { NOTREACHED() << "Unexpected closure of shutdown pipe."; break; } bytes_read += ret; } while (bytes_read < sizeof(signal)); if (bytes_read == sizeof(signal)) VLOG(1) << "Handling shutdown for signal " << signal << "."; else VLOG(1) << "Handling shutdown for unknown signal."; // Clean up Breakpad if necessary. if (IsCrashReporterEnabled()) { VLOG(1) << "Cleaning up Breakpad."; DestructCrashReporter(); } else { VLOG(1) << "Breakpad not enabled; no clean-up needed."; } // Something went seriously wrong, so get out. if (bytes_read != sizeof(signal)) { LOG(WARNING) << "Failed to get signal. Quitting ungracefully."; _exit(1); } // Re-raise the signal. kill(getpid(), signal); // The signal may be handled on another thread. Give that a chance to // happen. sleep(3); // We really should be dead by now. For whatever reason, we're not. Exit // immediately, with the exit status set to the signal number with bit 8 // set. On the systems that we care about, this exit status is what is // normally used to indicate an exit by this signal's default handler. // This mechanism isn't a de jure standard, but even in the worst case, it // should at least result in an immediate exit. LOG(WARNING) << "Still here, exiting really ungracefully."; _exit(signal | (1 << 7)); } private: const int shutdown_fd_; DISALLOW_COPY_AND_ASSIGN(ShutdownDetector); }; } // namespace #endif // OS_MACOSX // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } #if !defined(OFFICIAL_BUILD) // This parameter causes an assertion too. if (command_line.HasSwitch(switches::kRendererCheckFalseTest)) { CHECK(false); } #endif // !defined(OFFICIAL_BUILD) // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { ChildProcess::WaitForDebugger("Renderer"); } } // This is a simplified version of the browser Jankometer, which measures // the processing time of tasks on the render thread. class RendererMessageLoopObserver : public MessageLoop::TaskObserver { public: RendererMessageLoopObserver() : process_times_(base::Histogram::FactoryGet( "Chrome.ProcMsgL RenderThread", 1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag)) {} virtual ~RendererMessageLoopObserver() {} virtual void WillProcessTask(const Task* task) { begin_process_message_ = base::TimeTicks::Now(); } virtual void DidProcessTask(const Task* task) { if (begin_process_message_ != base::TimeTicks()) process_times_->AddTime(base::TimeTicks::Now() - begin_process_message_); } private: base::TimeTicks begin_process_message_; scoped_refptr<base::Histogram> process_times_; DISALLOW_COPY_AND_ASSIGN(RendererMessageLoopObserver); }; // mainline routine for running as the Renderer process int RendererMain(const MainFunctionParams& parameters) { TRACE_EVENT_BEGIN("RendererMain", 0, ""); const CommandLine& parsed_command_line = parameters.command_line_; base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_; #if defined(OS_MACOSX) // TODO(viettrungluu): Code taken from browser_main.cc. int pipefd[2]; int ret = pipe(pipefd); if (ret < 0) { PLOG(DFATAL) << "Failed to create pipe"; } else { int shutdown_pipe_read_fd = pipefd[0]; g_shutdown_pipe_write_fd = pipefd[1]; const size_t kShutdownDetectorThreadStackSize = 4096; if (!base::PlatformThread::CreateNonJoinable( kShutdownDetectorThreadStackSize, new ShutdownDetector(shutdown_pipe_read_fd))) { LOG(DFATAL) << "Failed to create shutdown detector task."; } } // crbug.com/28547: When Breakpad is in use, handle SIGTERM to avoid leaking // Mach ports. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGTERMHandler; CHECK(sigaction(SIGTERM, &action, NULL) == 0); #endif // OS_MACOSX #if defined(OS_CHROMEOS) // As Zygote process starts up earlier than browser process gets its own // locale (at login time for Chrome OS), we have to set the ICU default // locale for renderer process here. // ICU locale will be used for fallback font selection etc. if (parsed_command_line.HasSwitch(switches::kLang)) { const std::string locale = parsed_command_line.GetSwitchValueASCII(switches::kLang); base::i18n::SetICUDefaultLocale(locale); } #endif // Configure modules that need access to resources. net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider); gfx::GfxModule::SetResourceProvider(chrome::GfxResourceProvider); // This function allows pausing execution using the --renderer-startup-dialog // flag allowing us to attach a debugger. // Do not move this function down since that would mean we can't easily debug // whatever occurs before it. HandleRendererErrorTestParameters(parsed_command_line); RendererMainPlatformDelegate platform(parameters); base::StatsScope<base::StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); RendererMessageLoopObserver task_observer; #if defined(OS_MACOSX) // As long as we use Cocoa in the renderer (for the forseeable future as of // now; see http://crbug.com/13890 for info) we need to have a UI loop. MessageLoop main_message_loop(MessageLoop::TYPE_UI); #else // The main message loop of the renderer services doesn't have IO or UI tasks, // unless in-process-plugins is used. MessageLoop main_message_loop(RenderProcessImpl::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT); #endif main_message_loop.AddTaskObserver(&task_observer); base::PlatformThread::SetName("CrRendererMain"); ui::SystemMonitor system_monitor; HighResolutionTimerManager hi_res_timer_manager; platform.PlatformInitialize(); bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); platform.InitSandboxTests(no_sandbox); // Initialize histogram statistics gathering system. // Don't create StatisticsRecorder in the single process mode. scoped_ptr<base::StatisticsRecorder> statistics; if (!base::StatisticsRecorder::IsActive()) { statistics.reset(new base::StatisticsRecorder()); } // Initialize statistical testing infrastructure. base::FieldTrialList field_trial; // Ensure any field trials in browser are reflected into renderer. if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) { std::string persistent = parsed_command_line.GetSwitchValueASCII( switches::kForceFieldTestNameAndValue); bool ret = field_trial.CreateTrialsInChildProcess(persistent); DCHECK(ret); } // Load pepper plugins before engaging the sandbox. PepperPluginRegistry::GetInstance(); { #if !defined(OS_LINUX) // TODO(markus): Check if it is OK to unconditionally move this // instruction down. RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif bool run_loop = true; if (!no_sandbox) { run_loop = platform.EnableSandbox(); } else { LOG(ERROR) << "Running without renderer sandbox"; } #if defined(OS_LINUX) RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif platform.RunSandboxTests(); startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { if (pool) pool->Recycle(); TRACE_EVENT_BEGIN("RendererMain.START_MSG_LOOP", 0, 0); MessageLoop::current()->Run(); TRACE_EVENT_END("RendererMain.START_MSG_LOOP", 0, 0); } } platform.PlatformUninitialize(); TRACE_EVENT_END("RendererMain", 0, ""); return 0; } <|endoftext|>
<commit_before>#include "data-general.hpp" using namespace std; string tostring(int i) { ostringstream tmp; tmp << i; return tmp.str(); } int stringToInt(string const& str) { istringstream i(str); int x; i >> x; return x; } float stringToFloat(string const& str) { istringstream i(str); float x; i >> x; return x; } vector<string> &split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } vector<string> split(const string &s, char delim) { // taken from http://stackoverflow.com/a/236803 vector<string> elems; split(s, delim, elems); return elems; } string removeAllQuotes(string s) { s.erase(remove(s.begin(), s.end(), '\"'), s.end()); return s; } string removeTrailingSlashes(string s) { if (s[s.length()-1] == '/') s.erase(s.length()-1, s.length()); return s; } string removeTrailingText(string s, string toRemove) { if (s.find(toRemove) != s.npos) s.erase(s.find(toRemove)); return s; } string removeStartingText(string s, string toRemove) { if (s.find(toRemove) != s.npos) s.erase(s.find_first_of(toRemove), s.find_first_of(toRemove)+toRemove.length()); return s; } string deDoubleString(string s) { // Todo: write this. return s; } void printEntireRecord(vector<string> record) { for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) { cout << *i; if (i!=record.end()-1) cout << ", "; else cout << endl; } } <commit_msg>New algorithm for removing slashes at the end of strings<commit_after>#include "data-general.hpp" using namespace std; string tostring(int i) { ostringstream tmp; tmp << i; return tmp.str(); } int stringToInt(string const& str) { istringstream i(str); int x; i >> x; return x; } float stringToFloat(string const& str) { istringstream i(str); float x; i >> x; return x; } vector<string> &split(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while (getline(ss, item, delim)) { elems.push_back(item); } return elems; } vector<string> split(const string &s, char delim) { // taken from http://stackoverflow.com/a/236803 vector<string> elems; split(s, delim, elems); return elems; } string removeAllQuotes(string s) { s.erase(remove(s.begin(), s.end(), '\"'), s.end()); return s; } string removeTrailingSlashes(string s) { if (s[s.length()-1] == '/') s = s.substr(0, s.length()-1); return s; } string removeTrailingText(string s, string toRemove) { if (s.find(toRemove) != s.npos) s.erase(s.find(toRemove)); return s; } string removeStartingText(string s, string toRemove) { if (s.find(toRemove) != s.npos) s.erase(s.find_first_of(toRemove), s.find_first_of(toRemove)+toRemove.length()); return s; } string deDoubleString(string s) { // Todo: write this. return s; } void printEntireRecord(vector<string> record) { for (vector<string>::iterator i = record.begin(); i != record.end(); ++i) { cout << *i; if (i!=record.end()-1) cout << ", "; else cout << endl; } } <|endoftext|>
<commit_before>/* * guide_algorithm_resistswitch.cpp * PHD Guiding * * Created by Bret McKee * Copyright (c) 2012 Bret McKee * All rights reserved. * * Based upon work by Craig Stark. * Copyright (c) 2006-2010 Craig Stark. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Bret McKee, Dad Dog Development, * Craig Stark, Stark Labs 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 "phd.h" static const double DefaultMinMove = 0.2; static const double DefaultAggression = 1.0; GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitch(Mount *pMount, GuideAxis axis) : GuideAlgorithm(pMount, axis) { double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove); SetMinMove(minMove); double aggr = pConfig->Profile.GetDouble(GetConfigPath() + "/aggression", DefaultAggression); SetAggression(aggr); bool enable = pConfig->Profile.GetBoolean(GetConfigPath() + "/fastSwitch", true); SetFastSwitchEnabled(enable); reset(); } GuideAlgorithmResistSwitch::~GuideAlgorithmResistSwitch(void) { } GUIDE_ALGORITHM GuideAlgorithmResistSwitch::Algorithm() const { return GUIDE_ALGORITHM_RESIST_SWITCH; } void GuideAlgorithmResistSwitch::reset(void) { m_history.Empty(); while (m_history.GetCount() < HISTORY_SIZE) { m_history.Add(0.0); } m_currentSide = 0; } static int sign(double x) { int iReturn = 0; if (x > 0.0) { iReturn = 1; } else if (x < 0.0) { iReturn = -1; } return iReturn; } double GuideAlgorithmResistSwitch::result(double input) { double dReturn = input; m_history.Add(input); m_history.RemoveAt(0); try { if (fabs(input) < m_minMove) { throw THROW_INFO("input < m_minMove"); } if (m_fastSwitchEnabled) { double thresh = 3.0 * m_minMove; if (sign(input) != m_currentSide && fabs(input) > thresh) { Debug.Write(wxString::Format("resist switch: large excursion: input %.2f thresh %.2f direction from %d to %d\n", input, thresh, m_currentSide, sign(input))); // force switch m_currentSide = 0; unsigned int i; for (i = 0; i < HISTORY_SIZE - 3; i++) m_history[i] = 0.0; for (; i < HISTORY_SIZE; i++) m_history[i] = input; } } int decHistory = 0; for (unsigned int i = 0; i < m_history.GetCount(); i++) { if (fabs(m_history[i]) > m_minMove) { decHistory += sign(m_history[i]); } } if (m_currentSide == 0 || sign(m_currentSide) == -sign(decHistory)) { if (abs(decHistory) < 3) { throw THROW_INFO("not compelling enough"); } double oldest = 0.0; double newest = 0.0; for (int i = 0; i < 3; i++) { oldest += m_history[i]; newest += m_history[m_history.GetCount() - (i + 1)]; } if (fabs(newest) <= fabs(oldest)) { throw THROW_INFO("Not getting worse"); } Debug.Write(wxString::Format("switching direction from %d to %d - decHistory=%d oldest=%.2f newest=%.2f\n", m_currentSide, sign(decHistory), decHistory, oldest, newest)); m_currentSide = sign(decHistory); } if (m_currentSide != sign(input)) { throw THROW_INFO("must have overshot -- vetoing move"); } } catch (const wxString& Msg) { POSSIBLY_UNUSED(Msg); dReturn = 0.0; } Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::Result() returns %.2f from input %.2f\n", dReturn, input)); return dReturn * m_aggression; } bool GuideAlgorithmResistSwitch::SetMinMove(double minMove) { bool bError = false; try { if (minMove <= 0.0) { throw ERROR_INFO("invalid minMove"); } m_minMove = minMove; m_currentSide = 0; } catch (const wxString& Msg) { POSSIBLY_UNUSED(Msg); bError = true; m_minMove = DefaultMinMove; } pConfig->Profile.SetDouble(GetConfigPath() + "/minMove", m_minMove); Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetMinMove() returns %d, m_minMove=%.2f\n", bError, m_minMove)); return bError; } bool GuideAlgorithmResistSwitch::SetAggression(double aggr) { bool bError = false; try { if (aggr < 0.0 || aggr > 1.0) { throw ERROR_INFO("invalid aggression"); } m_aggression = aggr; } catch (const wxString& Msg) { POSSIBLY_UNUSED(Msg); bError = true; m_aggression = DefaultAggression; } pConfig->Profile.SetDouble(GetConfigPath() + "/aggression", m_aggression); Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetAggression() returns %d, m_aggression=%.2f\n", bError, m_aggression)); return bError; } void GuideAlgorithmResistSwitch::SetFastSwitchEnabled(bool enable) { m_fastSwitchEnabled = enable; pConfig->Profile.SetBoolean(GetConfigPath() + "/fastSwitch", m_fastSwitchEnabled); Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetFastSwitchEnabled(%d)\n", m_fastSwitchEnabled)); } void GuideAlgorithmResistSwitch::GetParamNames(wxArrayString& names) const { names.push_back("minMove"); names.push_back("fastSwitch"); names.push_back("aggression"); } bool GuideAlgorithmResistSwitch::GetParam(const wxString& name, double *val) const { bool ok = true; if (name == "minMove") *val = GetMinMove(); else if (name == "fastSwitch") *val = GetFastSwitchEnabled() ? 1.0 : 0.0; else if (name == "aggression") *val = GetAggression(); else ok = false; return ok; } bool GuideAlgorithmResistSwitch::SetParam(const wxString& name, double val) { bool err; if (name == "minMove") err = SetMinMove(val); else if (name == "fastSwitch") { SetFastSwitchEnabled(val != 0.0); err = false; } else if (name == "aggression") err = SetAggression(val); else err = true; return !err; } wxString GuideAlgorithmResistSwitch::GetSettingsSummary() const { // return a loggable summary of current mount settings return wxString::Format("Minimum move = %.3f Aggression = %.f%% FastSwitch = %s\n", GetMinMove(), GetAggression() * 100.0, GetFastSwitchEnabled() ? "enabled" : "disabled"); } ConfigDialogPane *GuideAlgorithmResistSwitch::GetConfigDialogPane(wxWindow *pParent) { return new GuideAlgorithmResistSwitchConfigDialogPane(pParent, this); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: GuideAlgorithmResistSwitchConfigDialogPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm) : ConfigDialogPane(_("ResistSwitch Guide Algorithm"), pParent) { int width; m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000")); m_pAggression = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, _T("Aggressiveness")); DoAdd(_("Aggressiveness"), m_pAggression, wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); width = StringWidth(_T("00.00")); m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); m_pFastSwitch = new wxCheckBox(pParent, wxID_ANY, _("Fast switch for large deflections")); DoAdd(m_pFastSwitch, _("Ordinarily the Resist Switch algortithm waits several frames before switching direction. With Fast Switch enabled PHD2 will switch direction immediately if it sees a very large deflection. Enable this option if your mount has a substantial amount of backlash and PHD2 sometimes overcorrects.")); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: ~GuideAlgorithmResistSwitchConfigDialogPane(void) { } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: LoadValues(void) { m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0); m_pFastSwitch->SetValue(m_pGuideAlgorithm->GetFastSwitchEnabled()); } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: UnloadValues(void) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); m_pGuideAlgorithm->SetFastSwitchEnabled(m_pFastSwitch->GetValue()); } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane::HandleBinningChange(int oldBinVal, int newBinVal) { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove, oldBinVal, newBinVal); } GraphControlPane *GuideAlgorithmResistSwitch::GetGraphControlPane(wxWindow *pParent, const wxString& label) { return new GuideAlgorithmResistSwitchGraphControlPane(pParent, this, label); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: GuideAlgorithmResistSwitchGraphControlPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label) : GraphControlPane(pParent, label) { int width; m_pGuideAlgorithm = pGuideAlgorithm; // Aggression width = StringWidth(_T("000")); m_pAggression = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, _T("Aggressiveness")); m_pAggression->SetToolTip(wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); m_pAggression->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnAggressionSpinCtrl, this); DoAdd(m_pAggression, _T("Agr")); m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0); // Min move width = StringWidth(_T("00.00")); m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnMinMoveSpinCtrlDouble, this); DoAdd(m_pMinMove, _("MnMo")); m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: ~GuideAlgorithmResistSwitchGraphControlPane(void) { } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch minimum move", m_pMinMove->GetValue()); } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: OnAggressionSpinCtrl(wxSpinEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch aggression", m_pAggression->GetValue()); } <commit_msg>fix debug output. Fixes #785<commit_after>/* * guide_algorithm_resistswitch.cpp * PHD Guiding * * Created by Bret McKee * Copyright (c) 2012 Bret McKee * All rights reserved. * * Based upon work by Craig Stark. * Copyright (c) 2006-2010 Craig Stark. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Bret McKee, Dad Dog Development, * Craig Stark, Stark Labs 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 "phd.h" static const double DefaultMinMove = 0.2; static const double DefaultAggression = 1.0; GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitch(Mount *pMount, GuideAxis axis) : GuideAlgorithm(pMount, axis) { double minMove = pConfig->Profile.GetDouble(GetConfigPath() + "/minMove", DefaultMinMove); SetMinMove(minMove); double aggr = pConfig->Profile.GetDouble(GetConfigPath() + "/aggression", DefaultAggression); SetAggression(aggr); bool enable = pConfig->Profile.GetBoolean(GetConfigPath() + "/fastSwitch", true); SetFastSwitchEnabled(enable); reset(); } GuideAlgorithmResistSwitch::~GuideAlgorithmResistSwitch(void) { } GUIDE_ALGORITHM GuideAlgorithmResistSwitch::Algorithm() const { return GUIDE_ALGORITHM_RESIST_SWITCH; } void GuideAlgorithmResistSwitch::reset(void) { m_history.Empty(); while (m_history.GetCount() < HISTORY_SIZE) { m_history.Add(0.0); } m_currentSide = 0; } static int sign(double x) { int iReturn = 0; if (x > 0.0) { iReturn = 1; } else if (x < 0.0) { iReturn = -1; } return iReturn; } double GuideAlgorithmResistSwitch::result(double input) { double rslt = input; m_history.Add(input); m_history.RemoveAt(0); try { if (fabs(input) < m_minMove) { throw THROW_INFO("input < m_minMove"); } if (m_fastSwitchEnabled) { double thresh = 3.0 * m_minMove; if (sign(input) != m_currentSide && fabs(input) > thresh) { Debug.Write(wxString::Format("resist switch: large excursion: input %.2f thresh %.2f direction from %d to %d\n", input, thresh, m_currentSide, sign(input))); // force switch m_currentSide = 0; unsigned int i; for (i = 0; i < HISTORY_SIZE - 3; i++) m_history[i] = 0.0; for (; i < HISTORY_SIZE; i++) m_history[i] = input; } } int decHistory = 0; for (unsigned int i = 0; i < m_history.GetCount(); i++) { if (fabs(m_history[i]) > m_minMove) { decHistory += sign(m_history[i]); } } if (m_currentSide == 0 || sign(m_currentSide) == -sign(decHistory)) { if (abs(decHistory) < 3) { throw THROW_INFO("not compelling enough"); } double oldest = 0.0; double newest = 0.0; for (int i = 0; i < 3; i++) { oldest += m_history[i]; newest += m_history[m_history.GetCount() - (i + 1)]; } if (fabs(newest) <= fabs(oldest)) { throw THROW_INFO("Not getting worse"); } Debug.Write(wxString::Format("switching direction from %d to %d - decHistory=%d oldest=%.2f newest=%.2f\n", m_currentSide, sign(decHistory), decHistory, oldest, newest)); m_currentSide = sign(decHistory); } if (m_currentSide != sign(input)) { throw THROW_INFO("must have overshot -- vetoing move"); } } catch (const wxString& Msg) { POSSIBLY_UNUSED(Msg); rslt = 0.0; } rslt *= m_aggression; Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::result() returns %.2f from input %.2f\n", rslt, input)); return rslt; } bool GuideAlgorithmResistSwitch::SetMinMove(double minMove) { bool bError = false; try { if (minMove <= 0.0) { throw ERROR_INFO("invalid minMove"); } m_minMove = minMove; m_currentSide = 0; } catch (const wxString& Msg) { POSSIBLY_UNUSED(Msg); bError = true; m_minMove = DefaultMinMove; } pConfig->Profile.SetDouble(GetConfigPath() + "/minMove", m_minMove); Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetMinMove() returns %d, m_minMove=%.2f\n", bError, m_minMove)); return bError; } bool GuideAlgorithmResistSwitch::SetAggression(double aggr) { bool bError = false; try { if (aggr < 0.0 || aggr > 1.0) { throw ERROR_INFO("invalid aggression"); } m_aggression = aggr; } catch (const wxString& Msg) { POSSIBLY_UNUSED(Msg); bError = true; m_aggression = DefaultAggression; } pConfig->Profile.SetDouble(GetConfigPath() + "/aggression", m_aggression); Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetAggression() returns %d, m_aggression=%.2f\n", bError, m_aggression)); return bError; } void GuideAlgorithmResistSwitch::SetFastSwitchEnabled(bool enable) { m_fastSwitchEnabled = enable; pConfig->Profile.SetBoolean(GetConfigPath() + "/fastSwitch", m_fastSwitchEnabled); Debug.Write(wxString::Format("GuideAlgorithmResistSwitch::SetFastSwitchEnabled(%d)\n", m_fastSwitchEnabled)); } void GuideAlgorithmResistSwitch::GetParamNames(wxArrayString& names) const { names.push_back("minMove"); names.push_back("fastSwitch"); names.push_back("aggression"); } bool GuideAlgorithmResistSwitch::GetParam(const wxString& name, double *val) const { bool ok = true; if (name == "minMove") *val = GetMinMove(); else if (name == "fastSwitch") *val = GetFastSwitchEnabled() ? 1.0 : 0.0; else if (name == "aggression") *val = GetAggression(); else ok = false; return ok; } bool GuideAlgorithmResistSwitch::SetParam(const wxString& name, double val) { bool err; if (name == "minMove") err = SetMinMove(val); else if (name == "fastSwitch") { SetFastSwitchEnabled(val != 0.0); err = false; } else if (name == "aggression") err = SetAggression(val); else err = true; return !err; } wxString GuideAlgorithmResistSwitch::GetSettingsSummary() const { // return a loggable summary of current mount settings return wxString::Format("Minimum move = %.3f Aggression = %.f%% FastSwitch = %s\n", GetMinMove(), GetAggression() * 100.0, GetFastSwitchEnabled() ? "enabled" : "disabled"); } ConfigDialogPane *GuideAlgorithmResistSwitch::GetConfigDialogPane(wxWindow *pParent) { return new GuideAlgorithmResistSwitchConfigDialogPane(pParent, this); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: GuideAlgorithmResistSwitchConfigDialogPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm) : ConfigDialogPane(_("ResistSwitch Guide Algorithm"), pParent) { int width; m_pGuideAlgorithm = pGuideAlgorithm; width = StringWidth(_T("000")); m_pAggression = pFrame->MakeSpinCtrl(pParent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, _T("Aggressiveness")); DoAdd(_("Aggressiveness"), m_pAggression, wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); width = StringWidth(_T("00.00")); m_pMinMove = pFrame->MakeSpinCtrlDouble(pParent, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); DoAdd(_("Minimum Move (pixels)"), m_pMinMove, wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); m_pFastSwitch = new wxCheckBox(pParent, wxID_ANY, _("Fast switch for large deflections")); DoAdd(m_pFastSwitch, _("Ordinarily the Resist Switch algortithm waits several frames before switching direction. With Fast Switch enabled PHD2 will switch direction immediately if it sees a very large deflection. Enable this option if your mount has a substantial amount of backlash and PHD2 sometimes overcorrects.")); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: ~GuideAlgorithmResistSwitchConfigDialogPane(void) { } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: LoadValues(void) { m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0); m_pFastSwitch->SetValue(m_pGuideAlgorithm->GetFastSwitchEnabled()); } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane:: UnloadValues(void) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); m_pGuideAlgorithm->SetFastSwitchEnabled(m_pFastSwitch->GetValue()); } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchConfigDialogPane::HandleBinningChange(int oldBinVal, int newBinVal) { GuideAlgorithm::AdjustMinMoveSpinCtrl(m_pMinMove, oldBinVal, newBinVal); } GraphControlPane *GuideAlgorithmResistSwitch::GetGraphControlPane(wxWindow *pParent, const wxString& label) { return new GuideAlgorithmResistSwitchGraphControlPane(pParent, this, label); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: GuideAlgorithmResistSwitchGraphControlPane(wxWindow *pParent, GuideAlgorithmResistSwitch *pGuideAlgorithm, const wxString& label) : GraphControlPane(pParent, label) { int width; m_pGuideAlgorithm = pGuideAlgorithm; // Aggression width = StringWidth(_T("000")); m_pAggression = pFrame->MakeSpinCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 1.0, 100.0, 100.0, _T("Aggressiveness")); m_pAggression->SetToolTip(wxString::Format(_("What percentage of the computed correction should be applied? Default = %.f%%"), DefaultAggression * 100.0)); m_pAggression->Bind(wxEVT_COMMAND_SPINCTRL_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnAggressionSpinCtrl, this); DoAdd(m_pAggression, _T("Agr")); m_pAggression->SetValue(m_pGuideAlgorithm->GetAggression() * 100.0); // Min move width = StringWidth(_T("00.00")); m_pMinMove = pFrame->MakeSpinCtrlDouble(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(width, -1), wxSP_ARROW_KEYS, 0.0, 20.0, 0.0, 0.01, _T("MinMove")); m_pMinMove->SetDigits(2); m_pMinMove->SetToolTip(wxString::Format(_("How many (fractional) pixels must the star move to trigger a guide pulse? \n" "If camera is binned, this is a fraction of the binned pixel size. Default = %.2f"), DefaultMinMove)); m_pMinMove->Bind(wxEVT_COMMAND_SPINCTRLDOUBLE_UPDATED, &GuideAlgorithmResistSwitch::GuideAlgorithmResistSwitchGraphControlPane::OnMinMoveSpinCtrlDouble, this); DoAdd(m_pMinMove, _("MnMo")); m_pMinMove->SetValue(m_pGuideAlgorithm->GetMinMove()); } GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: ~GuideAlgorithmResistSwitchGraphControlPane(void) { } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: OnMinMoveSpinCtrlDouble(wxSpinDoubleEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetMinMove(m_pMinMove->GetValue()); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch minimum move", m_pMinMove->GetValue()); } void GuideAlgorithmResistSwitch:: GuideAlgorithmResistSwitchGraphControlPane:: OnAggressionSpinCtrl(wxSpinEvent& WXUNUSED(evt)) { m_pGuideAlgorithm->SetAggression(m_pAggression->GetValue() / 100.0); pFrame->NotifyGuidingParam(m_pGuideAlgorithm->GetAxis() + " Resist switch aggression", m_pAggression->GetValue()); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <experimental/filesystem> // path proximate(const path& p, error_code &ec) // path proximate(const path& p, const path& base = current_path()) // path proximate(const path& p, const path& base, error_code& ec); #include "filesystem_include.hpp" #include <type_traits> #include <vector> #include <iostream> #include <cassert> #include "test_macros.h" #include "test_iterators.h" #include "count_new.hpp" #include "rapid-cxx-test.hpp" #include "filesystem_test_helper.hpp" static int count_path_elems(const fs::path& p) { int count = 0; for (auto& elem : p) { if (elem != "/" && elem != "") ++count; } return count; } TEST_SUITE(filesystem_proximate_path_test_suite) TEST_CASE(signature_test) { using fs::path; const path p; ((void)p); std::error_code ec; ((void)ec); ASSERT_NOT_NOEXCEPT(proximate(p)); ASSERT_NOT_NOEXCEPT(proximate(p, p)); ASSERT_NOT_NOEXCEPT(proximate(p, ec)); ASSERT_NOT_NOEXCEPT(proximate(p, p, ec)); } TEST_CASE(basic_test) { using fs::path; const path cwd = fs::current_path(); const path parent_cwd = cwd.parent_path(); const path curdir = cwd.filename(); TEST_REQUIRE(!cwd.native().empty()); int cwd_depth = count_path_elems(cwd); path dot_dot_to_root; for (int i=0; i < cwd_depth; ++i) dot_dot_to_root /= ".."; path relative_cwd = cwd.native().substr(1); // clang-format off struct { std::string input; std::string base; std::string expect; } TestCases[] = { {"", "", "."}, {cwd, "a", ".."}, {parent_cwd, "a", "../.."}, {"a", cwd, "a"}, {"a", parent_cwd, "fs.op.proximate/a"}, {"/", "a", dot_dot_to_root / ".."}, {"/", "a/b", dot_dot_to_root / "../.."}, {"/", "a/b/", dot_dot_to_root / "../../.."}, {"a", "/", relative_cwd / "a"}, {"a/b", "/", relative_cwd / "a/b"}, {"a", "/net", ".." / relative_cwd / "a"}, {"//foo/", "//foo", "/foo/"}, {"//foo", "//foo/", ".."}, {"//foo", "//foo", "."}, {"//foo/", "//foo/", "."}, {"//base", "a", dot_dot_to_root / "../base"}, {"a", "a", "."}, {"a/b", "a/b", "."}, {"a/b/c/", "a/b/c/", "."}, {"//net/a/b", "//net/a/b", "."}, {"/a/d", "/a/b/c", "../../d"}, {"/a/b/c", "/a/d", "../b/c"}, {"a/b/c", "a", "b/c"}, {"a/b/c", "a/b/c/x/y", "../.."}, {"a/b/c", "a/b/c", "."}, {"a/b", "c/d", "../../a/b"} }; // clang-format on int ID = 0; for (auto& TC : TestCases) { ++ID; std::error_code ec = GetTestEC(); fs::path p(TC.input); const fs::path output = fs::proximate(p, TC.base, ec); if (ec) { TEST_CHECK(!ec); std::cerr << "TEST CASE #" << ID << " FAILED: \n"; std::cerr << " Input: '" << TC.input << "'\n"; std::cerr << " Base: '" << TC.base << "'\n"; std::cerr << " Expected: '" << TC.expect << "'\n"; std::cerr << std::endl; } else if (!PathEq(output, TC.expect)) { TEST_CHECK(PathEq(output, TC.expect)); const path canon_input = fs::weakly_canonical(TC.input); const path canon_base = fs::weakly_canonical(TC.base); const path lexically_p = canon_input.lexically_proximate(canon_base); std::cerr << "TEST CASE #" << ID << " FAILED: \n"; std::cerr << " Input: '" << TC.input << "'\n"; std::cerr << " Base: '" << TC.base << "'\n"; std::cerr << " Expected: '" << TC.expect << "'\n"; std::cerr << " Output: '" << output.native() << "'\n"; std::cerr << " Lex Prox: '" << lexically_p.native() << "'\n"; std::cerr << " Canon Input: " << canon_input << "\n"; std::cerr << " Canon Base: " << canon_base << "\n"; std::cerr << std::endl; } } } TEST_SUITE_END() <commit_msg>[libcxx][test] Fix fs::proximate tests on platforms where /net exists.<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <experimental/filesystem> // path proximate(const path& p, error_code &ec) // path proximate(const path& p, const path& base = current_path()) // path proximate(const path& p, const path& base, error_code& ec); #include "filesystem_include.hpp" #include <type_traits> #include <vector> #include <iostream> #include <cassert> #include "test_macros.h" #include "test_iterators.h" #include "count_new.hpp" #include "rapid-cxx-test.hpp" #include "filesystem_test_helper.hpp" static int count_path_elems(const fs::path& p) { int count = 0; for (auto& elem : p) { if (elem != "/" && elem != "") ++count; } return count; } TEST_SUITE(filesystem_proximate_path_test_suite) TEST_CASE(signature_test) { using fs::path; const path p; ((void)p); std::error_code ec; ((void)ec); ASSERT_NOT_NOEXCEPT(proximate(p)); ASSERT_NOT_NOEXCEPT(proximate(p, p)); ASSERT_NOT_NOEXCEPT(proximate(p, ec)); ASSERT_NOT_NOEXCEPT(proximate(p, p, ec)); } TEST_CASE(basic_test) { using fs::path; const path cwd = fs::current_path(); const path parent_cwd = cwd.parent_path(); const path curdir = cwd.filename(); TEST_REQUIRE(!cwd.native().empty()); int cwd_depth = count_path_elems(cwd); path dot_dot_to_root; for (int i=0; i < cwd_depth; ++i) dot_dot_to_root /= ".."; path relative_cwd = cwd.native().substr(1); // clang-format off struct { std::string input; std::string base; std::string expect; } TestCases[] = { {"", "", "."}, {cwd, "a", ".."}, {parent_cwd, "a", "../.."}, {"a", cwd, "a"}, {"a", parent_cwd, "fs.op.proximate/a"}, {"/", "a", dot_dot_to_root / ".."}, {"/", "a/b", dot_dot_to_root / "../.."}, {"/", "a/b/", dot_dot_to_root / "../../.."}, {"a", "/", relative_cwd / "a"}, {"a/b", "/", relative_cwd / "a/b"}, {"a", "/net", ".." / relative_cwd / "a"}, {"//foo/", "//foo", "/foo/"}, {"//foo", "//foo/", ".."}, {"//foo", "//foo", "."}, {"//foo/", "//foo/", "."}, {"//base", "a", dot_dot_to_root / "../base"}, {"a", "a", "."}, {"a/b", "a/b", "."}, {"a/b/c/", "a/b/c/", "."}, {"//foo/a/b", "//foo/a/b", "."}, {"/a/d", "/a/b/c", "../../d"}, {"/a/b/c", "/a/d", "../b/c"}, {"a/b/c", "a", "b/c"}, {"a/b/c", "a/b/c/x/y", "../.."}, {"a/b/c", "a/b/c", "."}, {"a/b", "c/d", "../../a/b"} }; // clang-format on int ID = 0; for (auto& TC : TestCases) { ++ID; std::error_code ec = GetTestEC(); fs::path p(TC.input); const fs::path output = fs::proximate(p, TC.base, ec); if (ec) { TEST_CHECK(!ec); std::cerr << "TEST CASE #" << ID << " FAILED: \n"; std::cerr << " Input: '" << TC.input << "'\n"; std::cerr << " Base: '" << TC.base << "'\n"; std::cerr << " Expected: '" << TC.expect << "'\n"; std::cerr << std::endl; } else if (!PathEq(output, TC.expect)) { TEST_CHECK(PathEq(output, TC.expect)); const path canon_input = fs::weakly_canonical(TC.input); const path canon_base = fs::weakly_canonical(TC.base); const path lexically_p = canon_input.lexically_proximate(canon_base); std::cerr << "TEST CASE #" << ID << " FAILED: \n"; std::cerr << " Input: '" << TC.input << "'\n"; std::cerr << " Base: '" << TC.base << "'\n"; std::cerr << " Expected: '" << TC.expect << "'\n"; std::cerr << " Output: '" << output.native() << "'\n"; std::cerr << " Lex Prox: '" << lexically_p.native() << "'\n"; std::cerr << " Canon Input: " << canon_input << "\n"; std::cerr << " Canon Base: " << canon_base << "\n"; std::cerr << std::endl; } } } TEST_SUITE_END() <|endoftext|>
<commit_before>// // PROJECT: Aspia Remote Desktop // FILE: host/console_session_launcher.cc // LICENSE: See top-level directory // PROGRAMMERS: Dmitry Chapyshev ([email protected]) // #include "host/console_session_launcher.h" #include <userenv.h> #include <wtsapi32.h> #include <string> #include "base/version_helpers.h" #include "base/process_helpers.h" #include "base/service_manager.h" #include "base/scoped_object.h" #include "base/scoped_wts_memory.h" #include "base/scoped_impersonator.h" #include "base/object_watcher.h" #include "base/unicode.h" #include "base/path.h" #include "base/process.h" #include "base/logging.h" namespace aspia { static const WCHAR kServiceShortName[] = L"aspia-desktop-session-launcher"; static const WCHAR kServiceFullName[] = L"Aspia Desktop Session Launcher"; // Name of the default session desktop. static WCHAR kDefaultDesktopName[] = L"winsta0\\default"; ConsoleSessionLauncher::ConsoleSessionLauncher(const std::wstring& service_id) : Service(ServiceManager::CreateUniqueServiceName(kServiceShortName, service_id)) { // Nothing } static bool CopyProcessToken(DWORD desired_access, ScopedHandle& token_out) { ScopedHandle process_token; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | desired_access, process_token.Recieve())) { LOG(ERROR) << "OpenProcessToken() failed: " << GetLastSystemErrorString(); return false; } if (!DuplicateTokenEx(process_token, desired_access, nullptr, SecurityImpersonation, TokenPrimary, token_out.Recieve())) { LOG(ERROR) << "DuplicateTokenEx() failed: " << GetLastSystemErrorString(); return false; } return true; } // Creates a copy of the current process with SE_TCB_NAME privilege enabled. static bool CreatePrivilegedToken(ScopedHandle& token_out) { ScopedHandle privileged_token; DWORD desired_access = TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE | TOKEN_DUPLICATE | TOKEN_QUERY; if (!CopyProcessToken(desired_access, privileged_token)) return false; // Get the LUID for the SE_TCB_NAME privilege. TOKEN_PRIVILEGES state; state.PrivilegeCount = 1; state.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!LookupPrivilegeValueW(nullptr, SE_TCB_NAME, &state.Privileges[0].Luid)) { LOG(ERROR) << "LookupPrivilegeValueW() failed: " << GetLastSystemErrorString(); return false; } // Enable the SE_TCB_NAME privilege. if (!AdjustTokenPrivileges(privileged_token, FALSE, &state, 0, nullptr, 0)) { LOG(ERROR) << "AdjustTokenPrivileges() failed: " << GetLastSystemErrorString(); return false; } token_out.Reset(privileged_token.Release()); return true; } // Creates a copy of the current process token for the given |session_id| so // it can be used to launch a process in that session. static bool CreateSessionToken(uint32_t session_id, ScopedHandle& token_out) { ScopedHandle session_token; DWORD desired_access = TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY; if (!CopyProcessToken(desired_access, session_token)) return false; ScopedHandle privileged_token; if (!CreatePrivilegedToken(privileged_token)) return false; { ScopedImpersonator impersonator; if (!impersonator.ImpersonateLoggedOnUser(privileged_token)) return false; // Change the session ID of the token. DWORD new_session_id = session_id; if (!SetTokenInformation(session_token, TokenSessionId, &new_session_id, sizeof(new_session_id))) { LOG(ERROR) << "SetTokenInformation() failed: " << GetLastSystemErrorString(); return false; } } token_out.Reset(session_token.Release()); return true; } static bool CreateProcessWithToken(HANDLE user_token, const std::wstring& command_line) { PROCESS_INFORMATION process_info = { 0 }; STARTUPINFOW startup_info = { 0 }; startup_info.cb = sizeof(startup_info); startup_info.lpDesktop = kDefaultDesktopName; if (!CreateProcessAsUserW(user_token, nullptr, const_cast<LPWSTR>(command_line.c_str()), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup_info, &process_info)) { LOG(ERROR) << "CreateProcessAsUserW() failed: " << GetLastSystemErrorString(); return false; } CloseHandle(process_info.hThread); CloseHandle(process_info.hProcess); return true; } static bool LaunchProcessInSession(uint32_t session_id, const std::wstring& input_channel_id, const std::wstring& output_channel_id) { std::wstring command_line; if (!GetPathW(PathKey::FILE_EXE, command_line)) return false; command_line.append(L" --run_mode="); command_line.append(kDesktopSessionSwitch); command_line.append(L" --input_channel_id="); command_line.append(input_channel_id); command_line.append(L" --output_channel_id="); command_line.append(output_channel_id); ScopedHandle session_token; if (!CreateSessionToken(session_id, session_token)) return false; return CreateProcessWithToken(session_token, command_line); } void ConsoleSessionLauncher::Worker() { LaunchProcessInSession(session_id_, input_channel_id_, output_channel_id_); } void ConsoleSessionLauncher::OnStop() { // Nothing } void ConsoleSessionLauncher::ExecuteService(uint32_t session_id, const std::wstring& input_channel_id, const std::wstring& output_channel_id) { session_id_ = session_id; input_channel_id_ = input_channel_id; output_channel_id_ = output_channel_id; Run(); ServiceManager(ServiceName()).Remove(); } static bool GetSessionIdForCurrentProcess(DWORD& session_id) { typedef BOOL(WINAPI *ProcessIdToSessionIdFn)(DWORD, DWORD*); HMODULE kernel32_module = GetModuleHandleW(L"kernel32.dll"); if (!kernel32_module) { LOG(ERROR) << "Failed to get kernel32.dll module handle"; return false; } ProcessIdToSessionIdFn process_id_to_session_id = reinterpret_cast<ProcessIdToSessionIdFn>( GetProcAddress(kernel32_module, "ProcessIdToSessionId")); if (!process_id_to_session_id) { LOG(ERROR) << "Failed to load ProcessIdToSessionId function"; return false; } if (!process_id_to_session_id(GetCurrentProcessId(), &session_id)) { LOG(ERROR) << "ProcessIdToSessionId() failed: " << GetLastSystemErrorString(); return false; } return true; } // static bool ConsoleSessionLauncher::LaunchSession(uint32_t session_id, const std::wstring& input_channel_id, const std::wstring& output_channel_id) { std::wstring command_line; if (!GetPathW(PathKey::FILE_EXE, command_line)) return false; command_line.append(L" --input_channel_id="); command_line.append(input_channel_id); command_line.append(L" --output_channel_id="); command_line.append(output_channel_id); if (!IsCallerHasAdminRights()) { command_line.append(L" --run_mode="); command_line.append(kDesktopSessionSwitch); ScopedHandle token; if (!CopyProcessToken(TOKEN_ALL_ACCESS, token)) return false; return CreateProcessWithToken(token, command_line); } else { DWORD current_process_session_id; if (!GetSessionIdForCurrentProcess(current_process_session_id)) return false; // If the current process is started not in session 0 (not as a service), // then we create a service to start the process in the required session. if (!IsWindowsVistaOrGreater() || current_process_session_id != 0) { std::wstring service_id = ServiceManager::GenerateUniqueServiceId(); std::wstring unique_short_name = ServiceManager::CreateUniqueServiceName(kServiceShortName, service_id); std::wstring unique_full_name = ServiceManager::CreateUniqueServiceName(kServiceFullName, service_id); command_line.append(L" --run_mode="); command_line.append(kDesktopSessionLauncherSwitch); command_line.append(L" --session_id="); command_line.append(std::to_wstring(session_id)); command_line.append(L" --service_id="); command_line.append(service_id); // Install the service in the system. ServiceManager manager(ServiceManager::Create(command_line, unique_full_name, unique_short_name)); // If the service was not installed. if (!manager.IsValid()) return false; return manager.Start(); } else // The code is executed from the service. { // Start the process directly. return LaunchProcessInSession(session_id, input_channel_id, output_channel_id); } } } } // namespace aspia <commit_msg>- Using IsRunningAsService function<commit_after>// // PROJECT: Aspia Remote Desktop // FILE: host/console_session_launcher.cc // LICENSE: See top-level directory // PROGRAMMERS: Dmitry Chapyshev ([email protected]) // #include "host/console_session_launcher.h" #include <userenv.h> #include <wtsapi32.h> #include <string> #include "base/version_helpers.h" #include "base/process_helpers.h" #include "base/service_manager.h" #include "base/scoped_object.h" #include "base/scoped_wts_memory.h" #include "base/scoped_impersonator.h" #include "base/object_watcher.h" #include "base/unicode.h" #include "base/path.h" #include "base/process.h" #include "base/logging.h" namespace aspia { static const WCHAR kServiceShortName[] = L"aspia-desktop-session-launcher"; static const WCHAR kServiceFullName[] = L"Aspia Desktop Session Launcher"; // Name of the default session desktop. static WCHAR kDefaultDesktopName[] = L"winsta0\\default"; ConsoleSessionLauncher::ConsoleSessionLauncher(const std::wstring& service_id) : Service(ServiceManager::CreateUniqueServiceName(kServiceShortName, service_id)) { // Nothing } static bool CopyProcessToken(DWORD desired_access, ScopedHandle& token_out) { ScopedHandle process_token; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | desired_access, process_token.Recieve())) { LOG(ERROR) << "OpenProcessToken() failed: " << GetLastSystemErrorString(); return false; } if (!DuplicateTokenEx(process_token, desired_access, nullptr, SecurityImpersonation, TokenPrimary, token_out.Recieve())) { LOG(ERROR) << "DuplicateTokenEx() failed: " << GetLastSystemErrorString(); return false; } return true; } // Creates a copy of the current process with SE_TCB_NAME privilege enabled. static bool CreatePrivilegedToken(ScopedHandle& token_out) { ScopedHandle privileged_token; DWORD desired_access = TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE | TOKEN_DUPLICATE | TOKEN_QUERY; if (!CopyProcessToken(desired_access, privileged_token)) return false; // Get the LUID for the SE_TCB_NAME privilege. TOKEN_PRIVILEGES state; state.PrivilegeCount = 1; state.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!LookupPrivilegeValueW(nullptr, SE_TCB_NAME, &state.Privileges[0].Luid)) { LOG(ERROR) << "LookupPrivilegeValueW() failed: " << GetLastSystemErrorString(); return false; } // Enable the SE_TCB_NAME privilege. if (!AdjustTokenPrivileges(privileged_token, FALSE, &state, 0, nullptr, 0)) { LOG(ERROR) << "AdjustTokenPrivileges() failed: " << GetLastSystemErrorString(); return false; } token_out.Reset(privileged_token.Release()); return true; } // Creates a copy of the current process token for the given |session_id| so // it can be used to launch a process in that session. static bool CreateSessionToken(uint32_t session_id, ScopedHandle& token_out) { ScopedHandle session_token; DWORD desired_access = TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY; if (!CopyProcessToken(desired_access, session_token)) return false; ScopedHandle privileged_token; if (!CreatePrivilegedToken(privileged_token)) return false; { ScopedImpersonator impersonator; if (!impersonator.ImpersonateLoggedOnUser(privileged_token)) return false; // Change the session ID of the token. DWORD new_session_id = session_id; if (!SetTokenInformation(session_token, TokenSessionId, &new_session_id, sizeof(new_session_id))) { LOG(ERROR) << "SetTokenInformation() failed: " << GetLastSystemErrorString(); return false; } } token_out.Reset(session_token.Release()); return true; } static bool CreateProcessWithToken(HANDLE user_token, const std::wstring& command_line) { PROCESS_INFORMATION process_info = { 0 }; STARTUPINFOW startup_info = { 0 }; startup_info.cb = sizeof(startup_info); startup_info.lpDesktop = kDefaultDesktopName; if (!CreateProcessAsUserW(user_token, nullptr, const_cast<LPWSTR>(command_line.c_str()), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup_info, &process_info)) { LOG(ERROR) << "CreateProcessAsUserW() failed: " << GetLastSystemErrorString(); return false; } CloseHandle(process_info.hThread); CloseHandle(process_info.hProcess); return true; } static bool LaunchProcessInSession(uint32_t session_id, const std::wstring& input_channel_id, const std::wstring& output_channel_id) { std::wstring command_line; if (!GetPathW(PathKey::FILE_EXE, command_line)) return false; command_line.append(L" --run_mode="); command_line.append(kDesktopSessionSwitch); command_line.append(L" --input_channel_id="); command_line.append(input_channel_id); command_line.append(L" --output_channel_id="); command_line.append(output_channel_id); ScopedHandle session_token; if (!CreateSessionToken(session_id, session_token)) return false; return CreateProcessWithToken(session_token, command_line); } void ConsoleSessionLauncher::Worker() { LaunchProcessInSession(session_id_, input_channel_id_, output_channel_id_); } void ConsoleSessionLauncher::OnStop() { // Nothing } void ConsoleSessionLauncher::ExecuteService(uint32_t session_id, const std::wstring& input_channel_id, const std::wstring& output_channel_id) { session_id_ = session_id; input_channel_id_ = input_channel_id; output_channel_id_ = output_channel_id; Run(); ServiceManager(ServiceName()).Remove(); } // static bool ConsoleSessionLauncher::LaunchSession(uint32_t session_id, const std::wstring& input_channel_id, const std::wstring& output_channel_id) { std::wstring command_line; if (!GetPathW(PathKey::FILE_EXE, command_line)) return false; command_line.append(L" --input_channel_id="); command_line.append(input_channel_id); command_line.append(L" --output_channel_id="); command_line.append(output_channel_id); if (!IsCallerHasAdminRights()) { command_line.append(L" --run_mode="); command_line.append(kDesktopSessionSwitch); ScopedHandle token; if (!CopyProcessToken(TOKEN_ALL_ACCESS, token)) return false; return CreateProcessWithToken(token, command_line); } else { if (!IsRunningAsService()) { std::wstring service_id = ServiceManager::GenerateUniqueServiceId(); std::wstring unique_short_name = ServiceManager::CreateUniqueServiceName(kServiceShortName, service_id); std::wstring unique_full_name = ServiceManager::CreateUniqueServiceName(kServiceFullName, service_id); command_line.append(L" --run_mode="); command_line.append(kDesktopSessionLauncherSwitch); command_line.append(L" --session_id="); command_line.append(std::to_wstring(session_id)); command_line.append(L" --service_id="); command_line.append(service_id); // Install the service in the system. ServiceManager manager(ServiceManager::Create(command_line, unique_full_name, unique_short_name)); // If the service was not installed. if (!manager.IsValid()) return false; return manager.Start(); } else // The code is executed from the service. { // Start the process directly. return LaunchProcessInSession(session_id, input_channel_id, output_channel_id); } } } } // namespace aspia <|endoftext|>
<commit_before>#include "http2/adapter/nghttp2_session.h" #include "common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { NgHttp2Session::NgHttp2Session(Perspective perspective, nghttp2_session_callbacks_unique_ptr callbacks, const nghttp2_option* options, void* userdata) : session_(MakeSessionPtr(nullptr)), perspective_(perspective) { nghttp2_session* session; switch (perspective_) { case Perspective::kClient: nghttp2_session_client_new2(&session, callbacks.get(), userdata, options); break; case Perspective::kServer: nghttp2_session_server_new2(&session, callbacks.get(), userdata, options); break; } session_ = MakeSessionPtr(session); } NgHttp2Session::~NgHttp2Session() { // Can't invoke want_read() or want_write(), as they are virtual methods. const bool pending_reads = nghttp2_session_want_read(session_.get()) != 0; const bool pending_writes = nghttp2_session_want_write(session_.get()) != 0; QUICHE_LOG_IF(WARNING, pending_reads || pending_writes) << "Shutting down connection with pending reads: " << pending_reads << " or pending writes: " << pending_writes; } int64_t NgHttp2Session::ProcessBytes(absl::string_view bytes) { return nghttp2_session_mem_recv( session_.get(), reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size()); } int NgHttp2Session::Consume(Http2StreamId stream_id, size_t num_bytes) { return nghttp2_session_consume(session_.get(), stream_id, num_bytes); } bool NgHttp2Session::want_read() const { return nghttp2_session_want_read(session_.get()) != 0; } bool NgHttp2Session::want_write() const { return nghttp2_session_want_write(session_.get()) != 0; } int NgHttp2Session::GetRemoteWindowSize() const { return nghttp2_session_get_remote_window_size(session_.get()); } } // namespace adapter } // namespace http2 <commit_msg>Moves another noisy log to QUICHE_VLOG(1).<commit_after>#include "http2/adapter/nghttp2_session.h" #include "common/platform/api/quiche_logging.h" namespace http2 { namespace adapter { NgHttp2Session::NgHttp2Session(Perspective perspective, nghttp2_session_callbacks_unique_ptr callbacks, const nghttp2_option* options, void* userdata) : session_(MakeSessionPtr(nullptr)), perspective_(perspective) { nghttp2_session* session; switch (perspective_) { case Perspective::kClient: nghttp2_session_client_new2(&session, callbacks.get(), userdata, options); break; case Perspective::kServer: nghttp2_session_server_new2(&session, callbacks.get(), userdata, options); break; } session_ = MakeSessionPtr(session); } NgHttp2Session::~NgHttp2Session() { // Can't invoke want_read() or want_write(), as they are virtual methods. const bool pending_reads = nghttp2_session_want_read(session_.get()) != 0; const bool pending_writes = nghttp2_session_want_write(session_.get()) != 0; if (pending_reads || pending_writes) { QUICHE_VLOG(1) << "Shutting down connection with pending reads: " << pending_reads << " or pending writes: " << pending_writes; } } int64_t NgHttp2Session::ProcessBytes(absl::string_view bytes) { return nghttp2_session_mem_recv( session_.get(), reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size()); } int NgHttp2Session::Consume(Http2StreamId stream_id, size_t num_bytes) { return nghttp2_session_consume(session_.get(), stream_id, num_bytes); } bool NgHttp2Session::want_read() const { return nghttp2_session_want_read(session_.get()) != 0; } bool NgHttp2Session::want_write() const { return nghttp2_session_want_write(session_.get()) != 0; } int NgHttp2Session::GetRemoteWindowSize() const { return nghttp2_session_get_remote_window_size(session_.get()); } } // namespace adapter } // namespace http2 <|endoftext|>
<commit_before>/** * \file dcs/testbed/rain/sensors.hpp * * \brief Sensor for RAIN-driven applications. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright (C) 2012 Marco Guazzone ([email protected]) * [Distributed Computing System (DCS) Group, * Computer Science Institute, * Department of Science and Technological Innovation, * University of Piemonte Orientale, * Alessandria (Italy)] * * This file is part of dcsxx-testbed (below referred to as "this program"). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DCS_TESTBED_RAIN_SENSORS_HPP #define DCS_TESTBED_RAIN_SENSORS_HPP #include <cctype> #include <cstddef> #include <ctime> #include <dcs/debug.hpp> #include <dcs/testbed/base_sensor.hpp> #include <fstream> #include <ios> #include <string> #include <vector> namespace dcs { namespace testbed { namespace rain { template <typename TraitsT> class response_time_sensor: public base_sensor<TraitsT> { private: typedef base_sensor<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::observation_type observation_type; public: response_time_sensor(::std::string const& metrics_file_path) : metrics_file_(metrics_file_path), fpos_(0), new_data_(false) { } private: void do_sense() { // Available fields in a row (each field is separated by one or more white-spaces): // - '[' <generated-during> ']' // - <timestamp> // - <operation name> // - <response time> // - '[' <operation request> ']' // - <total response time> // - <number of observations> const ::std::size_t timestamp_field(2); const ::std::size_t operation_field(3); const ::std::size_t response_time_field(4); //const ::std::size_t max_open_trials(50); // reset last sensing new_data_ = false; obs_.clear(); if (!ifs_.good()) { // Found EOF. Two possible reasons: // 1. There is no data to read // 2. There is new data but we need to refresh input buffers // Investigate... ifs_.close(); ifs_.open(metrics_file_.c_str(), ::std::ios_base::ate); if (ifs_.good()) { ifs_.sync(); ::std::ifstream::pos_type new_fpos(ifs_.tellg()); DCS_DEBUG_TRACE("REOPENED (good) -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_) << " - IN_AVAIL: " << ifs_.rdbuf()->in_avail()); if (fpos_ != new_fpos) { // The file has changed, we are in case #2 // Restart to read file from the old position ifs_.seekg(fpos_); new_data_ = true; DCS_DEBUG_TRACE("SOUGHT IFS STREAM -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); } } } // Collect all available metrics entries while (ifs_.good() && new_data_) { fpos_ = ifs_.tellg(); ::std::string line; ::std::getline(ifs_, line); DCS_DEBUG_TRACE("IFS STREAM -- LINE: " << line << " - POS: " << fpos_ << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); const ::std::size_t n(line.size()); if (!ifs_.good() || n == 0) { continue; } ::std::time_t obs_ts(0); // timestamp (in secs from Epoch) ::std::string obs_op; // Operation label long obs_rtns(0); // response time (in ns) ::std::size_t field(0); for (::std::size_t pos = 0; pos < n; ++pos) { // eat all heading space for (; pos < n && ::std::isspace(line[pos]); ++pos) { ; } if (pos < n) { ++field; switch (field) { case timestamp_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isdigit(line[pos2]); ++pos2) { ; } ::std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_ts; DCS_DEBUG_TRACE("Timestamp: " << obs_ts); pos = pos2; break; } case operation_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isalpha(line[pos2]); ++pos2) { ; } obs_op = line.substr(pos, pos2-pos); DCS_DEBUG_TRACE("Operation: " << obs_op); pos = pos2; break; } case response_time_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isdigit(line[pos2]); ++pos2) { ; } ::std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_rtns; DCS_DEBUG_TRACE("Response Time (nsecs): " << obs_rtns); pos = pos2; break; } default: // skip these fields for (; pos < n && !::std::isspace(line[pos]); ++pos) { ; } break; } } } obs_.push_back(observation_type(obs_ts, obs_op, obs_rtns*1.0e-6)); } } private: void do_reset() { if (ifs_.is_open()) { ifs_.close(); } fpos_ = 0; new_data_ = false; obs_.clear(); } private: bool do_has_observations() const { return obs_.size() > 0; } private: ::std::vector<observation_type> do_observations() const { return obs_; } private: ::std::string metrics_file_; private: ::std::ifstream ifs_; private: ::std::ifstream::pos_type fpos_; private: bool new_data_; private: ::std::vector<observation_type> obs_; }; // response_time_sensor }}} // Namespace dcs::testbed::rain #endif // DCS_TESTBED_RAIN_SENSORS_HPP <commit_msg>(new:minor) In dcs::testbed::rain::response_time_sensor class, added some debugging messages.<commit_after>/** * \file dcs/testbed/rain/sensors.hpp * * \brief Sensor for RAIN-driven applications. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright (C) 2012 Marco Guazzone ([email protected]) * [Distributed Computing System (DCS) Group, * Computer Science Institute, * Department of Science and Technological Innovation, * University of Piemonte Orientale, * Alessandria (Italy)] * * This file is part of dcsxx-testbed (below referred to as "this program"). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DCS_TESTBED_RAIN_SENSORS_HPP #define DCS_TESTBED_RAIN_SENSORS_HPP #include <cctype> #include <cstddef> #include <ctime> #include <dcs/debug.hpp> #include <dcs/testbed/base_sensor.hpp> #include <fstream> #include <ios> #include <string> #include <vector> namespace dcs { namespace testbed { namespace rain { template <typename TraitsT> class response_time_sensor: public base_sensor<TraitsT> { private: typedef base_sensor<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::observation_type observation_type; public: response_time_sensor(::std::string const& metrics_file_path) : metrics_file_(metrics_file_path), fpos_(0), new_data_(false) { } private: void do_sense() { DCS_DEBUG_TRACE("BEGIN Do Sense"); // Available fields in a row (each field is separated by one or more white-spaces): // - '[' <generated-during> ']' // - <timestamp> // - <operation name> // - <response time> // - '[' <operation request> ']' // - <total response time> // - <number of observations> const ::std::size_t timestamp_field(2); const ::std::size_t operation_field(3); const ::std::size_t response_time_field(4); //const ::std::size_t max_open_trials(50); // reset last sensing new_data_ = false; obs_.clear(); if (!ifs_.good()) { // Found EOF. Two possible reasons: // 1. There is no data to read // 2. There is new data but we need to refresh input buffers // Investigate... ifs_.close(); ifs_.open(metrics_file_.c_str(), ::std::ios_base::ate); if (ifs_.good()) { ifs_.sync(); ::std::ifstream::pos_type new_fpos(ifs_.tellg()); DCS_DEBUG_TRACE("REOPENED (good) -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_) << " - IN_AVAIL: " << ifs_.rdbuf()->in_avail()); if (fpos_ != new_fpos) { // The file has changed, we are in case #2 // Restart to read file from the old position ifs_.seekg(fpos_); new_data_ = true; DCS_DEBUG_TRACE("SOUGHT IFS STREAM -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); } } } // Collect all available metrics entries while (ifs_.good() && new_data_) { fpos_ = ifs_.tellg(); ::std::string line; ::std::getline(ifs_, line); DCS_DEBUG_TRACE("IFS STREAM -- LINE: " << line << " - POS: " << fpos_ << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); const ::std::size_t n(line.size()); if (!ifs_.good() || n == 0) { continue; } ::std::time_t obs_ts(0); // timestamp (in secs from Epoch) ::std::string obs_op; // Operation label long obs_rtns(0); // response time (in ns) ::std::size_t field(0); for (::std::size_t pos = 0; pos < n; ++pos) { // eat all heading space for (; pos < n && ::std::isspace(line[pos]); ++pos) { ; } if (pos < n) { ++field; switch (field) { case timestamp_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isdigit(line[pos2]); ++pos2) { ; } ::std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_ts; DCS_DEBUG_TRACE("Timestamp: " << obs_ts); pos = pos2; break; } case operation_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isalpha(line[pos2]); ++pos2) { ; } obs_op = line.substr(pos, pos2-pos); DCS_DEBUG_TRACE("Operation: " << obs_op); pos = pos2; break; } case response_time_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isdigit(line[pos2]); ++pos2) { ; } ::std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_rtns; DCS_DEBUG_TRACE("Response Time (nsecs): " << obs_rtns); pos = pos2; break; } default: // skip these fields for (; pos < n && !::std::isspace(line[pos]); ++pos) { ; } break; } } } obs_.push_back(observation_type(obs_ts, obs_op, obs_rtns*1.0e-6)); } DCS_DEBUG_TRACE("END Do Sense"); } private: void do_reset() { if (ifs_.is_open()) { ifs_.close(); } fpos_ = 0; new_data_ = false; obs_.clear(); } private: bool do_has_observations() const { return obs_.size() > 0; } private: ::std::vector<observation_type> do_observations() const { return obs_; } private: ::std::string metrics_file_; private: ::std::ifstream ifs_; private: ::std::ifstream::pos_type fpos_; private: bool new_data_; private: ::std::vector<observation_type> obs_; }; // response_time_sensor }}} // Namespace dcs::testbed::rain #endif // DCS_TESTBED_RAIN_SENSORS_HPP <|endoftext|>
<commit_before>/** * \file dcs/testbed/rain/sensors.hpp * * \brief Sensor for RAIN-driven applications. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright 2012 Marco Guazzone ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DCS_TESTBED_RAIN_SENSORS_HPP #define DCS_TESTBED_RAIN_SENSORS_HPP #include <cctype> #include <cstddef> #include <ctime> #include <dcs/debug.hpp> #include <dcs/testbed/base_sensor.hpp> #include <fstream> #include <ios> #include <string> #include <vector> namespace dcs { namespace testbed { namespace rain { template <typename TraitsT> class response_time_sensor: public base_sensor<TraitsT> { private: typedef base_sensor<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::observation_type observation_type; public: response_time_sensor(::std::string const& metrics_file_path) : metrics_file_(metrics_file_path), fpos_(0) // new_data_(false) { } private: void do_sense() { DCS_DEBUG_TRACE("BEGIN Do Sense"); // Available fields in a row (each field is separated by one or more white-spaces): // - '[' <generated-during> ']' // - <timestamp> // - <operation name> // - <response time> // - '[' <operation request> ']' // - <total response time> // - <number of observations> const ::std::size_t timestamp_field(2); const ::std::size_t operation_field(3); const ::std::size_t response_time_field(4); //const ::std::size_t max_open_trials(50); // reset last sensing obs_.clear(); if (!ifs_.good() || !ifs_.is_open()) { // Found EOF. Two possible reasons: // 1. There is no data to read // 2. There is new data but we need to refresh input buffers // Investigate... if (ifs_.is_open()) { ifs_.close(); } ifs_.open(metrics_file_.c_str(), ::std::ios_base::ate); if (ifs_.good()) { ifs_.sync(); ::std::ifstream::pos_type new_fpos(ifs_.tellg()); //DCS_DEBUG_TRACE("REOPENED (good) -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_) << " - IN_AVAIL: " << ifs_.rdbuf()->in_avail()); if (fpos_ != new_fpos) { // The file has changed, we are in case #2 // Restart to read file from the old position ifs_.seekg(fpos_); // new_data_ = true; //DCS_DEBUG_TRACE("SOUGHT IFS STREAM -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); } else { ifs_.close(); } } } // Collect all available metrics entries while (ifs_.good() && ifs_.is_open()) { fpos_ = ifs_.tellg(); ::std::string line; ::std::getline(ifs_, line); //DCS_DEBUG_TRACE("IFS STREAM -- LINE: " << line << " - POS: " << fpos_ << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); const ::std::size_t n(line.size()); if (!ifs_.good() || n == 0) { continue; } ::std::time_t obs_ts(0); // timestamp (in secs from Epoch) ::std::string obs_op; // Operation label long obs_rtns(0); // response time (in ns) ::std::size_t field(0); for (::std::size_t pos = 0; pos < n; ++pos) { // eat all heading space for (; pos < n && ::std::isspace(line[pos]); ++pos) { ; } if (pos < n) { ++field; switch (field) { case timestamp_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isdigit(line[pos2]); ++pos2) { ; } ::std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_ts; //DCS_DEBUG_TRACE("Timestamp: " << obs_ts); pos = pos2; break; } case operation_field: { ::std::size_t pos2(pos); //for (; pos2 < n && ::std::isalpha(line[pos2]); ++pos2) for (; pos2 < n && !::std::isspace(line[pos2]); ++pos2) { ; } obs_op = line.substr(pos, pos2-pos); //DCS_DEBUG_TRACE("Operation: " << obs_op); pos = pos2; break; } case response_time_field: { ::std::size_t pos2(pos); for (; pos2 < n && ::std::isdigit(line[pos2]); ++pos2) { ; } ::std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_rtns; //DCS_DEBUG_TRACE("Response Time (nsecs): " << obs_rtns); pos = pos2; break; } default: // skip these fields for (; pos < n && !::std::isspace(line[pos]); ++pos) { ; } break; } } } obs_.push_back(observation_type(obs_ts, obs_op, obs_rtns*1.0e-9)); } DCS_DEBUG_TRACE("END Do Sense"); } private: void do_reset() { if (ifs_.is_open()) { ifs_.close(); } fpos_ = 0; //new_data_ = false; obs_.clear(); } private: bool do_has_observations() const { return obs_.size() > 0; } private: ::std::vector<observation_type> do_observations() const { return obs_; } private: ::std::string metrics_file_; private: ::std::ifstream ifs_; private: ::std::ifstream::pos_type fpos_; // private: bool new_data_; private: ::std::vector<observation_type> obs_; }; // response_time_sensor }}} // Namespace dcs::testbed::rain #endif // DCS_TESTBED_RAIN_SENSORS_HPP <commit_msg>(new) Added throughput sensor for the RAIN workload generator<commit_after>/** * \file dcs/testbed/rain/sensors.hpp * * \brief Sensor for RAIN-driven applications. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright 2012 Marco Guazzone ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef DCS_TESTBED_RAIN_SENSORS_HPP #define DCS_TESTBED_RAIN_SENSORS_HPP #include <cctype> #include <cstddef> #include <ctime> #include <dcs/debug.hpp> #include <dcs/testbed/base_sensor.hpp> #include <fstream> #include <ios> #include <string> #include <vector> namespace dcs { namespace testbed { namespace rain { template <typename TraitsT> class response_time_sensor: public base_sensor<TraitsT> { private: typedef base_sensor<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::observation_type observation_type; public: response_time_sensor(std::string const& metrics_file_path) : metrics_file_(metrics_file_path), fpos_(0) // new_data_(false) { } private: void do_sense() { DCS_DEBUG_TRACE("BEGIN Do Sense"); // Available fields in a row (each field is separated by one or more white-spaces): // - '[' <generated-during> ']' // - <finished-timestamp> // - <operation name> // - <response time> // - '[' <operation request> ']' // - <total response time> // - <number of observations> const std::size_t timestamp_field(2); const std::size_t operation_field(3); const std::size_t response_time_field(4); //const std::size_t max_open_trials(50); // reset last sensing obs_.clear(); if (!ifs_.good() || !ifs_.is_open()) { // Found EOF. Two possible reasons: // 1. There is no data to read // 2. There is new data but we need to refresh input buffers // Investigate... if (ifs_.is_open()) { ifs_.close(); } ifs_.open(metrics_file_.c_str(), std::ios_base::ate); if (ifs_.good()) { ifs_.sync(); std::ifstream::pos_type new_fpos(ifs_.tellg()); //DCS_DEBUG_TRACE("REOPENED (good) -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_) << " - IN_AVAIL: " << ifs_.rdbuf()->in_avail()); if (fpos_ != new_fpos) { // The file has changed, we are in case #2 // Restart to read file from the old position ifs_.seekg(fpos_); // new_data_ = true; //DCS_DEBUG_TRACE("SOUGHT IFS STREAM -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); } else { ifs_.close(); } } } // Collect all available metrics entries while (ifs_.good() && ifs_.is_open()) { fpos_ = ifs_.tellg(); std::string line; std::getline(ifs_, line); //DCS_DEBUG_TRACE("IFS STREAM -- LINE: " << line << " - POS: " << fpos_ << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); const std::size_t n(line.size()); if (!ifs_.good() || n == 0) { continue; } std::time_t obs_ts = 0; // timestamp (in secs from Epoch) std::string obs_op; // Operation label long obs_rtns = 0; // response time (in ns) std::size_t field = 0; for (std::size_t pos = 0; pos < n; ++pos) { // eat all heading space for (; pos < n && std::isspace(line[pos]); ++pos) { ; } if (pos < n) { ++field; switch (field) { case timestamp_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_ts; //DCS_DEBUG_TRACE("Timestamp: " << obs_ts); pos = pos2; break; } case operation_field: { std::size_t pos2(pos); //for (; pos2 < n && std::isalpha(line[pos2]); ++pos2) for (; pos2 < n && !std::isspace(line[pos2]); ++pos2) { ; } obs_op = line.substr(pos, pos2-pos); //DCS_DEBUG_TRACE("Operation: " << obs_op); pos = pos2; break; } case response_time_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_rtns; //DCS_DEBUG_TRACE("Response Time (nsecs): " << obs_rtns); pos = pos2; break; } default: // skip these fields for (; pos < n && !std::isspace(line[pos]); ++pos) { ; } break; } } } obs_.push_back(observation_type(obs_ts, obs_op, obs_rtns*1.0e-9)); } DCS_DEBUG_TRACE("END Do Sense"); } private: void do_reset() { if (ifs_.is_open()) { ifs_.close(); } fpos_ = 0; //new_data_ = false; obs_.clear(); } private: bool do_has_observations() const { return obs_.size() > 0; } private: std::vector<observation_type> do_observations() const { return obs_; } private: std::string metrics_file_; private: std::ifstream ifs_; private: std::ifstream::pos_type fpos_; // private: bool new_data_; private: std::vector<observation_type> obs_; }; // response_time_sensor template <typename TraitsT> class throughput_sensor: public base_sensor<TraitsT> { private: typedef base_sensor<TraitsT> base_type; public: typedef typename base_type::traits_type traits_type; public: typedef typename base_type::observation_type observation_type; public: throughput_sensor(std::string const& metrics_file_path) : metrics_file_(metrics_file_path), fpos_(0) // new_data_(false) { } private: void do_sense() { DCS_DEBUG_TRACE("BEGIN Do Sense"); // Available fields in a row (each field is separated by one or more white-spaces): // - '[' <generated-during> ']' // - <finished-timestamp> // - <operation name> // - <response time> // - '[' <operation request> ']' // - <total response time> // - <number of observations> const std::size_t timestamp_field(2); const std::size_t operation_field(3); const std::size_t num_observations_field(7); std::time_t first_obs_ts = -1; // timestamp (in secs from Epoch) of the first observation //const std::size_t max_open_trials(50); // reset last sensing obs_.clear(); if (!ifs_.good() || !ifs_.is_open()) { // Found EOF. Two possible reasons: // 1. There is no data to read // 2. There is new data but we need to refresh input buffers // Investigate... if (ifs_.is_open()) { ifs_.close(); } ifs_.open(metrics_file_.c_str(), std::ios_base::ate); if (ifs_.good()) { ifs_.sync(); std::ifstream::pos_type new_fpos(ifs_.tellg()); //DCS_DEBUG_TRACE("REOPENED (good) -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_) << " - IN_AVAIL: " << ifs_.rdbuf()->in_avail()); if (fpos_ != new_fpos) { // The file has changed, we are in case #2 // Restart to read file from the old position ifs_.seekg(fpos_); // new_data_ = true; //DCS_DEBUG_TRACE("SOUGHT IFS STREAM -- OLD POS: " << fpos_ << " - NEW POS: " << new_fpos << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); } else { ifs_.close(); } } } // Collect all available metrics entries while (ifs_.good() && ifs_.is_open()) { fpos_ = ifs_.tellg(); std::string line; std::getline(ifs_, line); //DCS_DEBUG_TRACE("IFS STREAM -- LINE: " << line << " - POS: " << fpos_ << " - GOOD: " << ifs_.good() << " - EOF: " << ifs_.eof() << " - FAIL: " << ifs_.fail() << " - BAD: " << ifs_.bad() << " - !(): " << !static_cast<bool>(ifs_)); const std::size_t n = line.size(); if (!ifs_.good() || n == 0) { continue; } std::time_t obs_ts = -1; // timestamp (in secs from Epoch) std::string obs_op; // Operation label unsigned long num_obs = 0; // number of observations std::size_t field = 0; for (std::size_t pos = 0; pos < n; ++pos) { // eat all heading space for (; pos < n && std::isspace(line[pos]); ++pos) { ; } if (pos < n) { ++field; switch (field) { case timestamp_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> obs_ts; //DCS_DEBUG_TRACE("Timestamp: " << obs_ts); pos = pos2; break; } case operation_field: { std::size_t pos2(pos); //for (; pos2 < n && std::isalpha(line[pos2]); ++pos2) for (; pos2 < n && !std::isspace(line[pos2]); ++pos2) { ; } obs_op = line.substr(pos, pos2-pos); //DCS_DEBUG_TRACE("Operation: " << obs_op); pos = pos2; break; } case num_observations_field: { std::size_t pos2(pos); for (; pos2 < n && std::isdigit(line[pos2]); ++pos2) { ; } std::istringstream iss(line.substr(pos, pos2-pos)); iss >> num_obs; //DCS_DEBUG_TRACE("Number of Observations: " << num_obs); pos = pos2; break; } default: // skip these fields for (; pos < n && !std::isspace(line[pos]); ++pos) { ; } break; } } } // Record this observation only if it is not the first observation if (first_obs_ts == -1) { first_obs_ts = obs_ts; } else { obs_.push_back(observation_type(obs_ts, obs_op, num_obs/static_cast<double>(obs_ts-first_obs_ts))); } } DCS_DEBUG_TRACE("END Do Sense"); } private: void do_reset() { if (ifs_.is_open()) { ifs_.close(); } fpos_ = 0; //new_data_ = false; obs_.clear(); } private: bool do_has_observations() const { return obs_.size() > 0; } private: std::vector<observation_type> do_observations() const { return obs_; } private: std::string metrics_file_; private: std::ifstream ifs_; private: std::ifstream::pos_type fpos_; // private: bool new_data_; private: std::vector<observation_type> obs_; }; // response_time_sensor }}} // Namespace dcs::testbed::rain #endif // DCS_TESTBED_RAIN_SENSORS_HPP <|endoftext|>
<commit_before>// Part of the apollo library -- Copyright (c) Christian Neumüller 2015 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #ifndef APOLLO_BUILTIN_TYPES_HPP_INCLUDED #define APOLLO_BUILTIN_TYPES_HPP_INCLUDED APOLLO_BUILTIN_TYPES_HPP_INCLUDED #include <apollo/config.hpp> #include <apollo/converters.hpp> #include <boost/assert.hpp> #include <cstdint> #include <limits> #include <string> namespace apollo { // Number converter // template<typename T> struct converter<T, typename std::enable_if< !std::is_enum<T>::value && detail::lua_type_id<T>::value == LUA_TNUMBER>::type >: converter_base<converter<T>> { private: static bool const is_integral = std::is_integral<T>::value; static bool const is_safe_integral = is_integral && sizeof(T) <= sizeof(lua_Integer) && // TODO heap allocated?! std::is_signed<T>::value == std::is_signed<lua_Integer>::value; public: static int push(lua_State* L, T n) { APOLLO_DETAIL_CONSTCOND_BEGIN if (is_integral && (is_safe_integral #if LUA_VERSION_NUM >= 503 // Not worth the effort on < 5.3. || fits_in_lua_integer(n) #endif // LUA_VERSION_NUM >= 503 )) { APOLLO_DETAIL_CONSTCOND_END lua_pushinteger(L, static_cast<lua_Integer>(n)); } else { lua_pushnumber(L, static_cast<lua_Number>(n)); } return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { if (lua_type(L, idx) == LUA_TNUMBER) { // Actual number. #if LUA_VERSION_NUM >= 503 if ((lua_isinteger(L, idx) ? true : false) == is_integral) // TODO make outer return 0; return 1; #else // LUA_VERSION_NUM >= 503 return 0; #endif // LUA_VERSION_NUM >= 503 / else } if (lua_isnumber(L, idx)) // String convertible to number. return 2; return no_conversion; } static T to(lua_State* L, int idx) { #if LUA_VERSION_NUM >= 503 APOLLO_DETAIL_CONSTCOND_BEGIN if (is_integral && lua_isinteger(L, idx)) return static_cast<T>(lua_tointeger(L, idx)); APOLLO_DETAIL_CONSTCOND_END #endif return static_cast<T>(lua_tonumber(L, idx)); } #if LUA_VERSION_NUM >= 502 // lua_tonumerx() is only available since 5.2 static T safe_to(lua_State* L, int idx) { # if LUA_VERSION_NUM >= 503 APOLLO_DETAIL_CONSTCOND_BEGIN if (is_integral && lua_isinteger(L, idx)) return static_cast<T>(lua_tointeger(L, idx)); APOLLO_DETAIL_CONSTCOND_END # endif int isnum; auto n = lua_tonumberx(L, idx, &isnum); if (!isnum) BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); return static_cast<T>(n); } #endif private: // Inspired by http://stackoverflow.com/a/17251989. static bool fits_in_lua_integer(T n) { // MSVC complains that n is unreferenced if it can determine the // result of the function at compile-time. (void)n; using llimits = std::numeric_limits<lua_Integer>; using tlimits = std::numeric_limits<T>; // C4309 'static_cast': truncation of constant value // Is emited for unsigned char and unsigned int here, but I have no // idea why -- after all min() in these cases is 0 for T. APOLLO_DETAIL_PUSHMSWARN(4309) auto const l_lo = static_cast<std::intmax_t>(llimits::min()); auto const t_lo = static_cast<std::intmax_t>(tlimits::min()); APOLLO_DETAIL_POPMSWARN auto const l_hi = static_cast<std::uintmax_t>(llimits::max()); auto const t_hi = static_cast<std::uintmax_t>(tlimits::max()); // C4309 again, but this time it might very well be that the // static_cast really truncates a value. However, in this case the // static_cast won't be evaluated because the first part of the || will // evaluate to true. APOLLO_DETAIL_PUSHMSWARN(4309) return (l_lo <= t_lo || n >= static_cast<T>(l_lo)) // Check underflow. && (l_hi >= t_hi || n <= static_cast<T>(l_hi)); // Check overflow. APOLLO_DETAIL_POPMSWARN } }; // Enum converter // template<typename T> struct converter<T, typename std::enable_if<std::is_enum<T>::value>::type >: converter_base<T> { static int push(lua_State* L, T n) { lua_pushinteger(L, static_cast<lua_Integer>(n)); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { if (lua_type(L, idx) == LUA_TNUMBER) return 1; return no_conversion; } static T to(lua_State* L, int idx) { return static_cast<T>(lua_tointeger(L, idx)); } }; // Boolean converter // template<> struct converter<bool>: converter_base<converter<bool>> { static int push(lua_State* L, bool b) { lua_pushboolean(L, static_cast<int>(b)); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { // Convert non-boolean values to bool only as a last resort. return lua_isboolean(L, idx) ? 0 : no_conversion - 1; } static bool to(lua_State* L, int idx) { // Avoid MSVC "performance warning" about int to bool conversion with // ternary operator. return lua_toboolean(L, idx) ? true : false; } static bool safe_to(lua_State* L, int idx) { return to(L, idx); } }; // void converter // template<> struct converter<void>: converter_base<converter<void>> { static unsigned n_conversion_steps(lua_State*, int) { return no_conversion - 1; } static void to(lua_State*, int) { } }; // String converter // namespace detail { inline void push_string(lua_State* L, char c) { lua_pushlstring(L, &c, 1); } template <std::size_t N> void push_string(lua_State* L, char const (&s)[N]) { // Don't count null termination. lua_pushlstring(L, s, N - (s[N - 1] == 0)); } // Need to make this a template too, so that the array overload is called in // the appropriate cases. Also can't make it const T* because otherwise the // call would be ambigous. template <typename T> inline void push_string(lua_State* L, T s) { using T2 = typename remove_cvr<T>::type; static_assert( std::is_same<T2, char*>::value || std::is_same<T2, char const*>::value, "push_string called with non-string"); lua_pushstring(L, s); } inline void push_string(lua_State* L, std::string const& s) { lua_pushlstring(L, s.c_str(), s.size()); } template <typename T> struct to_string { // char*, char const*, char[N] using type = char const*; static type to(lua_State* L, int idx) { return lua_tostring(L, idx); } static type safe_to(lua_State* L, int idx) { if (char const* s = lua_tostring(L, idx)) return s; BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); } }; template <> struct to_string<std::string> { using type = std::string; static type to(lua_State* L, int idx) { std::size_t len; char const* s = lua_tolstring(L, idx, &len); return std::string(s, len); } static type safe_to(lua_State* L, int idx) { std::size_t len; if (char const* s = lua_tolstring(L, idx, &len)) return std::string(s, len); BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); } }; template <> struct to_string<char> { using type = char; static type to(lua_State* L, int idx) { std::size_t len; char const* s = lua_tolstring(L, idx, &len); BOOST_ASSERT(len == 1); return s[0]; } static type safe_to(lua_State* L, int idx) { std::size_t len; char const* s = lua_tolstring(L, idx, &len); if (!s) BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); if (len != 1) { BOOST_THROW_EXCEPTION(to_cpp_conversion_error() << errinfo::msg("the string must be one byte long")); } return s[0]; } }; template <typename> struct string_conversion_steps { static unsigned get(lua_State* L, int idx) { switch(lua_type(L, idx)) { case LUA_TSTRING: return 0; case LUA_TNUMBER: return 1; default: return no_conversion; } BOOST_UNREACHABLE_RETURN(no_conversion); } }; template <> struct APOLLO_API string_conversion_steps<char> { static unsigned get(lua_State* L, int idx); }; } // namespace detail template <typename T> struct converter<T, typename std::enable_if< detail::lua_type_id<T>::value == LUA_TSTRING>::type >: converter_base<converter<T>, typename detail::to_string<T>::type> { static int push(lua_State* L, T const& s) { detail::push_string(L, s); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { return detail::string_conversion_steps<T>::get(L, idx); } static typename detail::to_string<T>::type to(lua_State* L, int idx) { return detail::to_string<T>::to(L, idx); } static typename detail::to_string<T>::type safe_to(lua_State* L, int idx) { return detail::to_string<T>::safe_to(L, idx); } }; template <> struct converter<void*>: converter_base<converter<void*>> { static int push(lua_State* L, void* p) { lua_pushlightuserdata(L, p); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { return lua_islightuserdata(L, idx) ? 0 : no_conversion; } static void* to(lua_State* L, int idx) { return lua_touserdata(L, idx); } static void* safe_to(lua_State* L, int idx) { if (void* ud = lua_touserdata(L, idx)) return ud; BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); } }; } // namepace apollo #endif // APOLLO_CONVERTERS_HPP_INCLUDED <commit_msg>Move #ifdef in number converter to a nicer place.<commit_after>// Part of the apollo library -- Copyright (c) Christian Neumüller 2015 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #ifndef APOLLO_BUILTIN_TYPES_HPP_INCLUDED #define APOLLO_BUILTIN_TYPES_HPP_INCLUDED APOLLO_BUILTIN_TYPES_HPP_INCLUDED #include <apollo/config.hpp> #include <apollo/converters.hpp> #include <boost/assert.hpp> #include <cstdint> #include <limits> #include <string> namespace apollo { // Number converter // template<typename T> struct converter<T, typename std::enable_if< !std::is_enum<T>::value && detail::lua_type_id<T>::value == LUA_TNUMBER>::type >: converter_base<converter<T>> { private: static bool const is_integral = std::is_integral<T>::value; static bool const is_safe_integral = is_integral && sizeof(T) <= sizeof(lua_Integer) && // TODO heap allocated?! std::is_signed<T>::value == std::is_signed<lua_Integer>::value; public: static int push(lua_State* L, T n) { APOLLO_DETAIL_CONSTCOND_BEGIN if (is_integral && (is_safe_integral || fits_in_lua_integer(n))) { APOLLO_DETAIL_CONSTCOND_END lua_pushinteger(L, static_cast<lua_Integer>(n)); } else { lua_pushnumber(L, static_cast<lua_Number>(n)); } return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { if (lua_type(L, idx) == LUA_TNUMBER) { // Actual number. #if LUA_VERSION_NUM >= 503 if ((lua_isinteger(L, idx) ? true : false) == is_integral) // TODO make outer return 0; return 1; #else // LUA_VERSION_NUM >= 503 return 0; #endif // LUA_VERSION_NUM >= 503 / else } if (lua_isnumber(L, idx)) // String convertible to number. return 2; return no_conversion; } static T to(lua_State* L, int idx) { #if LUA_VERSION_NUM >= 503 APOLLO_DETAIL_CONSTCOND_BEGIN if (is_integral && lua_isinteger(L, idx)) return static_cast<T>(lua_tointeger(L, idx)); APOLLO_DETAIL_CONSTCOND_END #endif return static_cast<T>(lua_tonumber(L, idx)); } #if LUA_VERSION_NUM >= 502 // lua_tonumerx() is only available since 5.2 static T safe_to(lua_State* L, int idx) { # if LUA_VERSION_NUM >= 503 APOLLO_DETAIL_CONSTCOND_BEGIN if (is_integral && lua_isinteger(L, idx)) return static_cast<T>(lua_tointeger(L, idx)); APOLLO_DETAIL_CONSTCOND_END # endif int isnum; auto n = lua_tonumberx(L, idx, &isnum); if (!isnum) BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); return static_cast<T>(n); } #endif private: // Inspired by http://stackoverflow.com/a/17251989. static bool fits_in_lua_integer(T n) { #if LUA_VERSION_NUM >= 503 // MSVC complains that n is unreferenced if it can determine the // result of the function at compile-time. (void)n; using llimits = std::numeric_limits<lua_Integer>; using tlimits = std::numeric_limits<T>; // C4309 'static_cast': truncation of constant value // Is emited for unsigned char and unsigned int here, but I have no // idea why -- after all min() in these cases is 0 for T. APOLLO_DETAIL_PUSHMSWARN(4309) auto const l_lo = static_cast<std::intmax_t>(llimits::min()); auto const t_lo = static_cast<std::intmax_t>(tlimits::min()); APOLLO_DETAIL_POPMSWARN auto const l_hi = static_cast<std::uintmax_t>(llimits::max()); auto const t_hi = static_cast<std::uintmax_t>(tlimits::max()); // C4309 again, but this time it might very well be that the // static_cast really truncates a value. However, in this case the // static_cast won't be evaluated because the first part of the || will // evaluate to true. APOLLO_DETAIL_PUSHMSWARN(4309) return (l_lo <= t_lo || n >= static_cast<T>(l_lo)) // Check underflow. && (l_hi >= t_hi || n <= static_cast<T>(l_hi)); // Check overflow. APOLLO_DETAIL_POPMSWARN #else (void)n; return false; // Not worth the effort on Lua w/o integer support. #endif } }; // Enum converter // template<typename T> struct converter<T, typename std::enable_if<std::is_enum<T>::value>::type >: converter_base<T> { static int push(lua_State* L, T n) { lua_pushinteger(L, static_cast<lua_Integer>(n)); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { if (lua_type(L, idx) == LUA_TNUMBER) return 1; return no_conversion; } static T to(lua_State* L, int idx) { return static_cast<T>(lua_tointeger(L, idx)); } }; // Boolean converter // template<> struct converter<bool>: converter_base<converter<bool>> { static int push(lua_State* L, bool b) { lua_pushboolean(L, static_cast<int>(b)); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { // Convert non-boolean values to bool only as a last resort. return lua_isboolean(L, idx) ? 0 : no_conversion - 1; } static bool to(lua_State* L, int idx) { // Avoid MSVC "performance warning" about int to bool conversion with // ternary operator. return lua_toboolean(L, idx) ? true : false; } static bool safe_to(lua_State* L, int idx) { return to(L, idx); } }; // void converter // template<> struct converter<void>: converter_base<converter<void>> { static unsigned n_conversion_steps(lua_State*, int) { return no_conversion - 1; } static void to(lua_State*, int) { } }; // String converter // namespace detail { inline void push_string(lua_State* L, char c) { lua_pushlstring(L, &c, 1); } template <std::size_t N> void push_string(lua_State* L, char const (&s)[N]) { // Don't count null termination. lua_pushlstring(L, s, N - (s[N - 1] == 0)); } // Need to make this a template too, so that the array overload is called in // the appropriate cases. Also can't make it const T* because otherwise the // call would be ambigous. template <typename T> inline void push_string(lua_State* L, T s) { using T2 = typename remove_cvr<T>::type; static_assert( std::is_same<T2, char*>::value || std::is_same<T2, char const*>::value, "push_string called with non-string"); lua_pushstring(L, s); } inline void push_string(lua_State* L, std::string const& s) { lua_pushlstring(L, s.c_str(), s.size()); } template <typename T> struct to_string { // char*, char const*, char[N] using type = char const*; static type to(lua_State* L, int idx) { return lua_tostring(L, idx); } static type safe_to(lua_State* L, int idx) { if (char const* s = lua_tostring(L, idx)) return s; BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); } }; template <> struct to_string<std::string> { using type = std::string; static type to(lua_State* L, int idx) { std::size_t len; char const* s = lua_tolstring(L, idx, &len); return std::string(s, len); } static type safe_to(lua_State* L, int idx) { std::size_t len; if (char const* s = lua_tolstring(L, idx, &len)) return std::string(s, len); BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); } }; template <> struct to_string<char> { using type = char; static type to(lua_State* L, int idx) { std::size_t len; char const* s = lua_tolstring(L, idx, &len); BOOST_ASSERT(len == 1); return s[0]; } static type safe_to(lua_State* L, int idx) { std::size_t len; char const* s = lua_tolstring(L, idx, &len); if (!s) BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); if (len != 1) { BOOST_THROW_EXCEPTION(to_cpp_conversion_error() << errinfo::msg("the string must be one byte long")); } return s[0]; } }; template <typename> struct string_conversion_steps { static unsigned get(lua_State* L, int idx) { switch(lua_type(L, idx)) { case LUA_TSTRING: return 0; case LUA_TNUMBER: return 1; default: return no_conversion; } BOOST_UNREACHABLE_RETURN(no_conversion); } }; template <> struct APOLLO_API string_conversion_steps<char> { static unsigned get(lua_State* L, int idx); }; } // namespace detail template <typename T> struct converter<T, typename std::enable_if< detail::lua_type_id<T>::value == LUA_TSTRING>::type >: converter_base<converter<T>, typename detail::to_string<T>::type> { static int push(lua_State* L, T const& s) { detail::push_string(L, s); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { return detail::string_conversion_steps<T>::get(L, idx); } static typename detail::to_string<T>::type to(lua_State* L, int idx) { return detail::to_string<T>::to(L, idx); } static typename detail::to_string<T>::type safe_to(lua_State* L, int idx) { return detail::to_string<T>::safe_to(L, idx); } }; template <> struct converter<void*>: converter_base<converter<void*>> { static int push(lua_State* L, void* p) { lua_pushlightuserdata(L, p); return 1; } static unsigned n_conversion_steps(lua_State* L, int idx) { return lua_islightuserdata(L, idx) ? 0 : no_conversion; } static void* to(lua_State* L, int idx) { return lua_touserdata(L, idx); } static void* safe_to(lua_State* L, int idx) { if (void* ud = lua_touserdata(L, idx)) return ud; BOOST_THROW_EXCEPTION(to_cpp_conversion_error()); } }; } // namepace apollo #endif // APOLLO_CONVERTERS_HPP_INCLUDED <|endoftext|>
<commit_before>//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_filepath.ipp * @brief iris unit test ファイルパスクラス ファイル * * @author t.shirayanagi * @par copyright * Copyright (C) 2012-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_FILEPATH_IPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_ #define INCG_IRIS_IUTEST_FILEPATH_IPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_ //====================================================================== // include #include "../internal/iutest_filepath.hpp" namespace iutest { namespace detail { IUTEST_IPP_INLINE bool iuFilePath::IsDirectory() const { // const char last = m_path.back(); const char last = m_path.c_str()[length() - 1]; return !m_path.empty() && (IsPathSeparator(last) || last == '.'); } IUTEST_IPP_INLINE bool iuFilePath::IsRootDirectory() const { #ifdef IUTEST_OS_WINDOWS if( length() != 3 ) { return false; } #else if( length() != 3 ) { return false; } #endif return IsAbsolutePath(); } IUTEST_IPP_INLINE bool iuFilePath::IsAbsolutePath() const { #ifdef IUTEST_OS_WINDOWS if( length() < 3 ) { return false; } const char* name = m_path.c_str(); if( IsDBCSLeadByte(name[0]) ) { ++name; } return (name[1] == ':' && IsPathSeparator(name[0])); #else return IsPathSeparator(m_path.c_str()[0]); #endif } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveTrailingPathSeparator() const { return IsDirectory() ? iuFilePath(std::string(m_path.c_str(), length()-1)) : *this; } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveExtension(const char* extention) const { const char* const path = m_path.c_str(); const char* const ext = strrchr(path, '.'); if( ext == NULL ) { return *this; } if( extention != NULL && !IsStringCaseEqual(ext + 1, extention) ) { return *this; } const size_t length = ext - path; return iuFilePath(std::string(path, length)); } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveDirectoryName() const { const char* const sep = FindLastPathSeparator(); return sep != NULL ? iuFilePath(sep+1) : *this; } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveFileName() const { const char* sep = FindLastPathSeparator(); if( sep == NULL ) { return GetRelativeCurrentDir(); } const size_t length = sep - c_str() + 1; return iuFilePath(std::string(c_str(), length)); } IUTEST_IPP_INLINE bool iuFilePath::CreateFolder() const { #if IUTEST_HAS_FILE_STAT #if defined(IUTEST_OS_WINDOWS_MOBILE) #elif defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_WINE) if( _mkdir(c_str()) == 0 ) { return true; } #else if( mkdir(c_str(), 0777) == 0 ) { return true; } #endif #endif return DirectoryExists(); } IUTEST_IPP_INLINE bool iuFilePath::CreateDirectoriesRecursively() const { if( !IsDirectory() ) { return false; } if( length() == 0 || DirectoryExists() ) { return true; } const iuFilePath parent = RemoveTrailingPathSeparator().RemoveFileName(); if( !parent.CreateDirectoriesRecursively() ) { return false; } return CreateFolder(); } IUTEST_IPP_INLINE bool iuFilePath::FileOrDirectoryExists() const { #if IUTEST_HAS_FILE_STAT posix::StatStruct file_stat; return posix::Stat(c_str(), &file_stat) == 0; #else return false; #endif } IUTEST_IPP_INLINE bool iuFilePath::DirectoryExists() const { #if IUTEST_HAS_FILE_STAT #ifdef IUTEST_OS_WINDOWS const iuFilePath& path = IsRootDirectory() ? *this : RemoveTrailingPathSeparator(); #else const iuFilePath& path = *this; #endif posix::StatStruct file_stat; if( posix::Stat(path.c_str(), &file_stat) == 0 ) { return posix::IsDir(file_stat); } #endif return false; } IUTEST_IPP_INLINE const char* iuFilePath::FindLastPathSeparator() const { return detail::FindLastPathSeparator(c_str(), length()); } IUTEST_IPP_INLINE iuFilePath iuFilePath::GetCurrentDir() { return iuFilePath(internal::posix::GetCWD()); } IUTEST_IPP_INLINE iuFilePath iuFilePath::GetRelativeCurrentDir() { ::std::string dir("."); dir += GetPathSeparator(); return iuFilePath(dir); } IUTEST_IPP_INLINE iuFilePath iuFilePath::GetExecFilePath() { #if defined(IUTEST_OS_WINDOWS) char path[IUTEST_MAX_PATH]; ::GetModuleFileNameA(NULL, path, sizeof(path)); return iuFilePath(path); #elif defined(IUTEST_OS_SOLARIS) return iuFilePath(getexecname()); #elif defined(__FreeBSD__) int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() }; char buf[1024]; size_t length = 0; if( sysctl(exe_path_mib, 4, buf, &length, NULL, 0) != 0 ) { return iuFilePath(); } return iuFilePath(buf); #elif defined(IUTEST_OS_LINUX) || defined(IUTEST_OS_CYGWIN) #if (defined(__BSD_VISIBLE) && __BSD_VISIBLE) || (defined(__POSIX_VISIBLE) && __POSIX_VISIBLE >= 200112) || (defined(__XSI_VISIBLE) && __XSI_VISIBLE >= 4) char buf[1024]; const ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf)-1); if( len == -1 ) { return iuFilePath(); } buf[len] = '\0'; return iuFilePath(buf); #else return iuFilePath(); #endif #else return iuFilePath(); #endif } IUTEST_IPP_INLINE iuFilePath iuFilePath::ConcatPaths(const iuFilePath& directory, const iuFilePath& relative_path) { ::std::string path = directory.RemoveTrailingPathSeparator().c_str(); path += GetPathSeparator(); path += relative_path.c_str(); return iuFilePath(path); } IUTEST_IPP_INLINE void iuFilePath::Normalize() { const char* src = c_str(); char* const dst_top = new char [length()+1]; char* dst = dst_top; while(*src != '\0') { *dst = *src; if( !IsPathSeparator(*src) ) { ++src; } else { if( IsAltPathSeparator(*src) ) { *dst = GetPathSeparator(); } ++src; while( IsPathSeparator(*src) ) { ++src; } } ++dst; } *dst = '\0'; m_path = dst_top; delete [] dst_top; } } // end of namespace detail } // end of namespace iutest #endif // INCG_IRIS_IUTEST_FILEPATH_IPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_ <commit_msg>fix cppplint<commit_after>//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_filepath.ipp * @brief iris unit test ファイルパスクラス ファイル * * @author t.shirayanagi * @par copyright * Copyright (C) 2012-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_FILEPATH_IPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_ #define INCG_IRIS_IUTEST_FILEPATH_IPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_ //====================================================================== // include #include "../internal/iutest_filepath.hpp" namespace iutest { namespace detail { IUTEST_IPP_INLINE bool iuFilePath::IsDirectory() const { // const char last = m_path.back(); const char last = m_path.c_str()[length() - 1]; return !m_path.empty() && (IsPathSeparator(last) || last == '.'); } IUTEST_IPP_INLINE bool iuFilePath::IsRootDirectory() const { #ifdef IUTEST_OS_WINDOWS if( length() != 3 ) { return false; } #else if( length() != 3 ) { return false; } #endif return IsAbsolutePath(); } IUTEST_IPP_INLINE bool iuFilePath::IsAbsolutePath() const { #ifdef IUTEST_OS_WINDOWS if( length() < 3 ) { return false; } const char* name = m_path.c_str(); if( IsDBCSLeadByte(name[0]) ) { ++name; } return (name[1] == ':' && IsPathSeparator(name[0])); #else return IsPathSeparator(m_path.c_str()[0]); #endif } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveTrailingPathSeparator() const { return IsDirectory() ? iuFilePath(std::string(m_path.c_str(), length()-1)) : *this; } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveExtension(const char* extention) const { const char* const path = m_path.c_str(); const char* const ext = strrchr(path, '.'); if( ext == NULL ) { return *this; } if( extention != NULL && !IsStringCaseEqual(ext + 1, extention) ) { return *this; } const size_t length = ext - path; return iuFilePath(std::string(path, length)); } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveDirectoryName() const { const char* const sep = FindLastPathSeparator(); return sep != NULL ? iuFilePath(sep+1) : *this; } IUTEST_IPP_INLINE iuFilePath iuFilePath::RemoveFileName() const { const char* sep = FindLastPathSeparator(); if( sep == NULL ) { return GetRelativeCurrentDir(); } const size_t length = sep - c_str() + 1; return iuFilePath(std::string(c_str(), length)); } IUTEST_IPP_INLINE bool iuFilePath::CreateFolder() const { #if IUTEST_HAS_FILE_STAT #if defined(IUTEST_OS_WINDOWS_MOBILE) #elif defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_WINE) if( _mkdir(c_str()) == 0 ) { return true; } #else if( mkdir(c_str(), 0777) == 0 ) { return true; } #endif #endif return DirectoryExists(); } IUTEST_IPP_INLINE bool iuFilePath::CreateDirectoriesRecursively() const { if( !IsDirectory() ) { return false; } if( length() == 0 || DirectoryExists() ) { return true; } const iuFilePath parent = RemoveTrailingPathSeparator().RemoveFileName(); if( !parent.CreateDirectoriesRecursively() ) { return false; } return CreateFolder(); } IUTEST_IPP_INLINE bool iuFilePath::FileOrDirectoryExists() const { #if IUTEST_HAS_FILE_STAT posix::StatStruct file_stat; return posix::Stat(c_str(), &file_stat) == 0; #else return false; #endif } IUTEST_IPP_INLINE bool iuFilePath::DirectoryExists() const { #if IUTEST_HAS_FILE_STAT #ifdef IUTEST_OS_WINDOWS const iuFilePath& path = IsRootDirectory() ? *this : RemoveTrailingPathSeparator(); #else const iuFilePath& path = *this; #endif posix::StatStruct file_stat; if( posix::Stat(path.c_str(), &file_stat) == 0 ) { return posix::IsDir(file_stat); } #endif return false; } IUTEST_IPP_INLINE const char* iuFilePath::FindLastPathSeparator() const { return detail::FindLastPathSeparator(c_str(), length()); } IUTEST_IPP_INLINE iuFilePath iuFilePath::GetCurrentDir() { return iuFilePath(internal::posix::GetCWD()); } IUTEST_IPP_INLINE iuFilePath iuFilePath::GetRelativeCurrentDir() { ::std::string dir("."); dir += GetPathSeparator(); return iuFilePath(dir); } IUTEST_IPP_INLINE iuFilePath iuFilePath::GetExecFilePath() { #if defined(IUTEST_OS_WINDOWS) char path[IUTEST_MAX_PATH]; ::GetModuleFileNameA(NULL, path, sizeof(path)); return iuFilePath(path); #elif defined(IUTEST_OS_SOLARIS) return iuFilePath(getexecname()); #elif defined(__FreeBSD__) int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() }; char buf[1024]; size_t length = 0; if( sysctl(exe_path_mib, 4, buf, &length, NULL, 0) != 0 ) { return iuFilePath(); } return iuFilePath(buf); #elif defined(IUTEST_OS_LINUX) || defined(IUTEST_OS_CYGWIN) #if (defined(__BSD_VISIBLE) && __BSD_VISIBLE) \ || (defined(__POSIX_VISIBLE) && __POSIX_VISIBLE >= 200112) \ || (defined(__XSI_VISIBLE) && __XSI_VISIBLE >= 4) char buf[1024]; const ssize_t len = ::readlink("/proc/self/exe", buf, sizeof(buf)-1); if( len == -1 ) { return iuFilePath(); } buf[len] = '\0'; return iuFilePath(buf); #else return iuFilePath(); #endif #else return iuFilePath(); #endif } IUTEST_IPP_INLINE iuFilePath iuFilePath::ConcatPaths(const iuFilePath& directory, const iuFilePath& relative_path) { ::std::string path = directory.RemoveTrailingPathSeparator().c_str(); path += GetPathSeparator(); path += relative_path.c_str(); return iuFilePath(path); } IUTEST_IPP_INLINE void iuFilePath::Normalize() { const char* src = c_str(); char* const dst_top = new char [length()+1]; char* dst = dst_top; while(*src != '\0') { *dst = *src; if( !IsPathSeparator(*src) ) { ++src; } else { if( IsAltPathSeparator(*src) ) { *dst = GetPathSeparator(); } ++src; while( IsPathSeparator(*src) ) { ++src; } } ++dst; } *dst = '\0'; m_path = dst_top; delete [] dst_top; } } // end of namespace detail } // end of namespace iutest #endif // INCG_IRIS_IUTEST_FILEPATH_IPP_D69E7545_BF8A_4EDC_9493_9105C69F9378_ <|endoftext|>
<commit_before>/* Copyright (c) 2007, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DISABLE_ENCRYPTION #ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED #define TORRENT_PE_CRYPTO_HPP_INCLUDED #include "libtorrent/config.hpp" #ifdef TORRENT_USE_GCRYPT #include <gcrypt.h> #elif defined TORRENT_USE_OPENSSL #include <openssl/rc4.h> #include <openssl/evp.h> #include <openssl/aes.h> #else // RC4 state from libtomcrypt struct rc4 { int x, y; unsigned char buf[256]; }; void TORRENT_EXPORT rc4_init(const unsigned char* in, unsigned long len, rc4 *state); unsigned long TORRENT_EXPORT rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state); #endif #include "libtorrent/peer_id.hpp" // For sha1_hash #include "libtorrent/assert.hpp" namespace libtorrent { class TORRENT_EXPORT dh_key_exchange { public: dh_key_exchange(); bool good() const { return true; } // Get local public key, always 96 bytes char const* get_local_key() const; // read remote_pubkey, generate and store shared secret in // m_dh_shared_secret. int compute_secret(const char* remote_pubkey); char const* get_secret() const { return m_dh_shared_secret; } sha1_hash const& get_hash_xor_mask() const { return m_xor_mask; } private: int get_local_key_size() const { return sizeof(m_dh_local_key); } char m_dh_local_key[96]; char m_dh_local_secret[96]; char m_dh_shared_secret[96]; sha1_hash m_xor_mask; }; struct encryption_handler { virtual void set_incoming_key(unsigned char const* key, int len) = 0; virtual void set_outgoing_key(unsigned char const* key, int len) = 0; virtual void encrypt(char* pos, int len) = 0; virtual void decrypt(char* pos, int len) = 0; }; struct rc4_handler : encryption_handler { public: // Input longkeys must be 20 bytes rc4_handler() : m_encrypt(false) , m_decrypt(false) { #ifdef TORRENT_USE_GCRYPT gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); #endif }; void set_incoming_key(unsigned char const* key, int len) { m_decrypt = true; #ifdef TORRENT_USE_GCRYPT gcry_cipher_close(m_rc4_incoming); gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); gcry_cipher_setkey(m_rc4_incoming, key, len); #elif defined TORRENT_USE_OPENSSL RC4_set_key(&m_remote_key, len, key); #else rc4_init(key, len, &m_rc4_incoming); #endif // Discard first 1024 bytes char buf[1024]; decrypt(buf, 1024); } void set_outgoing_key(unsigned char const* key, int len) { m_encrypt = true; #ifdef TORRENT_USE_GCRYPT gcry_cipher_close(m_rc4_outgoing); gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); gcry_cipher_setkey(m_rc4_outgoing, key, len); #elif defined TORRENT_USE_OPENSSL RC4_set_key(&m_local_key, len, key); #else rc4_init(key, len, &m_rc4_outgoing); #endif // Discard first 1024 bytes char buf[1024]; encrypt(buf, 1024); } ~rc4_handler() { #ifdef TORRENT_USE_GCRYPT gcry_cipher_close(m_rc4_incoming); gcry_cipher_close(m_rc4_outgoing); #endif }; void encrypt(char* pos, int len) { if (!m_encrypt) return; TORRENT_ASSERT(len >= 0); TORRENT_ASSERT(pos); #ifdef TORRENT_USE_GCRYPT gcry_cipher_encrypt(m_rc4_outgoing, pos, len, 0, 0); #elif defined TORRENT_USE_OPENSSL RC4(&m_local_key, len, (const unsigned char*)pos, (unsigned char*)pos); #else rc4_encrypt((unsigned char*)pos, len, &m_rc4_outgoing); #endif } void decrypt(char* pos, int len) { if (!m_decrypt) return; TORRENT_ASSERT(len >= 0); TORRENT_ASSERT(pos); #ifdef TORRENT_USE_GCRYPT gcry_cipher_decrypt(m_rc4_incoming, pos, len, 0, 0); #elif defined TORRENT_USE_OPENSSL RC4(&m_remote_key, len, (const unsigned char*)pos, (unsigned char*)pos); #else rc4_encrypt((unsigned char*)pos, len, &m_rc4_incoming); #endif } private: #ifdef TORRENT_USE_GCRYPT gcry_cipher_hd_t m_rc4_incoming; gcry_cipher_hd_t m_rc4_outgoing; #elif defined TORRENT_USE_OPENSSL RC4_KEY m_local_key; // Key to encrypt outgoing data RC4_KEY m_remote_key; // Key to decrypt incoming data #else rc4 m_rc4_incoming; rc4 m_rc4_outgoing; #endif // determines whether or not encryption and decryption is enabled bool m_encrypt; bool m_decrypt; }; #ifdef TORRENT_USE_OPENSSL struct aes256_handler : encryption_handler { aes256_handler() : m_enc_pos(0), m_dec_pos(0) { EVP_CIPHER_CTX_init(&m_enc); EVP_CIPHER_CTX_init(&m_dec); } ~aes256_handler() { EVP_CIPHER_CTX_cleanup(&m_enc); EVP_CIPHER_CTX_cleanup(&m_dec); } void set_incoming_key(unsigned char const* in_key, int len) { const int nrounds = 5; boost::uint8_t salt[8] = { 0xf1, 0x03, 0x46, 0xe2, 0xb1, 0xa8, 0x29, 0x63 }; boost::uint8_t key[32]; boost::uint8_t iv[32]; int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, in_key, len, nrounds, key, iv); TORRENT_ASSERT(len == 32); EVP_EncryptInit_ex(&m_enc, EVP_aes_256_cbc(), NULL, key, iv); // since we're using the AES as a stream cipher, both the encrypt and // decrypt context will in fact only _encrypt_ stuff, so initializing // this as encrypt is not a typo EVP_EncryptInit_ex(&m_dec, EVP_aes_256_cbc(), NULL, key, iv); m_enc_pos = 0; m_dec_pos = 0; std::memcpy(m_enc_state, iv, sizeof(m_enc_state)); std::memcpy(m_dec_state, iv, sizeof(m_enc_state)); } void set_outgoing_key(unsigned char const* key, int len) { /* no-op */ } void encrypt(char* pos, int len) { while (len > 0) { while (m_enc_pos < AES_BLOCK_SIZE && len > 0) { *pos ^= m_enc_state[m_enc_pos]; ++m_enc_pos; ++pos; --len; } if (m_enc_pos == AES_BLOCK_SIZE) { next_block(&m_enc, m_enc_state); m_enc_pos = 0; } } } void decrypt(char* pos, int len) { while (len > 0) { while (m_dec_pos < AES_BLOCK_SIZE && len > 0) { *pos ^= m_dec_state[m_dec_pos]; ++m_dec_pos; ++pos; --len; } if (m_dec_pos == AES_BLOCK_SIZE) { next_block(&m_dec, m_dec_state); m_dec_pos = 0; } } } private: // we're turning the AES block-cipher into a stream cipher. This // function will produce the next block in the sequence of // block-sized buffers. We're using "Output feedback" (OFB) mode. void next_block(EVP_CIPHER_CTX* ctx, boost::uint8_t* pad) { int outlen = AES_BLOCK_SIZE; EVP_EncryptUpdate(ctx, pad, &outlen, pad, AES_BLOCK_SIZE); TORRENT_ASSERT(outlen == AES_BLOCK_SIZE); } EVP_CIPHER_CTX m_enc; EVP_CIPHER_CTX m_dec; boost::uint8_t m_enc_state[AES_BLOCK_SIZE]; boost::uint8_t m_dec_state[AES_BLOCK_SIZE]; int m_enc_pos; int m_dec_pos; }; #endif // TORRENT_USE_OPENSSL } // namespace libtorrent #endif // TORRENT_PE_CRYPTO_HPP_INCLUDED #endif // TORRENT_DISABLE_ENCRYPTION <commit_msg>fix some encryption warnings<commit_after>/* Copyright (c) 2007, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DISABLE_ENCRYPTION #ifndef TORRENT_PE_CRYPTO_HPP_INCLUDED #define TORRENT_PE_CRYPTO_HPP_INCLUDED #include "libtorrent/config.hpp" #ifdef TORRENT_USE_GCRYPT #include <gcrypt.h> #elif defined TORRENT_USE_OPENSSL #include <openssl/rc4.h> #include <openssl/evp.h> #include <openssl/aes.h> #else // RC4 state from libtomcrypt struct rc4 { int x, y; unsigned char buf[256]; }; void TORRENT_EXPORT rc4_init(const unsigned char* in, unsigned long len, rc4 *state); unsigned long TORRENT_EXPORT rc4_encrypt(unsigned char *out, unsigned long outlen, rc4 *state); #endif #include "libtorrent/peer_id.hpp" // For sha1_hash #include "libtorrent/assert.hpp" namespace libtorrent { class TORRENT_EXPORT dh_key_exchange { public: dh_key_exchange(); bool good() const { return true; } // Get local public key, always 96 bytes char const* get_local_key() const; // read remote_pubkey, generate and store shared secret in // m_dh_shared_secret. int compute_secret(const char* remote_pubkey); char const* get_secret() const { return m_dh_shared_secret; } sha1_hash const& get_hash_xor_mask() const { return m_xor_mask; } private: int get_local_key_size() const { return sizeof(m_dh_local_key); } char m_dh_local_key[96]; char m_dh_local_secret[96]; char m_dh_shared_secret[96]; sha1_hash m_xor_mask; }; struct encryption_handler { virtual void set_incoming_key(unsigned char const* key, int len) = 0; virtual void set_outgoing_key(unsigned char const* key, int len) = 0; virtual void encrypt(char* pos, int len) = 0; virtual void decrypt(char* pos, int len) = 0; virtual ~encryption_handler() {} }; struct rc4_handler : encryption_handler { public: // Input longkeys must be 20 bytes rc4_handler() : m_encrypt(false) , m_decrypt(false) { #ifdef TORRENT_USE_GCRYPT gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); #endif }; void set_incoming_key(unsigned char const* key, int len) { m_decrypt = true; #ifdef TORRENT_USE_GCRYPT gcry_cipher_close(m_rc4_incoming); gcry_cipher_open(&m_rc4_incoming, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); gcry_cipher_setkey(m_rc4_incoming, key, len); #elif defined TORRENT_USE_OPENSSL RC4_set_key(&m_remote_key, len, key); #else rc4_init(key, len, &m_rc4_incoming); #endif // Discard first 1024 bytes char buf[1024]; decrypt(buf, 1024); } void set_outgoing_key(unsigned char const* key, int len) { m_encrypt = true; #ifdef TORRENT_USE_GCRYPT gcry_cipher_close(m_rc4_outgoing); gcry_cipher_open(&m_rc4_outgoing, GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM, 0); gcry_cipher_setkey(m_rc4_outgoing, key, len); #elif defined TORRENT_USE_OPENSSL RC4_set_key(&m_local_key, len, key); #else rc4_init(key, len, &m_rc4_outgoing); #endif // Discard first 1024 bytes char buf[1024]; encrypt(buf, 1024); } ~rc4_handler() { #ifdef TORRENT_USE_GCRYPT gcry_cipher_close(m_rc4_incoming); gcry_cipher_close(m_rc4_outgoing); #endif }; void encrypt(char* pos, int len) { if (!m_encrypt) return; TORRENT_ASSERT(len >= 0); TORRENT_ASSERT(pos); #ifdef TORRENT_USE_GCRYPT gcry_cipher_encrypt(m_rc4_outgoing, pos, len, 0, 0); #elif defined TORRENT_USE_OPENSSL RC4(&m_local_key, len, (const unsigned char*)pos, (unsigned char*)pos); #else rc4_encrypt((unsigned char*)pos, len, &m_rc4_outgoing); #endif } void decrypt(char* pos, int len) { if (!m_decrypt) return; TORRENT_ASSERT(len >= 0); TORRENT_ASSERT(pos); #ifdef TORRENT_USE_GCRYPT gcry_cipher_decrypt(m_rc4_incoming, pos, len, 0, 0); #elif defined TORRENT_USE_OPENSSL RC4(&m_remote_key, len, (const unsigned char*)pos, (unsigned char*)pos); #else rc4_encrypt((unsigned char*)pos, len, &m_rc4_incoming); #endif } private: #ifdef TORRENT_USE_GCRYPT gcry_cipher_hd_t m_rc4_incoming; gcry_cipher_hd_t m_rc4_outgoing; #elif defined TORRENT_USE_OPENSSL RC4_KEY m_local_key; // Key to encrypt outgoing data RC4_KEY m_remote_key; // Key to decrypt incoming data #else rc4 m_rc4_incoming; rc4 m_rc4_outgoing; #endif // determines whether or not encryption and decryption is enabled bool m_encrypt; bool m_decrypt; }; #ifdef TORRENT_USE_OPENSSL struct aes256_handler : encryption_handler { aes256_handler() : m_enc_pos(0), m_dec_pos(0) { EVP_CIPHER_CTX_init(&m_enc); EVP_CIPHER_CTX_init(&m_dec); } ~aes256_handler() { EVP_CIPHER_CTX_cleanup(&m_enc); EVP_CIPHER_CTX_cleanup(&m_dec); } void set_incoming_key(unsigned char const* in_key, int len) { const int nrounds = 5; boost::uint8_t salt[8] = { 0xf1, 0x03, 0x46, 0xe2, 0xb1, 0xa8, 0x29, 0x63 }; boost::uint8_t key[32]; boost::uint8_t iv[32]; EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), salt, in_key, len, nrounds, key, iv); TORRENT_ASSERT(len == 32); EVP_EncryptInit_ex(&m_enc, EVP_aes_256_cbc(), NULL, key, iv); // since we're using the AES as a stream cipher, both the encrypt and // decrypt context will in fact only _encrypt_ stuff, so initializing // this as encrypt is not a typo EVP_EncryptInit_ex(&m_dec, EVP_aes_256_cbc(), NULL, key, iv); m_enc_pos = 0; m_dec_pos = 0; std::memcpy(m_enc_state, iv, sizeof(m_enc_state)); std::memcpy(m_dec_state, iv, sizeof(m_enc_state)); } void set_outgoing_key(unsigned char const* key, int len) { /* no-op */ } void encrypt(char* pos, int len) { while (len > 0) { while (m_enc_pos < AES_BLOCK_SIZE && len > 0) { *pos ^= m_enc_state[m_enc_pos]; ++m_enc_pos; ++pos; --len; } if (m_enc_pos == AES_BLOCK_SIZE) { next_block(&m_enc, m_enc_state); m_enc_pos = 0; } } } void decrypt(char* pos, int len) { while (len > 0) { while (m_dec_pos < AES_BLOCK_SIZE && len > 0) { *pos ^= m_dec_state[m_dec_pos]; ++m_dec_pos; ++pos; --len; } if (m_dec_pos == AES_BLOCK_SIZE) { next_block(&m_dec, m_dec_state); m_dec_pos = 0; } } } private: // we're turning the AES block-cipher into a stream cipher. This // function will produce the next block in the sequence of // block-sized buffers. We're using "Output feedback" (OFB) mode. void next_block(EVP_CIPHER_CTX* ctx, boost::uint8_t* pad) { int outlen = AES_BLOCK_SIZE; EVP_EncryptUpdate(ctx, pad, &outlen, pad, AES_BLOCK_SIZE); TORRENT_ASSERT(outlen == AES_BLOCK_SIZE); } EVP_CIPHER_CTX m_enc; EVP_CIPHER_CTX m_dec; boost::uint8_t m_enc_state[AES_BLOCK_SIZE]; boost::uint8_t m_dec_state[AES_BLOCK_SIZE]; int m_enc_pos; int m_dec_pos; }; #endif // TORRENT_USE_OPENSSL } // namespace libtorrent #endif // TORRENT_PE_CRYPTO_HPP_INCLUDED #endif // TORRENT_DISABLE_ENCRYPTION <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> #include <cstring> #include "libtorrent/escape_string.hpp" namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; if (p != end && p+8 < end && string_begins_no_case("![CDATA[", p)) { // CDATA. match '![CDATA[' p += 8; start = p; while (p != end && !string_begins_no_case("]]>", p-2)) ++p; // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } token = xml_string; char tmp = p[-2]; p[-2] = 0; callback(token, start, val_start); p[-2] = tmp; continue; } // parse the name of the tag. for (start = p; p != end && *p != '>' && !is_space(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && isspace(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !isspace(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && isspace(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <commit_msg>replace calls to isspace() with is_space() to avoid asserts in the CRT<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> #include <cstring> #include "libtorrent/escape_string.hpp" namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; if (p != end && p+8 < end && string_begins_no_case("![CDATA[", p)) { // CDATA. match '![CDATA[' p += 8; start = p; while (p != end && !string_begins_no_case("]]>", p-2)) ++p; // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } token = xml_string; char tmp = p[-2]; p[-2] = 0; callback(token, start, val_start); p[-2] = tmp; continue; } // parse the name of the tag. for (start = p; p != end && *p != '>' && !is_space(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && is_space(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !is_space(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && is_space(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <|endoftext|>
<commit_before>#pragma once #include "oqpi/scheduling/task_base.hpp" #include "oqpi/scheduling/task_result.hpp" #include "oqpi/scheduling/task_notifier.hpp" namespace oqpi { template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func> class task final : public task_base , public task_result<typename std::result_of<_Func()>::type> , public _TaskContext , public notifier<_TaskType, _EventType> { //------------------------------------------------------------------------------------------ using self_type = task<_TaskType, _EventType, _TaskContext, _Func>; using return_type = typename std::result_of<_Func()>::type; using task_result_type = task_result<return_type>; using notifier_type = notifier<_TaskType, _EventType>; public: //------------------------------------------------------------------------------------------ task(const std::string &name, task_priority priority, _Func func) : task_base(priority) , _TaskContext(this, name) , notifier_type(task_base::getUID()) , func_(std::move(func)) {} //------------------------------------------------------------------------------------------ // Movable task(self_type &&other) : task_base(std::move(other)) , _TaskContext(std::move(other)) , notifier_type(std::move(other)) , func_(std::move(other.func_)) {} //------------------------------------------------------------------------------------------ self_type& operator =(self_type &&rhs) { if (this != &rhs) { task_base::operator =(std::move(rhs)); _TaskContext::operator =(std::move(rhs)); notifier_type::operator =(std::move(rhs)); func_ = std::move(rhs.func_); } return (*this); } //------------------------------------------------------------------------------------------ // Not copyable task(const self_type &) = delete; self_type& operator =(const self_type &) = delete; public: //------------------------------------------------------------------------------------------ virtual void execute() override final { if (oqpi_ensuref(task_base::isGrabbed(), "Trying to execute an ungrabbed task: %d", task_base::getUID())) { invoke(); task_base::notifyParent(); } } //------------------------------------------------------------------------------------------ virtual void executeSingleThreaded() override final { if (task_base::tryGrab()) { invoke(); // We are single threaded meaning that our parent (if any) is running this task // in its executeSingleThreaded function, so no need to notify it. } } //------------------------------------------------------------------------------------------ virtual void wait() const override final { notifier_type::wait(); } //------------------------------------------------------------------------------------------ virtual void activeWait() override final { if (task_base::tryGrab()) { execute(); } else { wait(); } } //------------------------------------------------------------------------------------------ virtual void onParentGroupSet() override final { _TaskContext::task_onAddedToGroup(this->spParentGroup_); } //------------------------------------------------------------------------------------------ return_type getResult() const { oqpi_checkf(task_base::isDone(), "Trying to get the result of an unfinished task: %d", task_base::getUID()); return task_result_type::getResult(); } //------------------------------------------------------------------------------------------ return_type waitForResult() const { wait(); return getResult(); } private: //------------------------------------------------------------------------------------------ inline void invoke() { // Run the preExecute code of the context _TaskContext::task_onPreExecute(); // Run the task itself task_result_type::run(func_); // Flag the task as done task_base::setDone(); // Run the postExecute code of the context _TaskContext::task_onPostExecute(); // Signal that the task is done notifier_type::notify(); } private: _Func func_; }; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Type : user defined // Context : user defined template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func, typename... _Args> inline auto make_task(const std::string &name, task_priority priority, _Func &&func, _Args &&...args) { const auto f = [func = std::forward<_Func>(func), &args...] { return func(std::forward<_Args>(args)...); }; using task_type = task<_TaskType, _EventType, _TaskContext, std::decay_t<decltype(f)>>; return std::make_shared<task_type> ( name, priority, std::move(f) ); } //---------------------------------------------------------------------------------------------- } /*oqpi*/ <commit_msg>Fixed the arguments forwarding when using make_task with variadic arguments to forward to the task. Needs C++17 feature: std::apply<commit_after>#pragma once #include <tuple> #include "oqpi/scheduling/task_base.hpp" #include "oqpi/scheduling/task_result.hpp" #include "oqpi/scheduling/task_notifier.hpp" namespace oqpi { template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func> class task final : public task_base , public task_result<typename std::result_of<_Func()>::type> , public _TaskContext , public notifier<_TaskType, _EventType> { //------------------------------------------------------------------------------------------ using self_type = task<_TaskType, _EventType, _TaskContext, _Func>; using return_type = typename std::result_of<_Func()>::type; using task_result_type = task_result<return_type>; using notifier_type = notifier<_TaskType, _EventType>; public: //------------------------------------------------------------------------------------------ task(const std::string &name, task_priority priority, _Func func) : task_base(priority) , _TaskContext(this, name) , notifier_type(task_base::getUID()) , func_(std::move(func)) {} //------------------------------------------------------------------------------------------ // Movable task(self_type &&other) : task_base(std::move(other)) , _TaskContext(std::move(other)) , notifier_type(std::move(other)) , func_(std::move(other.func_)) {} //------------------------------------------------------------------------------------------ self_type& operator =(self_type &&rhs) { if (this != &rhs) { task_base::operator =(std::move(rhs)); _TaskContext::operator =(std::move(rhs)); notifier_type::operator =(std::move(rhs)); func_ = std::move(rhs.func_); } return (*this); } //------------------------------------------------------------------------------------------ // Not copyable task(const self_type &) = delete; self_type& operator =(const self_type &) = delete; public: //------------------------------------------------------------------------------------------ virtual void execute() override final { if (oqpi_ensuref(task_base::isGrabbed(), "Trying to execute an ungrabbed task: %d", task_base::getUID())) { invoke(); task_base::notifyParent(); } } //------------------------------------------------------------------------------------------ virtual void executeSingleThreaded() override final { if (task_base::tryGrab()) { invoke(); // We are single threaded meaning that our parent (if any) is running this task // in its executeSingleThreaded function, so no need to notify it. } } //------------------------------------------------------------------------------------------ virtual void wait() const override final { notifier_type::wait(); } //------------------------------------------------------------------------------------------ virtual void activeWait() override final { if (task_base::tryGrab()) { execute(); } else { wait(); } } //------------------------------------------------------------------------------------------ virtual void onParentGroupSet() override final { _TaskContext::task_onAddedToGroup(this->spParentGroup_); } //------------------------------------------------------------------------------------------ return_type getResult() const { oqpi_checkf(task_base::isDone(), "Trying to get the result of an unfinished task: %d", task_base::getUID()); return task_result_type::getResult(); } //------------------------------------------------------------------------------------------ return_type waitForResult() const { wait(); return getResult(); } private: //------------------------------------------------------------------------------------------ inline void invoke() { // Run the preExecute code of the context _TaskContext::task_onPreExecute(); // Run the task itself task_result_type::run(func_); // Flag the task as done task_base::setDone(); // Run the postExecute code of the context _TaskContext::task_onPostExecute(); // Signal that the task is done notifier_type::notify(); } private: _Func func_; }; //---------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------- // Type : user defined // Context : user defined template<task_type _TaskType, typename _EventType, typename _TaskContext, typename _Func, typename... _Args> inline auto make_task(const std::string &name, task_priority priority, _Func &&func, _Args &&...args) { const auto f = [func = std::forward<_Func>(func), args = std::make_tuple(std::forward<_Args>(args)...)] { return std::apply(func, args); }; using task_type = task<_TaskType, _EventType, _TaskContext, std::decay_t<decltype(f)>>; return std::make_shared<task_type> ( name, priority, std::move(f) ); } //---------------------------------------------------------------------------------------------- } /*oqpi*/ <|endoftext|>
<commit_before>#pragma once #include <rex/config.hpp> #ifndef REX_DISABLE_ASYNC #include <mutex> #endif #include <unordered_map> #include <rex/thero.hpp> #include <rex/exceptions.hpp> #include <rex/exceptions.hpp> #include <rex/resourceview.hpp> #include <rex/sourceview.hpp> #ifndef REX_DISABLE_ASYNC #include <rex/asyncresourceview.hpp> #include <rex/threadpool.hpp> #endif namespace rex { class ResourceProvider { template<typename ResourceType> using LoadingFunction = ResourceType(*)(const th::Any&, const std::string&); using ListingFunction = std::vector<std::string>(*)(const th::Any&); using WaitFunction = void(*)(const th::Any&); struct SourceEntry { th::Any source; th::Any loadingFunction; ListingFunction listingFunction; WaitFunction waitFunction; std::type_index typeProvided; }; public: ResourceProvider(int32_t workerCount = 10); //sources template <typename SourceType> SourceView<SourceType> source(const std::string& sourceId) const; template <typename SourceType> SourceView<SourceType> addSource(const std::string& sourceId, SourceType source); std::vector<std::string> sources() const; bool removeSource(const std::string& sourceId); void clearSources(); //list std::vector<std::string> list(const std::string& sourceId) const; //sync get template <typename ResourceType> const ResourceType& get(const std::string& sourceId, const std::string& resourceId) const; template <typename ResourceType> std::vector<ResourceView<ResourceType>> get(const std::string& sourceId, const std::vector<std::string>& resourceIds) const; template <typename ResourceType> std::vector<ResourceView<ResourceType>> getAll(const std::string& sourceId) const; #ifndef REX_DISABLE_ASYNC //async get template <typename ResourceType> AsyncResourceView<ResourceType> asyncGet(const std::string& sourceId, const std::string& resourceId) const; template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> asyncGet(const std::string& sourceId, const std::vector<std::string>& resourceIds) const; template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> asyncGetAll(const std::string& sourceId) const; #endif //free void markUnused(const std::string& sourceId, const std::string& resourceId); void markAllUnused(const std::string& sourceId); private: bool resourceReady(const std::string& sourceId, const std::string& resourceId) const; bool resourceLoadInProgress(const std::string& sourceId, const std::string& resourceId) const; template <typename ResourceType> const ResourceType& loadResource(const std::string& sourceId, const std::string& resourceId) const; void waitForSourceAsync(const std::string& sourceId) const; const SourceEntry& toSourceEntry(const std::string& sourceId) const; std::unordered_map<std::string, SourceEntry> mSources; mutable std::unordered_map<std::string, std::unordered_map<std::string, th::Any>> mResources; #ifndef REX_DISABLE_ASYNC mutable std::unordered_map<std::string, std::unordered_map<std::string, th::Any>> mAsyncProcesses; mutable std::recursive_mutex mResourceMutex; mutable ThreadPool mThreadPool; #endif }; inline ResourceProvider::ResourceProvider(int32_t workerCount) #ifndef REX_DISABLE_ASYNC :mThreadPool(workerCount) #endif { } template <typename SourceType> SourceView<SourceType> ResourceProvider::source(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); try { return SourceView<SourceType> { sourceId, sourceEntry.source.get<SourceType>() }; } catch(th::AnyTypeException) { throw InvalidSourceException("trying to access source id " + sourceId + " as the wrong type"); } } template <typename SourceType> SourceView<SourceType> ResourceProvider::addSource(const std::string& sourceId, SourceType source) { using ResourceType = decltype(source.load(std::string())); LoadingFunction<ResourceType> loadingFunction = [] (const th::Any& packedSource, const std::string& identifier) { return packedSource.get<SourceType>().load(identifier); }; ListingFunction listingFunction = [] (const th::Any& packedSource) { return packedSource.get<SourceType>().list(); }; WaitFunction waitFunction = [] (const th::Any& packedFuture) { #ifndef REX_DISABLE_ASYNC packedFuture.get<std::shared_future<const ResourceType&>>().wait(); #endif }; auto added = mSources.emplace(sourceId, SourceEntry{std::move(source), loadingFunction, listingFunction, waitFunction, typeid(ResourceType)}); mResources[sourceId]; #ifndef REX_DISABLE_ASYNC mAsyncProcesses[sourceId]; #endif if(added.second) return SourceView<SourceType> { sourceId, added.first->second.source.get<SourceType>() }; else throw InvalidSourceException("adding source id " + sourceId + " which is already added"); } inline std::vector<std::string> ResourceProvider::sources() const { std::vector<std::string> result; for(const auto& source : mSources) result.push_back(source.first); return result; } inline bool ResourceProvider::removeSource(const std::string& sourceId) { mResources.erase(sourceId); #ifndef REX_DISABLE_ASYNC mAsyncProcesses.erase(sourceId); #endif return mSources.erase(sourceId) != 0; } inline void ResourceProvider::clearSources() { mSources.clear(); mResources.clear(); #ifndef REX_DISABLE_ASYNC mAsyncProcesses.clear(); #endif } inline std::vector<std::string> ResourceProvider::list(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); return sourceEntry.listingFunction(sourceEntry.source); } template <typename ResourceType> const ResourceType& ResourceProvider::get(const std::string& sourceId, const std::string& resourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); const auto& source = sourceEntry.source; if(std::type_index(typeid(ResourceType)) != sourceEntry.typeProvided) throw InvalidSourceException("trying to access source id " + sourceId + " as the wrong type"); #ifndef REX_DISABLE_ASYNC std::shared_future<const ResourceType&> futureToWaitFor; { std::lock_guard<std::recursive_mutex> lock(mResourceMutex); //there are three possible cases, and with the lock on, these won't change //1. it is already loaded, so just return it if(mResources.at(sourceId).count(resourceId) != 0) return mResources.at(sourceId).at(resourceId).get<ResourceType>(); //2. it is not loaded and no process is loading it if(mAsyncProcesses.at(sourceId).count(resourceId) == 0) return loadResource<ResourceType>(sourceId, resourceId); //3. it is not loaded and there is a process that loads it already futureToWaitFor = mAsyncProcesses.at(sourceId).at(resourceId).get<std::shared_future<const ResourceType&>>(); } futureToWaitFor.wait(); return futureToWaitFor.get(); #else //Without async, it is either loaded or not, so just return it or load-return it if(mResources.at(sourceId).count(resourceId) != 0) return mResources.at(sourceId).at(resourceId).get<ResourceType>(); else return loadResource<ResourceType>(sourceId, resourceId); #endif } template <typename ResourceType> std::vector<ResourceView<ResourceType>> ResourceProvider::get(const std::string& sourceId, const std::vector<std::string>& resourceIds) const { std::vector<ResourceView<ResourceType>> result; for(const std::string& resourceId : resourceIds) result.emplace_back(ResourceView<ResourceType>{resourceId, get<ResourceType>(sourceId, resourceId)}); return result; } template <typename ResourceType> std::vector<ResourceView<ResourceType>> ResourceProvider::getAll(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); std::vector<std::string> idList = sourceEntry.listingFunction(sourceEntry.source); return get<ResourceType>(sourceId, idList); } #ifndef REX_DISABLE_ASYNC template <typename ResourceType> AsyncResourceView<ResourceType> ResourceProvider::asyncGet(const std::string& sourceId, const std::string& resourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); if(std::type_index(typeid(ResourceType)) != sourceEntry.typeProvided) throw InvalidSourceException("trying to access source id " + sourceId + " as the wrong type"); bool resourceIsReady = false; { std::lock_guard<std::recursive_mutex> lock(mResourceMutex); resourceIsReady = resourceReady(sourceId, resourceId); } if(resourceIsReady) {//the resource is ready and this won't change from another thread std::promise<const ResourceType&> promise; std::shared_future<const ResourceType&> future = promise.get_future(); promise.set_value(mResources.at(sourceId).at(resourceId).get<ResourceType>()); return {resourceId, future}; } else { { std::lock_guard<std::recursive_mutex> lock(mResourceMutex); if(resourceLoadInProgress(sourceId, resourceId)) {//there is a future ready to piggyback on return AsyncResourceView<ResourceType>{resourceId, mAsyncProcesses.at(sourceId).at(resourceId).get<std::shared_future<const ResourceType&>>()}; } } //if we reached here, it means that there is no currently loaded resource and no process to load it, and this won't change, so it is safe to start loading {//other threads can still affect the storage on other resources though so we better lock std::lock_guard<std::recursive_mutex> lock(mResourceMutex); auto boundLaunch = std::bind(&ResourceProvider::loadResource<ResourceType>, this, sourceId, resourceId); std::shared_future<const ResourceType&> futureResource = mThreadPool.enqueue(std::move(boundLaunch), 0); auto emplaced = mAsyncProcesses.at(sourceId).emplace(resourceId, std::move(futureResource)); return AsyncResourceView<ResourceType>{resourceId, emplaced.first->second.template get<std::shared_future<const ResourceType&>>()}; } } } template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> ResourceProvider::asyncGet(const std::string& sourceId, const std::vector<std::string>& resourceIds) const { std::vector<AsyncResourceView<ResourceType>> result; for(const std::string& resourceId : resourceIds) result.emplace_back(asyncGet<ResourceType>(sourceId, resourceId)); return result; } template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> ResourceProvider::asyncGetAll(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); std::vector<std::string> idList = sourceEntry.listingFunction(sourceEntry.source); return asyncGet<ResourceType>(sourceId, idList); } #endif inline void ResourceProvider::markUnused(const std::string& sourceId, const std::string& resourceId) { const auto& sourceEntry = toSourceEntry(sourceId); #ifndef REX_DISABLE_ASYNC auto waitFunction = sourceEntry.waitFunction; auto asyncIter = mAsyncProcesses.at(sourceId).find(resourceId); if(asyncIter != mAsyncProcesses.at(sourceId).end()) waitFunction(asyncIter->second); { std::lock_guard<std::recursive_mutex> lock(mResourceMutex); mResources.at(sourceId).erase(resourceId); mAsyncProcesses.at(sourceId).erase(resourceId); } #else mResources.at(sourceId).erase(resourceId); #endif } inline void ResourceProvider::markAllUnused(const std::string& sourceId) { const auto& sourceEntry = toSourceEntry(sourceId); #ifndef REX_DISABLE_ASYNC waitForSourceAsync(sourceId); { std::lock_guard<std::recursive_mutex> lock(mResourceMutex); mResources.at(sourceId).clear(); mAsyncProcesses.at(sourceId).clear(); } #else mResources.at(sourceId).clear(); #endif } inline bool ResourceProvider::resourceReady(const std::string& sourceId, const std::string& resourceId) const { auto sourceIterator = mResources.find(sourceId); if(sourceIterator != mResources.end()) return sourceIterator->second.count(resourceId) != 0; return false; } inline bool ResourceProvider::resourceLoadInProgress(const std::string& sourceId, const std::string& resourceId) const { #ifndef REX_DISABLE_ASYNC auto sourceIterator = mAsyncProcesses.find(sourceId); if(sourceIterator != mAsyncProcesses.end()) return sourceIterator->second.count(resourceId); #endif return false; } template <typename ResourceType> const ResourceType& ResourceProvider::loadResource(const std::string& sourceId, const std::string& resourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); try { auto loadFunction = sourceEntry.loadingFunction.get<LoadingFunction<ResourceType>>(); auto resource = loadFunction(sourceEntry.source, resourceId); #ifndef REX_DISABLE_ASYNC { std::lock_guard<std::recursive_mutex> lock(mResourceMutex); auto emplaced = mResources.at(sourceId).emplace(resourceId, std::move(resource)); mAsyncProcesses.at(sourceId).erase(resourceId); return emplaced.first->second.template get<ResourceType>(); } #else auto emplaced = mResources.at(sourceId).emplace(resourceId, std::move(resource)); return emplaced.first->second.template get<ResourceType>(); #endif } catch(const std::exception& exception) { throw InvalidResourceException(exception.what()); } } inline void ResourceProvider::waitForSourceAsync(const std::string& sourceId) const { #ifndef REX_DISABLE_ASYNC auto sourceIterator = mSources.find(sourceId); if(sourceIterator != mSources.end()) { auto waitFunction = sourceIterator->second.waitFunction; for(auto& asyncIter : mAsyncProcesses.at(sourceId)) waitFunction(asyncIter.second); } #endif } inline const ResourceProvider::SourceEntry& ResourceProvider::toSourceEntry(const std::string& sourceId) const { auto sourceIterator = mSources.find(sourceId); if(sourceIterator != mSources.end()) { return sourceIterator->second; } else throw InvalidSourceException("trying to access source id " + sourceId + " which doesn't exist"); } } <commit_msg>mutex fix<commit_after>#pragma once #include <rex/config.hpp> #ifndef REX_DISABLE_ASYNC #include <mutex> #endif #include <unordered_map> #include <rex/thero.hpp> #include <rex/exceptions.hpp> #include <rex/exceptions.hpp> #include <rex/resourceview.hpp> #include <rex/sourceview.hpp> #ifndef REX_DISABLE_ASYNC #include <rex/asyncresourceview.hpp> #include <rex/threadpool.hpp> #endif namespace rex { class ResourceProvider { template<typename ResourceType> using LoadingFunction = ResourceType(*)(const th::Any&, const std::string&); using ListingFunction = std::vector<std::string>(*)(const th::Any&); using WaitFunction = void(*)(const th::Any&); struct SourceEntry { th::Any source; th::Any loadingFunction; ListingFunction listingFunction; WaitFunction waitFunction; std::type_index typeProvided; }; public: ResourceProvider(int32_t workerCount = 10); #ifndef REX_DISABLE_ASYNC ResourceProvider(const ResourceProvider& other) = delete; ResourceProvider& operator=(const ResourceProvider& other) = delete; ResourceProvider(ResourceProvider&& other); ResourceProvider& operator=(ResourceProvider&& other); #endif //sources template <typename SourceType> SourceView<SourceType> source(const std::string& sourceId) const; template <typename SourceType> SourceView<SourceType> addSource(const std::string& sourceId, SourceType source); std::vector<std::string> sources() const; bool removeSource(const std::string& sourceId); void clearSources(); //list std::vector<std::string> list(const std::string& sourceId) const; //sync get template <typename ResourceType> const ResourceType& get(const std::string& sourceId, const std::string& resourceId) const; template <typename ResourceType> std::vector<ResourceView<ResourceType>> get(const std::string& sourceId, const std::vector<std::string>& resourceIds) const; template <typename ResourceType> std::vector<ResourceView<ResourceType>> getAll(const std::string& sourceId) const; #ifndef REX_DISABLE_ASYNC //async get template <typename ResourceType> AsyncResourceView<ResourceType> asyncGet(const std::string& sourceId, const std::string& resourceId) const; template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> asyncGet(const std::string& sourceId, const std::vector<std::string>& resourceIds) const; template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> asyncGetAll(const std::string& sourceId) const; #endif //free void markUnused(const std::string& sourceId, const std::string& resourceId); void markAllUnused(const std::string& sourceId); private: bool resourceReady(const std::string& sourceId, const std::string& resourceId) const; bool resourceLoadInProgress(const std::string& sourceId, const std::string& resourceId) const; template <typename ResourceType> const ResourceType& loadResource(const std::string& sourceId, const std::string& resourceId) const; void waitForSourceAsync(const std::string& sourceId) const; const SourceEntry& toSourceEntry(const std::string& sourceId) const; std::unordered_map<std::string, SourceEntry> mSources; mutable std::unordered_map<std::string, std::unordered_map<std::string, th::Any>> mResources; #ifndef REX_DISABLE_ASYNC mutable std::unordered_map<std::string, std::unordered_map<std::string, th::Any>> mAsyncProcesses; mutable std::shared_ptr<std::recursive_mutex> mResourceMutex; mutable std::shared_ptr<ThreadPool> mThreadPool; #endif }; inline ResourceProvider::ResourceProvider(int32_t workerCount) #ifndef REX_DISABLE_ASYNC : mResourceMutex(std::make_shared<std::recursive_mutex>()), mThreadPool(std::make_shared<ThreadPool>(workerCount)) #endif { } #ifndef REX_DISABLE_ASYNC inline ResourceProvider::ResourceProvider(ResourceProvider&& other) { mSources = std::move(other.mSources); mResources = std::move(other.mResources); mAsyncProcesses = std::move(other.mAsyncProcesses); mResourceMutex = std::move(other.mResourceMutex); mThreadPool = std::move(mThreadPool); } inline ResourceProvider& ResourceProvider::operator=(ResourceProvider&& other) { mSources = std::move(other.mSources); mResources = std::move(other.mResources); mAsyncProcesses = std::move(other.mAsyncProcesses); mResourceMutex = std::move(other.mResourceMutex); mThreadPool = std::move(mThreadPool); return *this; } #endif template <typename SourceType> SourceView<SourceType> ResourceProvider::source(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); try { return SourceView<SourceType> { sourceId, sourceEntry.source.get<SourceType>() }; } catch(th::AnyTypeException) { throw InvalidSourceException("trying to access source id " + sourceId + " as the wrong type"); } } template <typename SourceType> SourceView<SourceType> ResourceProvider::addSource(const std::string& sourceId, SourceType source) { using ResourceType = decltype(source.load(std::string())); LoadingFunction<ResourceType> loadingFunction = [] (const th::Any& packedSource, const std::string& identifier) { return packedSource.get<SourceType>().load(identifier); }; ListingFunction listingFunction = [] (const th::Any& packedSource) { return packedSource.get<SourceType>().list(); }; WaitFunction waitFunction = [] (const th::Any& packedFuture) { #ifndef REX_DISABLE_ASYNC packedFuture.get<std::shared_future<const ResourceType&>>().wait(); #endif }; auto added = mSources.emplace(sourceId, SourceEntry{std::move(source), loadingFunction, listingFunction, waitFunction, typeid(ResourceType)}); mResources[sourceId]; #ifndef REX_DISABLE_ASYNC mAsyncProcesses[sourceId]; #endif if(added.second) return SourceView<SourceType> { sourceId, added.first->second.source.get<SourceType>() }; else throw InvalidSourceException("adding source id " + sourceId + " which is already added"); } inline std::vector<std::string> ResourceProvider::sources() const { std::vector<std::string> result; for(const auto& source : mSources) result.push_back(source.first); return result; } inline bool ResourceProvider::removeSource(const std::string& sourceId) { mResources.erase(sourceId); #ifndef REX_DISABLE_ASYNC mAsyncProcesses.erase(sourceId); #endif return mSources.erase(sourceId) != 0; } inline void ResourceProvider::clearSources() { mSources.clear(); mResources.clear(); #ifndef REX_DISABLE_ASYNC mAsyncProcesses.clear(); #endif } inline std::vector<std::string> ResourceProvider::list(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); return sourceEntry.listingFunction(sourceEntry.source); } template <typename ResourceType> const ResourceType& ResourceProvider::get(const std::string& sourceId, const std::string& resourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); const auto& source = sourceEntry.source; if(std::type_index(typeid(ResourceType)) != sourceEntry.typeProvided) throw InvalidSourceException("trying to access source id " + sourceId + " as the wrong type"); #ifndef REX_DISABLE_ASYNC std::shared_future<const ResourceType&> futureToWaitFor; { std::lock_guard<std::recursive_mutex> lock(*mResourceMutex); //there are three possible cases, and with the lock on, these won't change //1. it is already loaded, so just return it if(mResources.at(sourceId).count(resourceId) != 0) return mResources.at(sourceId).at(resourceId).get<ResourceType>(); //2. it is not loaded and no process is loading it if(mAsyncProcesses.at(sourceId).count(resourceId) == 0) return loadResource<ResourceType>(sourceId, resourceId); //3. it is not loaded and there is a process that loads it already futureToWaitFor = mAsyncProcesses.at(sourceId).at(resourceId).get<std::shared_future<const ResourceType&>>(); } futureToWaitFor.wait(); return futureToWaitFor.get(); #else //Without async, it is either loaded or not, so just return it or load-return it if(mResources.at(sourceId).count(resourceId) != 0) return mResources.at(sourceId).at(resourceId).get<ResourceType>(); else return loadResource<ResourceType>(sourceId, resourceId); #endif } template <typename ResourceType> std::vector<ResourceView<ResourceType>> ResourceProvider::get(const std::string& sourceId, const std::vector<std::string>& resourceIds) const { std::vector<ResourceView<ResourceType>> result; for(const std::string& resourceId : resourceIds) result.emplace_back(ResourceView<ResourceType>{resourceId, get<ResourceType>(sourceId, resourceId)}); return result; } template <typename ResourceType> std::vector<ResourceView<ResourceType>> ResourceProvider::getAll(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); std::vector<std::string> idList = sourceEntry.listingFunction(sourceEntry.source); return get<ResourceType>(sourceId, idList); } #ifndef REX_DISABLE_ASYNC template <typename ResourceType> AsyncResourceView<ResourceType> ResourceProvider::asyncGet(const std::string& sourceId, const std::string& resourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); if(std::type_index(typeid(ResourceType)) != sourceEntry.typeProvided) throw InvalidSourceException("trying to access source id " + sourceId + " as the wrong type"); bool resourceIsReady = false; { std::lock_guard<std::recursive_mutex> lock(*mResourceMutex); resourceIsReady = resourceReady(sourceId, resourceId); } if(resourceIsReady) {//the resource is ready and this won't change from another thread std::promise<const ResourceType&> promise; std::shared_future<const ResourceType&> future = promise.get_future(); promise.set_value(mResources.at(sourceId).at(resourceId).get<ResourceType>()); return {resourceId, future}; } else { { std::lock_guard<std::recursive_mutex> lock(*mResourceMutex); if(resourceLoadInProgress(sourceId, resourceId)) {//there is a future ready to piggyback on return AsyncResourceView<ResourceType>{resourceId, mAsyncProcesses.at(sourceId).at(resourceId).get<std::shared_future<const ResourceType&>>()}; } } //if we reached here, it means that there is no currently loaded resource and no process to load it, and this won't change, so it is safe to start loading {//other threads can still affect the storage on other resources though so we better lock std::lock_guard<std::recursive_mutex> lock(*mResourceMutex); auto boundLaunch = std::bind(&ResourceProvider::loadResource<ResourceType>, this, sourceId, resourceId); std::shared_future<const ResourceType&> futureResource = mThreadPool->enqueue(std::move(boundLaunch), 0); auto emplaced = mAsyncProcesses.at(sourceId).emplace(resourceId, std::move(futureResource)); return AsyncResourceView<ResourceType>{resourceId, emplaced.first->second.template get<std::shared_future<const ResourceType&>>()}; } } } template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> ResourceProvider::asyncGet(const std::string& sourceId, const std::vector<std::string>& resourceIds) const { std::vector<AsyncResourceView<ResourceType>> result; for(const std::string& resourceId : resourceIds) result.emplace_back(asyncGet<ResourceType>(sourceId, resourceId)); return result; } template <typename ResourceType> std::vector<AsyncResourceView<ResourceType>> ResourceProvider::asyncGetAll(const std::string& sourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); std::vector<std::string> idList = sourceEntry.listingFunction(sourceEntry.source); return asyncGet<ResourceType>(sourceId, idList); } #endif inline void ResourceProvider::markUnused(const std::string& sourceId, const std::string& resourceId) { const auto& sourceEntry = toSourceEntry(sourceId); #ifndef REX_DISABLE_ASYNC auto waitFunction = sourceEntry.waitFunction; auto asyncIter = mAsyncProcesses.at(sourceId).find(resourceId); if(asyncIter != mAsyncProcesses.at(sourceId).end()) waitFunction(asyncIter->second); { std::lock_guard<std::recursive_mutex> lock(*mResourceMutex); mResources.at(sourceId).erase(resourceId); mAsyncProcesses.at(sourceId).erase(resourceId); } #else mResources.at(sourceId).erase(resourceId); #endif } inline void ResourceProvider::markAllUnused(const std::string& sourceId) { const auto& sourceEntry = toSourceEntry(sourceId); #ifndef REX_DISABLE_ASYNC waitForSourceAsync(sourceId); { std::lock_guard<std::recursive_mutex> lock(*mResourceMutex); mResources.at(sourceId).clear(); mAsyncProcesses.at(sourceId).clear(); } #else mResources.at(sourceId).clear(); #endif } inline bool ResourceProvider::resourceReady(const std::string& sourceId, const std::string& resourceId) const { auto sourceIterator = mResources.find(sourceId); if(sourceIterator != mResources.end()) return sourceIterator->second.count(resourceId) != 0; return false; } inline bool ResourceProvider::resourceLoadInProgress(const std::string& sourceId, const std::string& resourceId) const { #ifndef REX_DISABLE_ASYNC auto sourceIterator = mAsyncProcesses.find(sourceId); if(sourceIterator != mAsyncProcesses.end()) return sourceIterator->second.count(resourceId); #endif return false; } template <typename ResourceType> const ResourceType& ResourceProvider::loadResource(const std::string& sourceId, const std::string& resourceId) const { const auto& sourceEntry = toSourceEntry(sourceId); try { auto loadFunction = sourceEntry.loadingFunction.get<LoadingFunction<ResourceType>>(); auto resource = loadFunction(sourceEntry.source, resourceId); #ifndef REX_DISABLE_ASYNC { std::lock_guard<std::recursive_mutex> lock(*mResourceMutex); auto emplaced = mResources.at(sourceId).emplace(resourceId, std::move(resource)); mAsyncProcesses.at(sourceId).erase(resourceId); return emplaced.first->second.template get<ResourceType>(); } #else auto emplaced = mResources.at(sourceId).emplace(resourceId, std::move(resource)); return emplaced.first->second.template get<ResourceType>(); #endif } catch(const std::exception& exception) { throw InvalidResourceException(exception.what()); } } inline void ResourceProvider::waitForSourceAsync(const std::string& sourceId) const { #ifndef REX_DISABLE_ASYNC auto sourceIterator = mSources.find(sourceId); if(sourceIterator != mSources.end()) { auto waitFunction = sourceIterator->second.waitFunction; for(auto& asyncIter : mAsyncProcesses.at(sourceId)) waitFunction(asyncIter.second); } #endif } inline const ResourceProvider::SourceEntry& ResourceProvider::toSourceEntry(const std::string& sourceId) const { auto sourceIterator = mSources.find(sourceId); if(sourceIterator != mSources.end()) { return sourceIterator->second; } else throw InvalidSourceException("trying to access source id " + sourceId + " which doesn't exist"); } } <|endoftext|>
<commit_before>#ifndef RFR_BINARY_NODES_HPP #define RFR_BINARY_NODES_HPP #include <vector> #include <deque> #include <array> #include <tuple> #include <sstream> #include <algorithm> #include <random> #include "rfr/data_containers/data_container.hpp" #include "rfr/data_containers/data_container_utils.hpp" #include "rfr/nodes/temporary_node.hpp" #include "rfr/util.hpp" #include "rfr/splits/split_base.hpp" #include "cereal/cereal.hpp" #include <cereal/types/vector.hpp> #include <cereal/types/array.hpp> #include <iostream> namespace rfr{ namespace nodes{ template <int k, typename split_type, typename num_t = float, typename response_t = float, typename index_t = unsigned int, typename rng_t = std::default_random_engine> class k_ary_node_minimal{ protected: index_t parent_index; // for leaf nodes rfr::util::weighted_running_statistics<num_t> response_stat; //TODO: needs to be serialized! // for internal_nodes std::array<index_t, k> children; std::array<num_t, k> split_fractions; split_type split; public: /* serialize function for saving forests */ template<class Archive> void serialize(Archive & archive) { archive( parent_index, children, split_fractions, split); } /** \brief If the temporary node should be split further, this member turns this node into an internal node. * * * \param tmp_node a temporary_node struct containing all the important information. It is not changed in this function. * \param data a refernce to the data object that is used * \param features_to_try vector of allowed features to be used for this split * \param num_nodes number of already created nodes * \param tmp_nodes a deque instance containing all temporary nodes that still have to be checked * \param rng a RNG instance * * \return num_t the loss of the split */ num_t make_internal_node(const rfr::nodes::temporary_node<num_t, response_t, index_t> &tmp_node, const rfr::data_containers::base<num_t, response_t, index_t> &data, std::vector<index_t> &features_to_try, index_t num_nodes, std::deque<rfr::nodes::temporary_node<num_t, response_t, index_t> > &tmp_nodes, rng_t &rng){ parent_index = tmp_node.parent_index; std::array<typename std::vector<rfr::splits::data_info_t<num_t, response_t, index_t> >::iterator, k+1> split_indices_it; num_t best_loss = split.find_best_split(data, features_to_try, tmp_node.begin, tmp_node.end, split_indices_it,rng); //check if a split was found // note: if the number of features to try is too small, there is a chance that the data cannot be split any further if (best_loss < std::numeric_limits<num_t>::infinity()){ // create a tmp node for each child num_t total_weight = 0; for (index_t i = 0; i < k; i++){ tmp_nodes.emplace_back(num_nodes+i, tmp_node.node_index, tmp_node.node_level+1, split_indices_it[i], split_indices_it[i+1]); split_fractions[i]=tmp_nodes.back().total_weight(); total_weight += split_fractions[i]; children[i] = num_nodes + i; } for (auto &sf: split_fractions) sf /= total_weight; } else make_leaf_node(tmp_node, data); return(best_loss); } /** \brief turns this node into a leaf node based on a temporary node. * * \param tmp_node the internal representation for a temporary node. * \param data a data container instance */ void make_leaf_node(const rfr::nodes::temporary_node<num_t, response_t, index_t> &tmp_node, const rfr::data_containers::base<num_t, response_t, index_t> &data){ parent_index = tmp_node.parent_index; children.fill(0); split_fractions.fill(NAN); for (auto it = tmp_node.begin; it != tmp_node.end; ++it){ push_response_value((*it).response, (*it).weight); } } /* \brief function to check if a feature vector can be splitted */ bool can_be_split(const std::vector<num_t> &feature_vector) const {return(split.can_be_split(feature_vector));} /** \brief returns the index of the child into which the provided sample falls * * \param feature_vector a feature vector of the appropriate size (not checked!) * * \return index_t index of the child */ index_t falls_into_child(const std::vector<num_t> &feature_vector) const { if (is_a_leaf()) return(0); return(children[split(feature_vector)]); } /** \brief adds an observation to the leaf node * * This function can be used for pseudo updates of a tree by * simply adding observations into the corresponding leaf */ virtual void push_response_value ( response_t r, num_t w){ response_stat.push(r,w); } /** \brief removes an observation from the leaf node * * This function can be used for pseudo updates of a tree by * simply removing observations from the corresponding leaf */ void pop_repsonse_value (response_t r, num_t w){ response_stat.pop(r,w); } /** \brief helper function for the fANOVA * * See description of rfr::splits::binary_split_one_feature_rss_loss. */ std::array<std::vector< std::vector<num_t> >, 2> compute_subspaces( std::vector< std::vector<num_t> > &subspace) const { return(split.compute_subspaces(subspace)); } /* \brief returns a running_statistics instance for computations of mean, variance, etc... * * See description of rfr::util::weighted_running_statistics for more information */ rfr::util::weighted_running_statistics<num_t> const & leaf_statistic() const { return (response_stat);} /** \brief to test whether this node is a leaf */ bool is_a_leaf() const {return(children[0] == 0);} /** \brief get the index of the node's parent */ index_t parent() const {return(parent_index);} /** \brief get indices of all children*/ std::array<index_t, k> get_children() const {return(children);} index_t get_child_index (index_t idx) const {return(children[idx]);}; std::array<num_t, k> get_split_fractions() const {return(split_fractions);} num_t get_split_fraction (index_t idx) const {return(split_fractions[idx]);}; split_type get_split() const {return(split);} /** \brief prints out some basic information about the node*/ virtual void print_info() const { if (is_a_leaf()){ std::cout << "N = "<<response_stat.sum_of_weights()<<std::endl; std::cout <<"mean = "<< response_stat.mean()<<std::endl; std::cout <<"variance = " << response_stat.variance_unbiased_frequency()<<std::endl; } else{ std::cout<<"status: internal node\n"; std::cout<<"children: "; for (auto i=0; i < k; i++) std::cout<<children[i]<<" "; std::cout<<std::endl; } } /** \brief generates a label for the node to be used in the LaTeX visualization*/ virtual std::string latex_representation( int my_index) const { std::stringstream str; if (is_a_leaf()){ str << "{i = " << my_index << ": "; str << "N = "<<response_stat.sum_of_weights(); str <<", mean = "<< response_stat.mean(); str <<", variance = " << response_stat.variance_unbiased_frequency()<<"}"; } else{ str << "{ i = " << my_index << "\\nodepart{two} {"; str << split.latex_representation() << "}},rectangle split,rectangle split parts=2,draw"; } return(str.str()); } }; /** \brief The node class for regular k-ary trees. * * In a regular k-ary tree, every node has either zero (a leaf) or exactly k-children (an internal node). * In this case, one can try to gain some speed by replacing variable length std::vectors by std::arrays. * */ template <int k, typename split_type, typename num_t = float, typename response_t = float, typename index_t = unsigned int, typename rng_t = std::default_random_engine> class k_ary_node_full: public k_ary_node_minimal<k, split_type, num_t, response_t, index_t, rng_t>{ protected: // additional info for leaf nodes std::vector<response_t> response_values; std::vector<num_t> response_weights; typedef k_ary_node_minimal<k, split_type, num_t, response_t, index_t, rng_t> super; public: /* serialize function for saving forests */ template<class Archive> void serialize(Archive & archive) { archive(response_values, response_weights); super::serialize(archive); } /** \brief adds an observation to the leaf node * * This function can be used for pseudo updates of a tree by * simply adding observations into the corresponding leaf */ virtual void push_response_value ( response_t r, num_t w){ super::push_response_value(r,w); response_values.push_back(r); response_weights.push_back(w); } /** \brief removes the last added observation from the leaf node * * This function can be used for pseudo updates of a tree by * simply adding observations into the corresponding leaf * * \param r ignored * \param w ignored * */ virtual void pop_response_value (response_t r, num_t w){ super::push_response_value(response_values.back(), response_weights.back()); response_values.pop_back(); response_weights.pop_back(); } /** \brief get reference to the response values*/ std::vector<response_t> const &responses () const { return( (std::vector<response_t> const &) response_values);} /** \brief get reference to the response values*/ std::vector<num_t> const &weights () const { return( (std::vector<num_t> const &) response_weights);} /** \brief prints out some basic information about the node*/ virtual void print_info() const { super::print_info(); if (super::is_a_leaf()){ rfr::print_vector(response_values); } } }; }} // namespace rfr::nodes #endif <commit_msg>added virtual destructors to node classes to remove warnings<commit_after>#ifndef RFR_BINARY_NODES_HPP #define RFR_BINARY_NODES_HPP #include <vector> #include <deque> #include <array> #include <tuple> #include <sstream> #include <algorithm> #include <random> #include "rfr/data_containers/data_container.hpp" #include "rfr/data_containers/data_container_utils.hpp" #include "rfr/nodes/temporary_node.hpp" #include "rfr/util.hpp" #include "rfr/splits/split_base.hpp" #include "cereal/cereal.hpp" #include <cereal/types/vector.hpp> #include <cereal/types/array.hpp> #include <iostream> namespace rfr{ namespace nodes{ template <int k, typename split_type, typename num_t = float, typename response_t = float, typename index_t = unsigned int, typename rng_t = std::default_random_engine> class k_ary_node_minimal{ protected: index_t parent_index; // for leaf nodes rfr::util::weighted_running_statistics<num_t> response_stat; //TODO: needs to be serialized! // for internal_nodes std::array<index_t, k> children; std::array<num_t, k> split_fractions; split_type split; public: virtual ~k_ary_node_minimal (); /* serialize function for saving forests */ template<class Archive> void serialize(Archive & archive) { archive( parent_index, children, split_fractions, split); } /** \brief If the temporary node should be split further, this member turns this node into an internal node. * * * \param tmp_node a temporary_node struct containing all the important information. It is not changed in this function. * \param data a refernce to the data object that is used * \param features_to_try vector of allowed features to be used for this split * \param num_nodes number of already created nodes * \param tmp_nodes a deque instance containing all temporary nodes that still have to be checked * \param rng a RNG instance * * \return num_t the loss of the split */ num_t make_internal_node(const rfr::nodes::temporary_node<num_t, response_t, index_t> &tmp_node, const rfr::data_containers::base<num_t, response_t, index_t> &data, std::vector<index_t> &features_to_try, index_t num_nodes, std::deque<rfr::nodes::temporary_node<num_t, response_t, index_t> > &tmp_nodes, rng_t &rng){ parent_index = tmp_node.parent_index; std::array<typename std::vector<rfr::splits::data_info_t<num_t, response_t, index_t> >::iterator, k+1> split_indices_it; num_t best_loss = split.find_best_split(data, features_to_try, tmp_node.begin, tmp_node.end, split_indices_it,rng); //check if a split was found // note: if the number of features to try is too small, there is a chance that the data cannot be split any further if (best_loss < std::numeric_limits<num_t>::infinity()){ // create a tmp node for each child num_t total_weight = 0; for (index_t i = 0; i < k; i++){ tmp_nodes.emplace_back(num_nodes+i, tmp_node.node_index, tmp_node.node_level+1, split_indices_it[i], split_indices_it[i+1]); split_fractions[i]=tmp_nodes.back().total_weight(); total_weight += split_fractions[i]; children[i] = num_nodes + i; } for (auto &sf: split_fractions) sf /= total_weight; } else make_leaf_node(tmp_node, data); return(best_loss); } /** \brief turns this node into a leaf node based on a temporary node. * * \param tmp_node the internal representation for a temporary node. * \param data a data container instance */ void make_leaf_node(const rfr::nodes::temporary_node<num_t, response_t, index_t> &tmp_node, const rfr::data_containers::base<num_t, response_t, index_t> &data){ parent_index = tmp_node.parent_index; children.fill(0); split_fractions.fill(NAN); for (auto it = tmp_node.begin; it != tmp_node.end; ++it){ push_response_value((*it).response, (*it).weight); } } /* \brief function to check if a feature vector can be splitted */ bool can_be_split(const std::vector<num_t> &feature_vector) const {return(split.can_be_split(feature_vector));} /** \brief returns the index of the child into which the provided sample falls * * \param feature_vector a feature vector of the appropriate size (not checked!) * * \return index_t index of the child */ index_t falls_into_child(const std::vector<num_t> &feature_vector) const { if (is_a_leaf()) return(0); return(children[split(feature_vector)]); } /** \brief adds an observation to the leaf node * * This function can be used for pseudo updates of a tree by * simply adding observations into the corresponding leaf */ virtual void push_response_value ( response_t r, num_t w){ response_stat.push(r,w); } /** \brief removes an observation from the leaf node * * This function can be used for pseudo updates of a tree by * simply removing observations from the corresponding leaf */ void pop_repsonse_value (response_t r, num_t w){ response_stat.pop(r,w); } /** \brief helper function for the fANOVA * * See description of rfr::splits::binary_split_one_feature_rss_loss. */ std::array<std::vector< std::vector<num_t> >, 2> compute_subspaces( std::vector< std::vector<num_t> > &subspace) const { return(split.compute_subspaces(subspace)); } /* \brief returns a running_statistics instance for computations of mean, variance, etc... * * See description of rfr::util::weighted_running_statistics for more information */ rfr::util::weighted_running_statistics<num_t> const & leaf_statistic() const { return (response_stat);} /** \brief to test whether this node is a leaf */ bool is_a_leaf() const {return(children[0] == 0);} /** \brief get the index of the node's parent */ index_t parent() const {return(parent_index);} /** \brief get indices of all children*/ std::array<index_t, k> get_children() const {return(children);} index_t get_child_index (index_t idx) const {return(children[idx]);}; std::array<num_t, k> get_split_fractions() const {return(split_fractions);} num_t get_split_fraction (index_t idx) const {return(split_fractions[idx]);}; split_type get_split() const {return(split);} /** \brief prints out some basic information about the node*/ virtual void print_info() const { if (is_a_leaf()){ std::cout << "N = "<<response_stat.sum_of_weights()<<std::endl; std::cout <<"mean = "<< response_stat.mean()<<std::endl; std::cout <<"variance = " << response_stat.variance_unbiased_frequency()<<std::endl; } else{ std::cout<<"status: internal node\n"; std::cout<<"children: "; for (auto i=0; i < k; i++) std::cout<<children[i]<<" "; std::cout<<std::endl; } } /** \brief generates a label for the node to be used in the LaTeX visualization*/ virtual std::string latex_representation( int my_index) const { std::stringstream str; if (is_a_leaf()){ str << "{i = " << my_index << ": "; str << "N = "<<response_stat.sum_of_weights(); str <<", mean = "<< response_stat.mean(); str <<", variance = " << response_stat.variance_unbiased_frequency()<<"}"; } else{ str << "{ i = " << my_index << "\\nodepart{two} {"; str << split.latex_representation() << "}},rectangle split,rectangle split parts=2,draw"; } return(str.str()); } }; /** \brief The node class for regular k-ary trees. * * In a regular k-ary tree, every node has either zero (a leaf) or exactly k-children (an internal node). * In this case, one can try to gain some speed by replacing variable length std::vectors by std::arrays. * */ template <int k, typename split_type, typename num_t = float, typename response_t = float, typename index_t = unsigned int, typename rng_t = std::default_random_engine> class k_ary_node_full: public k_ary_node_minimal<k, split_type, num_t, response_t, index_t, rng_t>{ protected: // additional info for leaf nodes std::vector<response_t> response_values; std::vector<num_t> response_weights; typedef k_ary_node_minimal<k, split_type, num_t, response_t, index_t, rng_t> super; public: virtual ~k_ary_node_full (); /* serialize function for saving forests */ template<class Archive> void serialize(Archive & archive) { archive(response_values, response_weights); super::serialize(archive); } /** \brief adds an observation to the leaf node * * This function can be used for pseudo updates of a tree by * simply adding observations into the corresponding leaf */ virtual void push_response_value ( response_t r, num_t w){ super::push_response_value(r,w); response_values.push_back(r); response_weights.push_back(w); } /** \brief removes the last added observation from the leaf node * * This function can be used for pseudo updates of a tree by * simply adding observations into the corresponding leaf * * \param r ignored * \param w ignored * */ virtual void pop_response_value (response_t r, num_t w){ super::push_response_value(response_values.back(), response_weights.back()); response_values.pop_back(); response_weights.pop_back(); } /** \brief get reference to the response values*/ std::vector<response_t> const &responses () const { return( (std::vector<response_t> const &) response_values);} /** \brief get reference to the response values*/ std::vector<num_t> const &weights () const { return( (std::vector<num_t> const &) response_weights);} /** \brief prints out some basic information about the node*/ virtual void print_info() const { super::print_info(); if (super::is_a_leaf()){ rfr::print_vector(response_values); } } }; }} // namespace rfr::nodes #endif <|endoftext|>
<commit_before> #include "SiconosConfig.h" #include "MechanicsIO.hpp" #define DUMMY(X, Y) class X : public Y {} #undef BULLET_CLASSES #undef OCC_CLASSES #undef MECHANISMS_CLASSES #include <BodyDS.hpp> #define XBULLET_CLASSES() \ REGISTER(BulletR) #ifdef SICONOS_HAVE_BULLET #include <BulletR.hpp> #else #include <NewtonEulerDS.hpp> #include <NewtonEulerFrom3DLocalFrameR.hpp> #include <SpaceFilter.hpp> DUMMY(BulletR, NewtonEulerFrom3DLocalFrameR); #endif #define OCC_CLASSES() \ REGISTER(OccBody) \ REGISTER(OccR) #ifdef SICONOS_HAVE_OCC #include <OccBody.hpp> #include <OccR.hpp> #else #include <NewtonEulerDS.hpp> #include <NewtonEulerFrom3DLocalFrameR.hpp> DUMMY(OccBody, NewtonEulerDS); DUMMY(OccR, NewtonEulerFrom3DLocalFrameR); #endif #define MECHANISMS_CLASSES() \ REGISTER(MBTB_FC3DContactRelation) \ REGISTER(MBTB_ContactRelation) #ifdef HAVE_MECHANISMS #include <MBTB_FC3DContactRelation.hpp> #include <MBTB_ContactRelation.hpp> #else #include <NewtonEulerFrom3DLocalFrameR.hpp> #include <NewtonEulerFrom1DLocalFrameR.hpp> DUMMY(MBTB_FC3DContactRelation, NewtonEulerFrom3DLocalFrameR); DUMMY(MBTB_ContactRelation, NewtonEulerFrom1DLocalFrameR); #endif #define VISITOR_CLASSES() \ REGISTER(DynamicalSystem) \ REGISTER(LagrangianDS) \ REGISTER(NewtonEulerDS) \ REGISTER(LagrangianR) \ REGISTER(Disk) \ REGISTER(Circle) \ REGISTER(NewtonEulerFrom1DLocalFrameR) \ REGISTER(NewtonEulerFrom3DLocalFrameR) \ REGISTER(PivotJointR) \ REGISTER(KneeJointR) \ REGISTER(PrismaticJointR) \ REGISTER(BodyDS) \ OCC_CLASSES() \ XBULLET_CLASSES() \ MECHANISMS_CLASSES() \ REGISTER(NewtonEulerR) #undef SICONOS_VISITABLES #define SICONOS_VISITABLES() VISITOR_CLASSES() #include <BlockVector.hpp> #include <Question.hpp> #include <LagrangianDS.hpp> #include <NewtonEulerDS.hpp> /* ... */ /* to be fixed: forward mess with mpl::is_base_of who needs fully * declared classes */ #include <SiconosKernel.hpp> /* Mechanics visitables bodies */ #include "Circle.hpp" #include "Disk.hpp" #include "DiskDiskR.hpp" #include "CircleCircleR.hpp" #include "DiskPlanR.hpp" #include "DiskMovingPlanR.hpp" #include "SphereLDS.hpp" #include "SphereLDSSphereLDSR.hpp" #include "SphereNEDSSphereNEDSR.hpp" #include "SphereLDSPlanR.hpp" #include "SphereNEDS.hpp" #include "SphereNEDSPlanR.hpp" #include "ExternalBody.hpp" #include <PivotJointR.hpp> #include <KneeJointR.hpp> #include <PrismaticJointR.hpp> #include <VisitorMaker.hpp> //#define DEBUG_MESSAGES 1 #include <debug.h> using namespace Experimental; struct GetPosition : public SiconosVisitor { SP::SiconosVector result; template<typename T> void operator()(const T& ds) { result.reset(new SiconosVector(1+ds.q()->size())); result->setValue(0, ds.number()); result->setBlock(1, *ds.q()); } }; struct GetVelocity : public SiconosVisitor { SP::SiconosVector result; template<typename T> void operator()(const T& ds) { result.reset(new SiconosVector(1+ds.velocity()->size())); result->setValue(0, ds.number()); result->setBlock(1, *ds.velocity()); } }; struct ForMu : public Question<double> { ANSWER(NewtonImpactFrictionNSL, mu()); ANSWER_V_NOUSING(NewtonImpactNSL, 0.); }; /* template partial specilization is not possible inside struct, so we * need an helper function */ template<typename T> void contactPointProcess(SiconosVector& answer, const Interaction& inter, const T& rel) { answer.resize(14); const SiconosVector& posa = *rel.pc1(); const SiconosVector& posb = *rel.pc2(); const SiconosVector& nc = *rel.nc(); const SimpleMatrix& jachqT = *rel.jachqT(); double id = inter.number(); double mu = ask<ForMu>(*inter.nonSmoothLaw()); SiconosVector cf(jachqT.size(1)); prod(*inter.lambda(1), jachqT, cf, true); answer.setValue(0, mu); DEBUG_PRINTF("posa(0)=%g\n", posa(0)); DEBUG_PRINTF("posa(1)=%g\n", posa(1)); DEBUG_PRINTF("posa(2)=%g\n", posa(2)); answer.setValue(1, posa(0)); answer.setValue(2, posa(1)); answer.setValue(3, posa(2)); answer.setValue(4, posb(0)); answer.setValue(5, posb(1)); answer.setValue(6, posb(2)); answer.setValue(7, nc(0)); answer.setValue(8, nc(1)); answer.setValue(9, nc(2)); answer.setValue(10, cf(0)); answer.setValue(11, cf(1)); answer.setValue(12, cf(2)); answer.setValue(13, id); }; template<> void contactPointProcess<PivotJointR>(SiconosVector& answer, const Interaction& inter, const PivotJointR& rel) { }; template<> void contactPointProcess<KneeJointR>(SiconosVector& answer, const Interaction& inter, const KneeJointR& rel) { }; template<> void contactPointProcess<PrismaticJointR>(SiconosVector& answer, const Interaction& inter, const PrismaticJointR& rel) { }; struct ContactPointVisitor : public SiconosVisitor { SP::Interaction inter; SiconosVector answer; template<typename T> void operator()(const T& rel) { contactPointProcess<T>(answer, *inter, rel); } }; struct ContactPointDomainVisitor : public SiconosVisitor { SP::Interaction inter; SiconosVector answer; template<typename T> void operator()(const T& rel) { } }; template<> void ContactPointDomainVisitor::operator()(const BulletR& rel) { answer.resize(2); /* * TODO: contact point domain coloring (e.g. based on broadphase). * currently, domain = (x>0):1?0 */ answer.setValue(0, rel.pc1()->getValue(0) > 0); answer.setValue(1, inter->number()); } template<typename T, typename G> SP::SimpleMatrix MechanicsIO::visitAllVerticesForVector(const G& graph) const { SP::SimpleMatrix result(new SimpleMatrix()); typename G::VIterator vi, viend; unsigned int current_row; for(current_row=0,std11::tie(vi,viend)=graph.vertices(); vi!=viend; ++vi, ++current_row) { T getter; graph.bundle(*vi)->accept(getter); const SiconosVector& data = *getter.result; result->resize(current_row+1, data.size()); result->setRow(current_row, data); } return result; } template<typename T, typename G> SP::SiconosVector MechanicsIO::visitAllVerticesForDouble(const G& graph) const { SP::SiconosVector result(new SiconosVector(graph.vertices_number())); typename G::VIterator vi, viend; unsigned int current_row; for(current_row=0,std11::tie(vi,viend)=graph.vertices(); vi!=viend; ++vi, ++current_row) { T getter; graph.bundle(*vi)->accept(getter); result->setValue(current_row, *getter.result); } return result; } SP::SimpleMatrix MechanicsIO::positions(const NonSmoothDynamicalSystem& nsds) const { typedef Visitor < Classes < LagrangianDS, NewtonEulerDS >, GetPosition >::Make Getter; return visitAllVerticesForVector<Getter> (*(nsds.topology()->dSG(0))); }; SP::SimpleMatrix MechanicsIO::velocities(const NonSmoothDynamicalSystem& nsds) const { typedef Visitor < Classes < LagrangianDS, NewtonEulerDS >, GetVelocity>::Make Getter; return visitAllVerticesForVector<Getter> (*nsds.topology()->dSG(0)); } SP::SimpleMatrix MechanicsIO::contactPoints(const NonSmoothDynamicalSystem& nsds, unsigned int index_set) const { SP::SimpleMatrix result(new SimpleMatrix()); InteractionsGraph::VIterator vi, viend; if (nsds.topology()->numberOfIndexSet() > 0) { InteractionsGraph& graph = *nsds.topology()->indexSet(index_set); unsigned int current_row; result->resize(graph.vertices_number(), 14); for(current_row=0, std11::tie(vi,viend) = graph.vertices(); vi!=viend; ++vi, ++current_row) { DEBUG_PRINTF("process interaction : %p\n", &*graph.bundle(*vi)); typedef Visitor < Classes < NewtonEulerFrom1DLocalFrameR, NewtonEulerFrom3DLocalFrameR, PrismaticJointR, KneeJointR, PivotJointR>, ContactPointVisitor>::Make ContactPointInspector; ContactPointInspector inspector; inspector.inter = graph.bundle(*vi); graph.bundle(*vi)->relation()->accept(inspector); const SiconosVector& data = inspector.answer; if (data.size() == 14) result->setRow(current_row, data); } } return result; } SP::SimpleMatrix MechanicsIO::domains(const NonSmoothDynamicalSystem& nsds) const { SP::SimpleMatrix result(new SimpleMatrix()); InteractionsGraph::VIterator vi, viend; if (nsds.topology()->numberOfIndexSet() > 0) { InteractionsGraph& graph = *nsds.topology()->indexSet(1); unsigned int current_row; result->resize(graph.vertices_number(), 2); for(current_row=0, std11::tie(vi,viend) = graph.vertices(); vi!=viend; ++vi, ++current_row) { DEBUG_PRINTF("process interaction : %p\n", &*graph.bundle(*vi)); typedef Visitor < Classes < NewtonEulerFrom1DLocalFrameR, NewtonEulerFrom3DLocalFrameR, PrismaticJointR, KneeJointR, PivotJointR>, ContactPointDomainVisitor>::Make DomainInspector; DomainInspector inspector; inspector.inter = graph.bundle(*vi); graph.bundle(*vi)->relation()->accept(inspector); const SiconosVector& data = inspector.answer; if (data.size() == 2) result->setRow(current_row, data); } } return result; } <commit_msg>[io] do not output joints as rows in the contact points matrix<commit_after> #include "SiconosConfig.h" #include "MechanicsIO.hpp" #define DUMMY(X, Y) class X : public Y {} #undef BULLET_CLASSES #undef OCC_CLASSES #undef MECHANISMS_CLASSES #include <BodyDS.hpp> #define XBULLET_CLASSES() \ REGISTER(BulletR) #ifdef SICONOS_HAVE_BULLET #include <BulletR.hpp> #else #include <NewtonEulerDS.hpp> #include <NewtonEulerFrom3DLocalFrameR.hpp> #include <SpaceFilter.hpp> DUMMY(BulletR, NewtonEulerFrom3DLocalFrameR); #endif #define OCC_CLASSES() \ REGISTER(OccBody) \ REGISTER(OccR) #ifdef SICONOS_HAVE_OCC #include <OccBody.hpp> #include <OccR.hpp> #else #include <NewtonEulerDS.hpp> #include <NewtonEulerFrom3DLocalFrameR.hpp> DUMMY(OccBody, NewtonEulerDS); DUMMY(OccR, NewtonEulerFrom3DLocalFrameR); #endif #define MECHANISMS_CLASSES() \ REGISTER(MBTB_FC3DContactRelation) \ REGISTER(MBTB_ContactRelation) #ifdef HAVE_MECHANISMS #include <MBTB_FC3DContactRelation.hpp> #include <MBTB_ContactRelation.hpp> #else #include <NewtonEulerFrom3DLocalFrameR.hpp> #include <NewtonEulerFrom1DLocalFrameR.hpp> DUMMY(MBTB_FC3DContactRelation, NewtonEulerFrom3DLocalFrameR); DUMMY(MBTB_ContactRelation, NewtonEulerFrom1DLocalFrameR); #endif #define VISITOR_CLASSES() \ REGISTER(DynamicalSystem) \ REGISTER(LagrangianDS) \ REGISTER(NewtonEulerDS) \ REGISTER(LagrangianR) \ REGISTER(Disk) \ REGISTER(Circle) \ REGISTER(NewtonEulerFrom1DLocalFrameR) \ REGISTER(NewtonEulerFrom3DLocalFrameR) \ REGISTER(PivotJointR) \ REGISTER(KneeJointR) \ REGISTER(PrismaticJointR) \ REGISTER(BodyDS) \ OCC_CLASSES() \ XBULLET_CLASSES() \ MECHANISMS_CLASSES() \ REGISTER(NewtonEulerR) #undef SICONOS_VISITABLES #define SICONOS_VISITABLES() VISITOR_CLASSES() #include <BlockVector.hpp> #include <Question.hpp> #include <LagrangianDS.hpp> #include <NewtonEulerDS.hpp> /* ... */ /* to be fixed: forward mess with mpl::is_base_of who needs fully * declared classes */ #include <SiconosKernel.hpp> /* Mechanics visitables bodies */ #include "Circle.hpp" #include "Disk.hpp" #include "DiskDiskR.hpp" #include "CircleCircleR.hpp" #include "DiskPlanR.hpp" #include "DiskMovingPlanR.hpp" #include "SphereLDS.hpp" #include "SphereLDSSphereLDSR.hpp" #include "SphereNEDSSphereNEDSR.hpp" #include "SphereLDSPlanR.hpp" #include "SphereNEDS.hpp" #include "SphereNEDSPlanR.hpp" #include "ExternalBody.hpp" #include <PivotJointR.hpp> #include <KneeJointR.hpp> #include <PrismaticJointR.hpp> #include <VisitorMaker.hpp> //#define DEBUG_MESSAGES 1 #include <debug.h> using namespace Experimental; struct GetPosition : public SiconosVisitor { SP::SiconosVector result; template<typename T> void operator()(const T& ds) { result.reset(new SiconosVector(1+ds.q()->size())); result->setValue(0, ds.number()); result->setBlock(1, *ds.q()); } }; struct GetVelocity : public SiconosVisitor { SP::SiconosVector result; template<typename T> void operator()(const T& ds) { result.reset(new SiconosVector(1+ds.velocity()->size())); result->setValue(0, ds.number()); result->setBlock(1, *ds.velocity()); } }; struct ForMu : public Question<double> { ANSWER(NewtonImpactFrictionNSL, mu()); ANSWER_V_NOUSING(NewtonImpactNSL, 0.); }; /* template partial specilization is not possible inside struct, so we * need an helper function */ template<typename T> void contactPointProcess(SiconosVector& answer, const Interaction& inter, const T& rel) { answer.resize(14); const SiconosVector& posa = *rel.pc1(); const SiconosVector& posb = *rel.pc2(); const SiconosVector& nc = *rel.nc(); const SimpleMatrix& jachqT = *rel.jachqT(); double id = inter.number(); double mu = ask<ForMu>(*inter.nonSmoothLaw()); SiconosVector cf(jachqT.size(1)); prod(*inter.lambda(1), jachqT, cf, true); answer.setValue(0, mu); DEBUG_PRINTF("posa(0)=%g\n", posa(0)); DEBUG_PRINTF("posa(1)=%g\n", posa(1)); DEBUG_PRINTF("posa(2)=%g\n", posa(2)); answer.setValue(1, posa(0)); answer.setValue(2, posa(1)); answer.setValue(3, posa(2)); answer.setValue(4, posb(0)); answer.setValue(5, posb(1)); answer.setValue(6, posb(2)); answer.setValue(7, nc(0)); answer.setValue(8, nc(1)); answer.setValue(9, nc(2)); answer.setValue(10, cf(0)); answer.setValue(11, cf(1)); answer.setValue(12, cf(2)); answer.setValue(13, id); }; template<> void contactPointProcess<PivotJointR>(SiconosVector& answer, const Interaction& inter, const PivotJointR& rel) { }; template<> void contactPointProcess<KneeJointR>(SiconosVector& answer, const Interaction& inter, const KneeJointR& rel) { }; template<> void contactPointProcess<PrismaticJointR>(SiconosVector& answer, const Interaction& inter, const PrismaticJointR& rel) { }; struct ContactPointVisitor : public SiconosVisitor { SP::Interaction inter; SiconosVector answer; template<typename T> void operator()(const T& rel) { contactPointProcess<T>(answer, *inter, rel); } }; struct ContactPointDomainVisitor : public SiconosVisitor { SP::Interaction inter; SiconosVector answer; template<typename T> void operator()(const T& rel) { } }; template<> void ContactPointDomainVisitor::operator()(const BulletR& rel) { answer.resize(2); /* * TODO: contact point domain coloring (e.g. based on broadphase). * currently, domain = (x>0):1?0 */ answer.setValue(0, rel.pc1()->getValue(0) > 0); answer.setValue(1, inter->number()); } template<typename T, typename G> SP::SimpleMatrix MechanicsIO::visitAllVerticesForVector(const G& graph) const { SP::SimpleMatrix result(new SimpleMatrix()); typename G::VIterator vi, viend; unsigned int current_row; for(current_row=0,std11::tie(vi,viend)=graph.vertices(); vi!=viend; ++vi, ++current_row) { T getter; graph.bundle(*vi)->accept(getter); const SiconosVector& data = *getter.result; result->resize(current_row+1, data.size()); result->setRow(current_row, data); } return result; } template<typename T, typename G> SP::SiconosVector MechanicsIO::visitAllVerticesForDouble(const G& graph) const { SP::SiconosVector result(new SiconosVector(graph.vertices_number())); typename G::VIterator vi, viend; unsigned int current_row; for(current_row=0,std11::tie(vi,viend)=graph.vertices(); vi!=viend; ++vi, ++current_row) { T getter; graph.bundle(*vi)->accept(getter); result->setValue(current_row, *getter.result); } return result; } SP::SimpleMatrix MechanicsIO::positions(const NonSmoothDynamicalSystem& nsds) const { typedef Visitor < Classes < LagrangianDS, NewtonEulerDS >, GetPosition >::Make Getter; return visitAllVerticesForVector<Getter> (*(nsds.topology()->dSG(0))); }; SP::SimpleMatrix MechanicsIO::velocities(const NonSmoothDynamicalSystem& nsds) const { typedef Visitor < Classes < LagrangianDS, NewtonEulerDS >, GetVelocity>::Make Getter; return visitAllVerticesForVector<Getter> (*nsds.topology()->dSG(0)); } SP::SimpleMatrix MechanicsIO::contactPoints(const NonSmoothDynamicalSystem& nsds, unsigned int index_set) const { SP::SimpleMatrix result(new SimpleMatrix()); InteractionsGraph::VIterator vi, viend; if (nsds.topology()->numberOfIndexSet() > 0) { InteractionsGraph& graph = *nsds.topology()->indexSet(index_set); unsigned int current_row; result->resize(graph.vertices_number(), 14); for(current_row=0, std11::tie(vi,viend) = graph.vertices(); vi!=viend; ++vi) { DEBUG_PRINTF("process interaction : %p\n", &*graph.bundle(*vi)); typedef Visitor < Classes < NewtonEulerFrom1DLocalFrameR, NewtonEulerFrom3DLocalFrameR, PrismaticJointR, KneeJointR, PivotJointR>, ContactPointVisitor>::Make ContactPointInspector; ContactPointInspector inspector; inspector.inter = graph.bundle(*vi); graph.bundle(*vi)->relation()->accept(inspector); const SiconosVector& data = inspector.answer; if (data.size() == 14) result->setRow(current_row++, data); } result->resize(current_row, 14); } return result; } SP::SimpleMatrix MechanicsIO::domains(const NonSmoothDynamicalSystem& nsds) const { SP::SimpleMatrix result(new SimpleMatrix()); InteractionsGraph::VIterator vi, viend; if (nsds.topology()->numberOfIndexSet() > 0) { InteractionsGraph& graph = *nsds.topology()->indexSet(1); unsigned int current_row; result->resize(graph.vertices_number(), 2); for(current_row=0, std11::tie(vi,viend) = graph.vertices(); vi!=viend; ++vi, ++current_row) { DEBUG_PRINTF("process interaction : %p\n", &*graph.bundle(*vi)); typedef Visitor < Classes < NewtonEulerFrom1DLocalFrameR, NewtonEulerFrom3DLocalFrameR, PrismaticJointR, KneeJointR, PivotJointR>, ContactPointDomainVisitor>::Make DomainInspector; DomainInspector inspector; inspector.inter = graph.bundle(*vi); graph.bundle(*vi)->relation()->accept(inspector); const SiconosVector& data = inspector.answer; if (data.size() == 2) result->setRow(current_row, data); } } return result; } <|endoftext|>
<commit_before><commit_msg>SCROWS64K is not used anywhere<commit_after><|endoftext|>
<commit_before>#include "../search/search.hpp" #include "../structs/binheap.hpp" #include "../utils/pool.hpp" #include <limits> #include <vector> void dfrowhdr(FILE *, const char *name, int ncols, ...); void dfrow(FILE *, const char *name, const char *colfmt, ...); void fatal(const char*, ...); template <class D> struct Arastar : public SearchAlgorithm<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; struct Node : SearchNode<D> { Cost h; double fprime; static bool pred(Node *a, Node *b) { if (a->fprime == b->fprime) return a->g > b->g; return a->fprime < b->fprime; } }; struct Incons { Incons(unsigned long szhint) : mem(szhint) { } void init(D &d) { mem.init(d); } void add(Node *n, unsigned long h) { if (mem.find(n->packed, h) != NULL) return; mem.add(n); incons.push_back(n); } std::vector<Node*> &nodes(void) { return incons; } void clear(void) { mem.clear(); incons.clear(); } private: ClosedList<SearchNode<D>, SearchNode<D>, D> mem; std::vector<Node*> incons; }; Arastar(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), closed(30000001), incons(30000001) { wt0 = dwt = -1; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) dwt = strtod(argv[++i], NULL); } if (wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); wt = wt0; nodes = new Pool<Node>(); } ~Arastar(void) { delete nodes; } void search(D &d, typename D::State &s0) { this->start(); closed.init(d); incons.init(d); dfrowhdr(stdout, "sol", 6, "num", "nodes expanded", "nodes generated", "weight", "solution bound", "solution cost", "wall time"); Node *n0 = init(d, s0); closed.add(n0); open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = findbound(); if (wt < epsprime) epsprime = wt; dfrow(stdout, "sol", "uuugggg", n, SearchAlgorithm<D>::res.expd, SearchAlgorithm<D>::res.gend, wt, epsprime, (double) SearchAlgorithm<D>::res.cost, walltime() - SearchAlgorithm<D>::res.wallstrt); } if (wt <= 1.0) break; wt = wt - dwt > 1.0 ? wt - dwt : 1.0; updateopen(); closed.clear(); } while(!SearchAlgorithm<D>::limit() && !open.empty()); this->finish(); } virtual void reset(void) { SearchAlgorithm<D>::reset(); wt = wt0; open.clear(); closed.clear(); incons.clear(); delete nodes; nodes = new Pool<Node>(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); closed.prstats(stdout, "closed "); dfpair(stdout, "open list type", "%s", "binary heap"); dfpair(stdout, "node size", "%u", sizeof(Node)); dfpair(stdout, "initial weight", "%g", wt0); dfpair(stdout, "weight decrement", "%g", dwt); } private: bool improve(D &d) { bool goal = false; while (!SearchAlgorithm<D>::limit() && goodnodes()) { Node *n = *open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { SearchAlgorithm<D>::res.goal(d, n); goal = true; } expand(d, n, state); } return goal; } bool goodnodes() { return !open.empty() && (SearchAlgorithm<D>::res.cost == Cost(-1) || (double) SearchAlgorithm<D>::res.cost > (*open.front())->fprime); } // Find the tightest bound for the current incumbent. double findbound(void) { assert (SearchAlgorithm<D>::res.cost != Cost(-1)); double cost = SearchAlgorithm<D>::res.cost; double min = std::numeric_limits<double>::infinity(); std::vector<Node*> &inodes = incons.nodes(); for (long i = 0; i < (long) inodes.size(); i++) { Node *n = inodes[i]; double f = n->g + n->h; if (f >= cost) { inodes[i] = inodes[inodes.size()-1]; inodes.pop_back(); i--; continue; } if (f < min) min = f; } std::vector<Node*> &onodes = open.data(); for (long i = 0; i < (long) onodes.size(); i++) { Node *n = onodes[i]; double f = n->g + n->h; if (f >= cost) { onodes[i] = onodes[onodes.size()-1]; onodes.pop_back(); i--; continue; } if (f < min) min = f; } return cost / min; } // Update the open list: update f' values and add INCONS // and re-heapify. void updateopen(void) { std::vector<Node*> &nodes = incons.nodes(); for (unsigned long i = 0; i < nodes.size(); i++) { Node *n = nodes[i]; n->fprime = (double) n->g + wt * n->h; } for (long i = 0; i < open.size(); i++) { Node *n = open.at(i); n->fprime = (double) n->g + wt * n->h; } open.append(incons.nodes()); // reinits heap property incons.clear(); } void expand(D &d, Node *n, State &state) { SearchAlgorithm<D>::res.expd++; for (unsigned int i = 0; i < d.nops(state); i++) { Oper op = d.nthop(state, i); if (op == n->pop) continue; SearchAlgorithm<D>::res.gend++; considerkid(d, n, state, op); } } void considerkid(D &d, Node *parent, State &state, Oper op) { Node *kid = nodes->construct(); typename D::Transition tr(d, state, op); kid->g = parent->g + tr.cost; d.pack(kid->packed, tr.state); unsigned long hash = kid->packed.hash(); Node *dup = static_cast<Node*>(closed.find(kid->packed, hash)); if (dup) { SearchAlgorithm<D>::res.dups++; if (kid->g >= dup->g) { nodes->destruct(kid); return; } SearchAlgorithm<D>::res.reopnd++; dup->fprime = dup->fprime - dup->g + kid->g; dup->update(kid->g, parent, op, tr.revop); if (dup->openind < 0) incons.add(dup, hash); else open.update(dup->openind); nodes->destruct(kid); } else { kid->h = d.h(tr.state); kid->fprime = (double) kid->g + wt * kid->h; kid->update(kid->g, parent, op, tr.revop); closed.add(kid, hash); open.push(kid); } } Node *init(D &d, State &s0) { Node *n0 = nodes->construct(); d.pack(n0->packed, s0); n0->g = Cost(0); n0->h = d.h(s0); n0->fprime = wt * n0->h; n0->op = n0->pop = D::Nop; n0->parent = NULL; return n0; } double wt0, dwt, wt; BinHeap<Node, Node*> open; ClosedList<SearchNode<D>, SearchNode<D>, D> closed; Incons incons; Pool<Node> *nodes; }; <commit_msg>arastar: fix stupid floating point rounding bugs. When decrementing the weight to a value extremely close to 1, just set it to 1 instead so that this will be the last iteration.<commit_after>#include "../search/search.hpp" #include "../structs/binheap.hpp" #include "../utils/pool.hpp" #include <limits> #include <vector> #include <cmath> void dfrowhdr(FILE *, const char *name, int ncols, ...); void dfrow(FILE *, const char *name, const char *colfmt, ...); void fatal(const char*, ...); template <class D> struct Arastar : public SearchAlgorithm<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; struct Node : SearchNode<D> { Cost h; double fprime; static bool pred(Node *a, Node *b) { if (a->fprime == b->fprime) return a->g > b->g; return a->fprime < b->fprime; } }; struct Incons { Incons(unsigned long szhint) : mem(szhint) { } void init(D &d) { mem.init(d); } void add(Node *n, unsigned long h) { if (mem.find(n->packed, h) != NULL) return; mem.add(n); incons.push_back(n); } std::vector<Node*> &nodes(void) { return incons; } void clear(void) { mem.clear(); incons.clear(); } private: ClosedList<SearchNode<D>, SearchNode<D>, D> mem; std::vector<Node*> incons; }; Arastar(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), closed(30000001), incons(30000001) { wt0 = dwt = -1; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) dwt = strtod(argv[++i], NULL); } if (wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); wt = wt0; nodes = new Pool<Node>(); } ~Arastar(void) { delete nodes; } void search(D &d, typename D::State &s0) { this->start(); closed.init(d); incons.init(d); dfrowhdr(stdout, "sol", 6, "num", "nodes expanded", "nodes generated", "weight", "solution bound", "solution cost", "wall time"); Node *n0 = init(d, s0); closed.add(n0); open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = wt == 1.0 ? 1.0 : findbound(); if (wt < epsprime) epsprime = wt; dfrow(stdout, "sol", "uuugggg", n, this->res.expd, this->res.gend, wt, epsprime, (double) this->res.cost, walltime() - this->res.wallstrt); } if (wt <= 1.0) break; wt = wt - dwt > 1.0 ? wt - dwt : 1.0; if (wt < 1.0 + sqrt(std::numeric_limits<double>::epsilon())) wt = 1.0; updateopen(); closed.clear(); } while(!this->limit() && !open.empty()); this->finish(); } virtual void reset(void) { SearchAlgorithm<D>::reset(); wt = wt0; open.clear(); closed.clear(); incons.clear(); delete nodes; nodes = new Pool<Node>(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); closed.prstats(stdout, "closed "); dfpair(stdout, "open list type", "%s", "binary heap"); dfpair(stdout, "node size", "%u", sizeof(Node)); dfpair(stdout, "initial weight", "%g", wt0); dfpair(stdout, "weight decrement", "%g", dwt); } private: bool improve(D &d) { bool goal = false; while (!this->limit() && goodnodes()) { Node *n = *open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { this->res.goal(d, n); goal = true; } expand(d, n, state); } return goal; } bool goodnodes() { return !open.empty() && (this->res.cost == Cost(-1) || (double) this->res.cost > (*open.front())->fprime); } // Find the tightest bound for the current incumbent. double findbound(void) { assert (this->res.cost != Cost(-1)); double cost = this->res.cost; double min = std::numeric_limits<double>::infinity(); std::vector<Node*> &inodes = incons.nodes(); for (long i = 0; i < (long) inodes.size(); i++) { Node *n = inodes[i]; double f = n->g + n->h; if (f >= cost) { inodes[i] = inodes[inodes.size()-1]; inodes.pop_back(); i--; continue; } if (f < min) min = f; } std::vector<Node*> &onodes = open.data(); for (long i = 0; i < (long) onodes.size(); i++) { Node *n = onodes[i]; double f = n->g + n->h; if (f >= cost) { onodes[i] = onodes[onodes.size()-1]; onodes.pop_back(); i--; continue; } if (f < min) min = f; } return cost / min; } // Update the open list: update f' values and add INCONS // and re-heapify. void updateopen(void) { std::vector<Node*> &nodes = incons.nodes(); for (unsigned long i = 0; i < nodes.size(); i++) { Node *n = nodes[i]; n->fprime = (double) n->g + wt * n->h; } for (long i = 0; i < open.size(); i++) { Node *n = open.at(i); n->fprime = (double) n->g + wt * n->h; } open.append(incons.nodes()); // reinits heap property incons.clear(); } void expand(D &d, Node *n, State &state) { this->res.expd++; for (unsigned int i = 0; i < d.nops(state); i++) { Oper op = d.nthop(state, i); if (op == n->pop) continue; this->res.gend++; considerkid(d, n, state, op); } } void considerkid(D &d, Node *parent, State &state, Oper op) { Node *kid = nodes->construct(); typename D::Transition tr(d, state, op); kid->g = parent->g + tr.cost; d.pack(kid->packed, tr.state); unsigned long hash = kid->packed.hash(); Node *dup = static_cast<Node*>(closed.find(kid->packed, hash)); if (dup) { this->res.dups++; if (kid->g >= dup->g) { nodes->destruct(kid); return; } this->res.reopnd++; dup->fprime = dup->fprime - dup->g + kid->g; dup->update(kid->g, parent, op, tr.revop); if (dup->openind < 0) incons.add(dup, hash); else open.update(dup->openind); nodes->destruct(kid); } else { kid->h = d.h(tr.state); kid->fprime = (double) kid->g + wt * kid->h; kid->update(kid->g, parent, op, tr.revop); closed.add(kid, hash); open.push(kid); } } Node *init(D &d, State &s0) { Node *n0 = nodes->construct(); d.pack(n0->packed, s0); n0->g = Cost(0); n0->h = d.h(s0); n0->fprime = wt * n0->h; n0->op = n0->pop = D::Nop; n0->parent = NULL; return n0; } double wt0, dwt, wt; BinHeap<Node, Node*> open; ClosedList<SearchNode<D>, SearchNode<D>, D> closed; Incons incons; Pool<Node> *nodes; }; <|endoftext|>
<commit_before>#include <sl.h> #include <stdio.h> #include "thread.h" #include "overlay.h" typedef struct _THREAD_LIST THREAD_LIST_ENTRY; typedef struct _THREAD_LIST { UINT16 ThreadId; UINT64 cycles; UINT8 cpuUsage; //VOID* handle; BOOLEAN affinitized; THREAD_LIST_ENTRY* NextEntry; } THREAD_LIST_ENTRY, *THREAD_LIST; THREAD_LIST_ENTRY* TmThreadList = 0; VOID* TmHeapHandle; ULONG BaseMhz; extern UINT64 CyclesWaited; BOOLEAN StripWaitCycles = TRUE; #ifdef _WIN64 #include <intrin.h> TEB* __stdcall NtCurrentTeb() { return (TEB *) __readgsqword(0x30); } #endif VOID AddToThreadList( UINT16 ThreadId ) { THREAD_LIST_ENTRY *threadListEntry; OBJECT_ATTRIBUTES objectAttributes = {0}; CLIENT_ID id = {0}; VOID *handle = 0; //InitializeObjectAttributes(&objectAttributes, 0,0,0,0); objectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); //clear struct //memset(&id, 0, sizeof(id)); id.UniqueProcess = 0; id.UniqueThread = (VOID*)ThreadId; /*NtOpenThread(&handle, THREAD_SET_INFORMATION | THREAD_QUERY_INFORMATION, &objectAttributes, &id);*/ if (TmThreadList == 0) { //thread list is empty, mallocate first entry and return TmThreadList = (THREAD_LIST_ENTRY*) RtlAllocateHeap( TmHeapHandle, 0, sizeof(THREAD_LIST_ENTRY) ); TmThreadList->NextEntry = 0; TmThreadList->affinitized = 0; TmThreadList->cpuUsage = 0; TmThreadList->cycles = 0; //threadListFirstEntry->handle = handle; TmThreadList->ThreadId = ThreadId; return; } threadListEntry = (THREAD_LIST_ENTRY*) TmThreadList; //move to empty list while(threadListEntry->NextEntry != 0) { //check if already added if (threadListEntry->ThreadId == ThreadId) return; threadListEntry = threadListEntry->NextEntry; } //mallocate memory for new thread entry threadListEntry->NextEntry = (THREAD_LIST_ENTRY*) RtlAllocateHeap( TmHeapHandle, 0, sizeof(THREAD_LIST_ENTRY) ); //move to newly mallocated memory threadListEntry = threadListEntry->NextEntry; //init entry threadListEntry->NextEntry = 0; threadListEntry->affinitized = 0; threadListEntry->cpuUsage = 0; threadListEntry->cycles = 0; //threadListEntry->handle = handle; threadListEntry->ThreadId = ThreadId; } SYSTEM_PROCESS_INFORMATION* GetProcessInformation( UINT32* BufferSize ) { UINT64 delta = 0; UINT32 ProcOffset = 0; UINT32 bufferSize; PROCESSID processId; INT32 status = 0; VOID *buffer; SYSTEM_PROCESS_INFORMATION *processEntry; HANDLE heapHandle; heapHandle = NtCurrentTeb()->ProcessEnvironmentBlock->ProcessHeap; bufferSize = 0x4000; buffer = RtlAllocateHeap(heapHandle, 0, bufferSize); while (TRUE) { status = NtQuerySystemInformation( SystemProcessInformation, buffer, bufferSize, &bufferSize ); if (status == STATUS_BUFFER_TOO_SMALL || status == STATUS_INFO_LENGTH_MISMATCH) { RtlFreeHeap(heapHandle, 0, buffer); buffer = RtlAllocateHeap(heapHandle, 0, bufferSize); } else { break; } } processEntry = (SYSTEM_PROCESS_INFORMATION*)buffer; processId = (UINT32)NtCurrentTeb()->ClientId.UniqueProcess; do { processEntry = (SYSTEM_PROCESS_INFORMATION*)((UINT_B)processEntry + ProcOffset); if (processEntry && (UINT16)processEntry->UniqueProcessId == processId) { break; } ProcOffset = processEntry->NextEntryOffset; } while (processEntry != 0 && processEntry->NextEntryOffset != 0); return processEntry; } ThreadMonitor::ThreadMonitor() { UINT64 delta = 0; UINT32 ProcOffset = 0; UINT32 n, bufferSize; INT32 status = 0; SYSTEM_PROCESS_INFORMATION *processEntry; SYSTEM_THREAD_INFORMATION *threads; processEntry = GetProcessInformation(&bufferSize); threads = processEntry->Threads; TmHeapHandle = NtCurrentTeb()->ProcessEnvironmentBlock->ProcessHeap; for(n = 0; n < processEntry->NumberOfThreads; n++) { AddToThreadList( (UINT16) threads[n].ClientId.UniqueThread ); //Log(L"adding thread %u to list\n", (UINT16) threads[n].ClientId.UniqueThread); } NtFreeVirtualMemory( (VOID*)-1, (VOID**)&processEntry, (UINT32*)&bufferSize, MEM_RELEASE ); BaseMhz = PushSharedMemory->HarwareInformation.Processor.MhzBase; } VOID UpdateThreadList() { SYSTEM_PROCESS_INFORMATION *processInfo; static UINT8 currentThreadCount; UINT8 n; UINT32 bufferSize; processInfo = GetProcessInformation(&bufferSize); if (currentThreadCount != processInfo->NumberOfThreads) { for (n = 0; n < processInfo->NumberOfThreads; n++) { AddToThreadList((UINT16)processInfo->Threads[n].ClientId.UniqueThread); } } NtFreeVirtualMemory( (VOID*)-1, (VOID**)&processInfo, (UINT32*)&bufferSize, MEM_RELEASE ); } extern HANDLE RenderThreadHandle; VOID ThreadMonitor::Refresh() { UINT64 cyclesDeltaMax = 0; static UINT64 tcycles = 0; THREAD_CYCLE_TIME_INFORMATION cycles; OBJECT_ATTRIBUTES objectAttributes = {0}; VOID *handle = 0; objectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); NtQueryInformationThread( RenderThreadHandle, ThreadCycleTime, &cycles, sizeof(THREAD_CYCLE_TIME_INFORMATION), 0 ); // Ensure that this function was already called at least once and we // have the previous cycle time value if (tcycles) { UINT64 cyclesDelta; cyclesDelta = cycles.AccumulatedCycles.QuadPart - tcycles; if (cyclesDelta > cyclesDeltaMax) cyclesDeltaMax = cyclesDelta; } tcycles = cycles.AccumulatedCycles.QuadPart; MaxThreadCyclesDelta = cyclesDeltaMax; } UINT8 ThreadMonitor::GetMaxThreadUsage() { FLOAT threadUsage = 0.0f; //Remove waiting cycles used by frame limiter if (StripWaitCycles) { MaxThreadCyclesDelta -= CyclesWaited; } CyclesWaited = 0; threadUsage = ((FLOAT)MaxThreadCyclesDelta / (FLOAT)(BaseMhz * 1000000)) * 100; //clip calculated thread usage to [0-100] range to filter calculation non-ideality if (threadUsage < 0.0f) threadUsage = 0.0f; if (threadUsage > 100.0f) threadUsage = 100.0f; return threadUsage; } <commit_msg>fix thread monitor crash<commit_after>#include <sl.h> #include <stdio.h> #include "thread.h" #include "overlay.h" typedef struct _THREAD_LIST THREAD_LIST_ENTRY; typedef struct _THREAD_LIST { UINT16 ThreadId; UINT64 cycles; UINT8 cpuUsage; //VOID* handle; BOOLEAN affinitized; THREAD_LIST_ENTRY* NextEntry; } THREAD_LIST_ENTRY, *THREAD_LIST; THREAD_LIST_ENTRY* TmThreadList = 0; VOID* TmHeapHandle; ULONG BaseMhz; extern UINT64 CyclesWaited; BOOLEAN StripWaitCycles = TRUE; #ifdef _WIN64 #include <intrin.h> TEB* __stdcall NtCurrentTeb() { return (TEB *) __readgsqword(0x30); } #endif VOID AddToThreadList( UINT16 ThreadId ) { THREAD_LIST_ENTRY *threadListEntry; OBJECT_ATTRIBUTES objectAttributes = {0}; CLIENT_ID id = {0}; VOID *handle = 0; //InitializeObjectAttributes(&objectAttributes, 0,0,0,0); objectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); //clear struct //memset(&id, 0, sizeof(id)); id.UniqueProcess = 0; id.UniqueThread = (VOID*)ThreadId; /*NtOpenThread(&handle, THREAD_SET_INFORMATION | THREAD_QUERY_INFORMATION, &objectAttributes, &id);*/ if (TmThreadList == 0) { //thread list is empty, mallocate first entry and return TmThreadList = (THREAD_LIST_ENTRY*) RtlAllocateHeap( TmHeapHandle, 0, sizeof(THREAD_LIST_ENTRY) ); TmThreadList->NextEntry = 0; TmThreadList->affinitized = 0; TmThreadList->cpuUsage = 0; TmThreadList->cycles = 0; //threadListFirstEntry->handle = handle; TmThreadList->ThreadId = ThreadId; return; } threadListEntry = (THREAD_LIST_ENTRY*) TmThreadList; //move to empty list while(threadListEntry->NextEntry != 0) { //check if already added if (threadListEntry->ThreadId == ThreadId) return; threadListEntry = threadListEntry->NextEntry; } //mallocate memory for new thread entry threadListEntry->NextEntry = (THREAD_LIST_ENTRY*) RtlAllocateHeap( TmHeapHandle, 0, sizeof(THREAD_LIST_ENTRY) ); //move to newly mallocated memory threadListEntry = threadListEntry->NextEntry; //init entry threadListEntry->NextEntry = 0; threadListEntry->affinitized = 0; threadListEntry->cpuUsage = 0; threadListEntry->cycles = 0; //threadListEntry->handle = handle; threadListEntry->ThreadId = ThreadId; } extern "C" INTBOOL __stdcall IsBadReadPtr( const VOID *lp, ULONG_PTR ucb ); bool IsValidPointer(void* p) { return !IsBadReadPtr(p, sizeof(ULONG_PTR)) && p; } SYSTEM_PROCESS_INFORMATION* GetProcessInformation( UINT32* BufferSize ) { UINT64 delta = 0; UINT32 ProcOffset = 0; UINT32 bufferSize; PROCESSID processId; INT32 status = 0; VOID *buffer; SYSTEM_PROCESS_INFORMATION *processEntry; HANDLE heapHandle; heapHandle = NtCurrentTeb()->ProcessEnvironmentBlock->ProcessHeap; bufferSize = 0x4000; buffer = RtlAllocateHeap(heapHandle, 0, bufferSize); while (TRUE) { status = NtQuerySystemInformation( SystemProcessInformation, buffer, bufferSize, &bufferSize ); if (status == STATUS_BUFFER_TOO_SMALL || status == STATUS_INFO_LENGTH_MISMATCH) { RtlFreeHeap(heapHandle, 0, buffer); buffer = RtlAllocateHeap(heapHandle, 0, bufferSize); } else { break; } } processEntry = (SYSTEM_PROCESS_INFORMATION*)buffer; processId = (UINT32)NtCurrentTeb()->ClientId.UniqueProcess; do { processEntry = (SYSTEM_PROCESS_INFORMATION*)((UINT_B)processEntry + ProcOffset); if (!IsValidPointer(processEntry)) return NULL; if (processEntry && (UINT16)processEntry->UniqueProcessId == processId) { break; } ProcOffset = processEntry->NextEntryOffset; } while (processEntry != 0 && processEntry->NextEntryOffset != 0); return processEntry; } ThreadMonitor::ThreadMonitor() { UINT64 delta = 0; UINT32 ProcOffset = 0; UINT32 n, bufferSize; INT32 status = 0; SYSTEM_PROCESS_INFORMATION *processEntry; SYSTEM_THREAD_INFORMATION *threads; TmHeapHandle = NtCurrentTeb()->ProcessEnvironmentBlock->ProcessHeap; processEntry = GetProcessInformation(&bufferSize); if (processEntry) { threads = processEntry->Threads; for (n = 0; n < processEntry->NumberOfThreads; n++) { AddToThreadList((UINT16)threads[n].ClientId.UniqueThread); //Log(L"adding thread %u to list\n", (UINT16) threads[n].ClientId.UniqueThread); } NtFreeVirtualMemory( (VOID*)-1, (VOID**)&processEntry, (UINT32*)&bufferSize, MEM_RELEASE ); } BaseMhz = PushSharedMemory->HarwareInformation.Processor.MhzBase; } VOID UpdateThreadList() { SYSTEM_PROCESS_INFORMATION *processInfo; static UINT8 currentThreadCount; UINT8 n; UINT32 bufferSize; processInfo = GetProcessInformation(&bufferSize); if (currentThreadCount != processInfo->NumberOfThreads) { for (n = 0; n < processInfo->NumberOfThreads; n++) { AddToThreadList((UINT16)processInfo->Threads[n].ClientId.UniqueThread); } } NtFreeVirtualMemory( (VOID*)-1, (VOID**)&processInfo, (UINT32*)&bufferSize, MEM_RELEASE ); } extern HANDLE RenderThreadHandle; VOID ThreadMonitor::Refresh() { UINT64 cyclesDeltaMax = 0; static UINT64 tcycles = 0; THREAD_CYCLE_TIME_INFORMATION cycles; OBJECT_ATTRIBUTES objectAttributes = {0}; VOID *handle = 0; objectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); NtQueryInformationThread( RenderThreadHandle, ThreadCycleTime, &cycles, sizeof(THREAD_CYCLE_TIME_INFORMATION), 0 ); // Ensure that this function was already called at least once and we // have the previous cycle time value if (tcycles) { UINT64 cyclesDelta; cyclesDelta = cycles.AccumulatedCycles.QuadPart - tcycles; if (cyclesDelta > cyclesDeltaMax) cyclesDeltaMax = cyclesDelta; } tcycles = cycles.AccumulatedCycles.QuadPart; MaxThreadCyclesDelta = cyclesDeltaMax; } UINT8 ThreadMonitor::GetMaxThreadUsage() { FLOAT threadUsage = 0.0f; //Remove waiting cycles used by frame limiter if (StripWaitCycles) { MaxThreadCyclesDelta -= CyclesWaited; } CyclesWaited = 0; threadUsage = ((FLOAT)MaxThreadCyclesDelta / (FLOAT)(BaseMhz * 1000000)) * 100; //clip calculated thread usage to [0-100] range to filter calculation non-ideality if (threadUsage < 0.0f) threadUsage = 0.0f; if (threadUsage > 100.0f) threadUsage = 100.0f; return threadUsage; } <|endoftext|>
<commit_before>#include "tests-base.hpp" #include "utf8rewind.h" #include "helpers-strings.hpp" TEST(ToTitle, BasicLatinUppercase) { const char* c = "J"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("J", b); EXPECT_EQ(0, errors); } TEST(ToTitle, BasicLatinLowercase) { const char* c = "z"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Z", b); EXPECT_EQ(0, errors); } TEST(ToTitle, BasicLatinUnaffected) { const char* c = "$"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("$", b); EXPECT_EQ(0, errors); } TEST(ToTitle, Word) { const char* c = "ApplE"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(5, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Apple", b); EXPECT_EQ(0, errors); } TEST(ToTitle, WordAllUppercase) { const char* c = "BROWN"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(5, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Brown", b); EXPECT_EQ(0, errors); } TEST(ToTitle, WordAllLowercase) { const char* c = "lady"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(4, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Lady", b); EXPECT_EQ(0, errors); } TEST(ToTitle, SentenceTwoWords) { const char* c = "PRINTER INK"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(11, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Printer Ink", b); EXPECT_EQ(0, errors); } TEST(ToTitle, SentencePunctuation) { const char* c = "RE/wind=cool"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(12, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Re/Wind=Cool", b); EXPECT_EQ(0, errors); }<commit_msg>suite-totitle: Added multibyte and invalid data tests.<commit_after>#include "tests-base.hpp" #include "utf8rewind.h" #include "helpers-strings.hpp" TEST(ToTitle, BasicLatinUppercase) { const char* c = "J"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("J", b); EXPECT_EQ(0, errors); } TEST(ToTitle, BasicLatinLowercase) { const char* c = "z"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Z", b); EXPECT_EQ(0, errors); } TEST(ToTitle, BasicLatinUnaffected) { const char* c = "$"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(1, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("$", b); EXPECT_EQ(0, errors); } TEST(ToTitle, MultiByteUppercase) { const char* c = "\xC7\x84"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("\xC7\x85", b); EXPECT_EQ(0, errors); } TEST(ToTitle, MultiByteLowercase) { const char* c = "\xEF\xAC\x97"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(4, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("\xD5\x84\xD5\xAD", b); EXPECT_EQ(0, errors); } TEST(ToTitle, MultiByteTitlecase) { const char* c = "\xC7\xB2"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(2, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("\xC7\xB2", b); EXPECT_EQ(0, errors); } TEST(ToTitle, Word) { const char* c = "ApplE"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(5, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Apple", b); EXPECT_EQ(0, errors); } TEST(ToTitle, WordAllUppercase) { const char* c = "BROWN"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(5, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Brown", b); EXPECT_EQ(0, errors); } TEST(ToTitle, WordAllLowercase) { const char* c = "lady"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(4, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Lady", b); EXPECT_EQ(0, errors); } TEST(ToTitle, SentenceTwoWords) { const char* c = "PRINTER INK"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(11, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Printer Ink", b); EXPECT_EQ(0, errors); } TEST(ToTitle, SentencePunctuation) { const char* c = "RE/wind=cool"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(12, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Re/Wind=Cool", b); EXPECT_EQ(0, errors); } TEST(ToTitle, AmountOfBytes) { const char* c = "tiny \xEA\x9E\xAA"; int32_t errors = 0; EXPECT_EQ(8, utf8totitle(c, strlen(c), nullptr, 0, 0, &errors)); EXPECT_EQ(0, errors); } TEST(ToTitle, NotEnoughSpace) { const char* c = "SMALL \xCE\x90"; const size_t s = 7; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(6, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("Small ", b); EXPECT_EQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors); } TEST(ToTitle, InvalidCodepoint) { const char* c = "\xF0\x92"; const size_t s = 256; char b[s] = { 0 }; int32_t errors = 0; EXPECT_EQ(3, utf8totitle(c, strlen(c), b, s - 1, 0, &errors)); EXPECT_UTF8EQ("\xEF\xBF\xBD", b); EXPECT_EQ(0, errors); } TEST(ToTitle, InvalidData) { int32_t errors = 0; EXPECT_EQ(0, utf8totitle(nullptr, 1, nullptr, 0, 0, &errors)); EXPECT_EQ(UTF8_ERR_INVALID_DATA, errors); }<|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware 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 "lane_select_core.h" namespace lane_planner { // Constructor LaneSelectNode::LaneSelectNode() : private_nh_("~") , num_of_lane_(-1) , num_of_closest_(-1) , change_flag_(ChangeFlag::unknown) , is_lane_array_subscribed_(false) , is_current_pose_subscribed_(false) , last_time_(ros::Time::now()) { initParameter(); initSubscriber(); initPublisher(); } // Destructor LaneSelectNode::~LaneSelectNode() { } void LaneSelectNode::initSubscriber() { // setup subscriber sub1_ = nh_.subscribe("traffic_waypoints_array", 100, &LaneSelectNode::callbackFromLaneArray, this); sub2_ = nh_.subscribe("current_pose", 100, &LaneSelectNode::callbackFromCurrentPose, this); } void LaneSelectNode::initPublisher() { // setup publisher pub_ = nh_.advertise<waypoint_follower::lane>("base_waypoints", 10, true); } void LaneSelectNode::initParameter() { private_nh_.param<int32_t>("size_of_waypoints", size_of_waypoints_, int32_t(30)); private_nh_.param<int32_t>("lane_change_interval", lane_change_interval_, int32_t(2)); } void LaneSelectNode::publishLocalLane() { if (!is_current_pose_subscribed_ || !is_lane_array_subscribed_) { ROS_ERROR("Necessary topics are not subscribed yet."); return; } if (num_of_lane_ == -1) num_of_lane_++; ros::Time current_time = ros::Time::now(); double dt = (current_time - last_time_).toSec(); ROS_INFO("dt: %lf", dt); if (dt > lane_change_interval_ && (change_flag_ == ChangeFlag::right && num_of_lane_ < static_cast<int32_t>(lane_array_.lanes.size()))) { num_of_lane_++; last_time_ = current_time; } if (dt > lane_change_interval_ && (change_flag_ == ChangeFlag::left && num_of_lane_ > 0)) { num_of_lane_--; last_time_ = current_time; } waypoint_follower::lane local_lane; createLocalLane(&local_lane); pub_.publish(local_lane); // if (current_lane.waypoints.at(num_of_closest_).change_flag == static_cast<ChangeFlagInteger>(ChangeFlag::right) && // num_of_lane_ != lane_array_.size() - 1) //{ // num_of_lane_++; //} is_current_pose_subscribed_ = false; } void LaneSelectNode::createLocalLane(waypoint_follower::lane *lane) { num_of_closest_ = getClosestWaypoint(lane_array_.lanes.at(num_of_lane_), current_pose_.pose); if (num_of_closest_ == -1) { ROS_ERROR("cannot get closest waypoint"); return; } // setup lane->header.stamp = ros::Time::now(); lane->header.frame_id = "map"; // push some waypoints for (auto i = 0; i < size_of_waypoints_; i++) { if (num_of_closest_ + i > static_cast<int32_t>(lane_array_.lanes.at(num_of_lane_).waypoints.size() - 1)) break; lane->waypoints.push_back(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_ + i)); } // push current_pose as first waypoint waypoint_follower::waypoint first_waypoint; first_waypoint = lane->waypoints.at(0); first_waypoint.pose.pose.position.x = current_pose_.pose.position.x; first_waypoint.pose.pose.position.y = current_pose_.pose.position.y; auto it = lane->waypoints.begin(); lane->waypoints.insert(it, first_waypoint); change_flag_ = static_cast<ChangeFlag>(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_).change_flag); ROS_INFO("change_flag: %d", static_cast<ChangeFlagInteger>(change_flag_)); } void LaneSelectNode::callbackFromLaneArray(const waypoint_follower::LaneArrayConstPtr &msg) { lane_array_ = *msg; is_lane_array_subscribed_ = true; } void LaneSelectNode::callbackFromCurrentPose(const geometry_msgs::PoseStampedConstPtr &msg) { current_pose_ = *msg; is_current_pose_subscribed_ = true; publishLocalLane(); } // get closest waypoint from current pose /*int32_t getClosestWaypoint(const waypoint_follower::lane &current_path, const geometry_msgs::Pose &current_pose) { WayPoints wp; wp.setPath(current_path); if (wp.isEmpty()) return -1; // search closest candidate within a certain meter double search_distance = 5.0; std::vector<int> waypoint_candidates; for (int i = 1; i < wp.getSize(); i++) { if (getPlaneDistance(wp.getWaypointPosition(i), current_pose.position) > search_distance) continue; if (!wp.isFront(i, current_pose)) continue; double angle_threshold = 90; if (getRelativeAngle(wp.getWaypointPose(i), current_pose) > angle_threshold) continue; waypoint_candidates.push_back(i); } // get closest waypoint from candidates if (!waypoint_candidates.empty()) { int waypoint_min = -1; double distance_min = DBL_MAX; for (auto el : waypoint_candidates) { // ROS_INFO("closest_candidates : %d",el); double d = getPlaneDistance(wp.getWaypointPosition(el), current_pose.position); if (d < distance_min) { waypoint_min = el; distance_min = d; } } return waypoint_min; } else { ROS_INFO("no candidate. search closest waypoint from all waypoints..."); // if there is no candidate... int waypoint_min = -1; double distance_min = DBL_MAX; for (int i = 1; i < wp.getSize(); i++) { if (!wp.isFront(i, current_pose)) continue; // if (!wp.isValid(i, current_pose)) // continue; double d = getPlaneDistance(wp.getWaypointPosition(i), current_pose.position); if (d < distance_min) { waypoint_min = i; distance_min = d; } } return waypoint_min; } }*/ } // lane_planner <commit_msg>Delete comment out<commit_after>/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware 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 "lane_select_core.h" namespace lane_planner { // Constructor LaneSelectNode::LaneSelectNode() : private_nh_("~") , num_of_lane_(-1) , num_of_closest_(-1) , change_flag_(ChangeFlag::unknown) , is_lane_array_subscribed_(false) , is_current_pose_subscribed_(false) , last_time_(ros::Time::now()) { initParameter(); initSubscriber(); initPublisher(); } // Destructor LaneSelectNode::~LaneSelectNode() { } void LaneSelectNode::initSubscriber() { // setup subscriber sub1_ = nh_.subscribe("traffic_waypoints_array", 100, &LaneSelectNode::callbackFromLaneArray, this); sub2_ = nh_.subscribe("current_pose", 100, &LaneSelectNode::callbackFromCurrentPose, this); } void LaneSelectNode::initPublisher() { // setup publisher pub_ = nh_.advertise<waypoint_follower::lane>("base_waypoints", 10, true); } void LaneSelectNode::initParameter() { private_nh_.param<int32_t>("size_of_waypoints", size_of_waypoints_, int32_t(30)); private_nh_.param<int32_t>("lane_change_interval", lane_change_interval_, int32_t(2)); } void LaneSelectNode::publishLocalLane() { if (!is_current_pose_subscribed_ || !is_lane_array_subscribed_) { ROS_ERROR("Necessary topics are not subscribed yet."); return; } if (num_of_lane_ == -1) num_of_lane_++; ros::Time current_time = ros::Time::now(); double dt = (current_time - last_time_).toSec(); ROS_INFO("dt: %lf", dt); if (dt > lane_change_interval_ && (change_flag_ == ChangeFlag::right && num_of_lane_ < static_cast<int32_t>(lane_array_.lanes.size()))) { num_of_lane_++; last_time_ = current_time; } if (dt > lane_change_interval_ && (change_flag_ == ChangeFlag::left && num_of_lane_ > 0)) { num_of_lane_--; last_time_ = current_time; } waypoint_follower::lane local_lane; createLocalLane(&local_lane); pub_.publish(local_lane); is_current_pose_subscribed_ = false; } void LaneSelectNode::createLocalLane(waypoint_follower::lane *lane) { num_of_closest_ = getClosestWaypoint(lane_array_.lanes.at(num_of_lane_), current_pose_.pose); if (num_of_closest_ == -1) { ROS_ERROR("cannot get closest waypoint"); return; } // setup lane->header.stamp = ros::Time::now(); lane->header.frame_id = "map"; // push some waypoints for (auto i = 0; i < size_of_waypoints_; i++) { if (num_of_closest_ + i > static_cast<int32_t>(lane_array_.lanes.at(num_of_lane_).waypoints.size() - 1)) break; lane->waypoints.push_back(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_ + i)); } // push current_pose as first waypoint waypoint_follower::waypoint first_waypoint; first_waypoint = lane->waypoints.at(0); first_waypoint.pose.pose.position.x = current_pose_.pose.position.x; first_waypoint.pose.pose.position.y = current_pose_.pose.position.y; auto it = lane->waypoints.begin(); lane->waypoints.insert(it, first_waypoint); change_flag_ = static_cast<ChangeFlag>(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_).change_flag); ROS_INFO("change_flag: %d", static_cast<ChangeFlagInteger>(change_flag_)); } void LaneSelectNode::callbackFromLaneArray(const waypoint_follower::LaneArrayConstPtr &msg) { lane_array_ = *msg; is_lane_array_subscribed_ = true; } void LaneSelectNode::callbackFromCurrentPose(const geometry_msgs::PoseStampedConstPtr &msg) { current_pose_ = *msg; is_current_pose_subscribed_ = true; publishLocalLane(); } // get closest waypoint from current pose /*int32_t getClosestWaypoint(const waypoint_follower::lane &current_path, const geometry_msgs::Pose &current_pose) { WayPoints wp; wp.setPath(current_path); if (wp.isEmpty()) return -1; // search closest candidate within a certain meter double search_distance = 5.0; std::vector<int> waypoint_candidates; for (int i = 1; i < wp.getSize(); i++) { if (getPlaneDistance(wp.getWaypointPosition(i), current_pose.position) > search_distance) continue; if (!wp.isFront(i, current_pose)) continue; double angle_threshold = 90; if (getRelativeAngle(wp.getWaypointPose(i), current_pose) > angle_threshold) continue; waypoint_candidates.push_back(i); } // get closest waypoint from candidates if (!waypoint_candidates.empty()) { int waypoint_min = -1; double distance_min = DBL_MAX; for (auto el : waypoint_candidates) { // ROS_INFO("closest_candidates : %d",el); double d = getPlaneDistance(wp.getWaypointPosition(el), current_pose.position); if (d < distance_min) { waypoint_min = el; distance_min = d; } } return waypoint_min; } else { ROS_INFO("no candidate. search closest waypoint from all waypoints..."); // if there is no candidate... int waypoint_min = -1; double distance_min = DBL_MAX; for (int i = 1; i < wp.getSize(); i++) { if (!wp.isFront(i, current_pose)) continue; // if (!wp.isValid(i, current_pose)) // continue; double d = getPlaneDistance(wp.getWaypointPosition(i), current_pose.position); if (d < distance_min) { waypoint_min = i; distance_min = d; } } return waypoint_min; } }*/ } // lane_planner <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RL78/G13 グループ・データ・フラッシュ制御 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RL78/blob/master/LICENSE */ //=====================================================================// #include "data_flash_lib/data_flash_util.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief フラッシュ制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class flash_io { public: //-----------------------------------------------------------------// /*! @brief データ・フラッシュ構成 @n (全体8Kバイト、ブロック8個、バンク1024個) */ //-----------------------------------------------------------------// static const uint16_t data_flash_block = 1024; ///< データ・フラッシュのブロックサイズ static const uint16_t data_flash_size = 8192; ///< データ・フラッシュの容量 static const uint16_t data_flash_bank = 8; ///< データ・フラッシュのバンク数 //-----------------------------------------------------------------// /*! @brief エラー型 */ //-----------------------------------------------------------------// enum class error : uint8_t { NONE, ///< エラー無し ADDRESS, ///< アドレス・エラー TIMEOUT, ///< タイム・アウト・エラー LOCK, ///< ロック・エラー }; private: error error_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// flash_io() : error_(error::NONE) { } //-----------------------------------------------------------------// /*! @brief 開始 */ //-----------------------------------------------------------------// bool start() { error_ = error::NONE; return pfdl_open() == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 終了 */ //-----------------------------------------------------------------// void end() { pfdl_close(); } //-----------------------------------------------------------------// /*! @brief 読み出し @param[in] org 開始アドレス @param[out] dst 先 @param[in] len バイト数 @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool read(uint16_t org, void* dst, uint16_t len) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } if((org + len) > data_flash_size) { len = data_flash_size - org; } return pfdl_read(org, static_cast<uint8_t*>(dst), len) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 読み出し @param[in] org 開始アドレス @return データ */ //-----------------------------------------------------------------// uint8_t read(uint16_t org) { uint8_t tmp[1]; if(read(org, &tmp, 1)) { return tmp[0]; } return 0; } //-----------------------------------------------------------------// /*! @brief 消去チェック @param[in] org 開始アドレス @param[in] len 検査長(バイト単位) @return 消去されていれば「true」(エラーは「false」) */ //-----------------------------------------------------------------// bool erase_check(uint16_t org, uint16_t len = data_flash_block) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } return pfdl_blank_check(org, len) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 消去 @param[in] org 開始アドレス @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool erase(uint16_t org) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } return pfdl_erase_block(org / data_flash_block) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 全消去 @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool erase_all() { for(uint16_t pos = 0; pos < data_flash_size; pos += data_flash_block) { if(!erase_check(pos)) { auto ret = erase(pos); if(!ret) { return false; } } } return true; } //-----------------------------------------------------------------// /*! @brief 書き込み @n ※仕様上、4バイト単位で書き込まれる。@n ※4バイト未満の場合は、0xFFが書き込まれる @param[in] org 開始オフセット @param[in] src ソース @param[in] len バイト数 @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool write(uint16_t org, const void* src, uint16_t len) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } return pfdl_write(org, static_cast<const uint8_t*>(src), len) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 書き込み @param[in] org 開始オフセット @param[in] data 書き込みデータ @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool write(uint16_t org, uint8_t data) { uint8_t d = data; return write(org, &d, 1); } }; } <commit_msg>update device selector<commit_after>#pragma once //=====================================================================// /*! @file @brief RL78/G13 グループ・データ・フラッシュ制御 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RL78/blob/master/LICENSE */ //=====================================================================// #include "data_flash_lib/data_flash_util.h" /// DEVICE_SIG はデータ・フラッシュ・メモリーの容量定義に必要で、設定が無ければエラーとする #ifndef DEVICE_SIG # error "flash_io.hpp requires DEVICE_SIG to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief フラッシュ制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class flash_io { public: //-----------------------------------------------------------------// /*! @brief データ・フラッシュ構成 @n R5F100LC, R5F100LE: 4K, 4 x 1024 @n R5F100LG, R5F100LJ: 8K, 8 x 1024 */ //-----------------------------------------------------------------// static const uint16_t data_flash_block = 1024; ///< データ・フラッシュのブロックサイズ #if (DEVICE_SIG == R5F100LC) || (DEVICE_SIG == R5F100LE) static const uint16_t data_flash_size = 4096; ///< データ・フラッシュの容量 static const uint16_t data_flash_bank = 4; ///< データ・フラッシュのバンク数 #elif (DEVICE_SIG == R5F100LG) || (DEVICE_SIG == R5F100LJ) static const uint16_t data_flash_size = 8192; ///< データ・フラッシュの容量 static const uint16_t data_flash_bank = 8; ///< データ・フラッシュのバンク数 #else static const uint16_t data_flash_size = 0; ///< データ・フラッシュの容量 static const uint16_t data_flash_bank = 0; ///< データ・フラッシュのバンク数 #endif //-----------------------------------------------------------------// /*! @brief エラー型 */ //-----------------------------------------------------------------// enum class error : uint8_t { NONE, ///< エラー無し ADDRESS, ///< アドレス・エラー TIMEOUT, ///< タイム・アウト・エラー LOCK, ///< ロック・エラー }; private: error error_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// flash_io() : error_(error::NONE) { } //-----------------------------------------------------------------// /*! @brief 開始 */ //-----------------------------------------------------------------// bool start() { if(data_flash_size == 0) return false; error_ = error::NONE; return pfdl_open() == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 終了 */ //-----------------------------------------------------------------// void end() { pfdl_close(); } //-----------------------------------------------------------------// /*! @brief 読み出し @param[in] org 開始アドレス @param[out] dst 先 @param[in] len バイト数 @return エラー無ければ「true」 */ //-----------------------------------------------------------------// bool read(uint16_t org, void* dst, uint16_t len) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } if((org + len) > data_flash_size) { len = data_flash_size - org; } return pfdl_read(org, static_cast<uint8_t*>(dst), len) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 読み出し @param[in] org 開始アドレス @return データ */ //-----------------------------------------------------------------// uint8_t read(uint16_t org) { uint8_t tmp[1]; if(read(org, &tmp, 1)) { return tmp[0]; } return 0; } //-----------------------------------------------------------------// /*! @brief 消去チェック @param[in] org 開始アドレス @param[in] len 検査長(バイト単位) @return 消去されていれば「true」(エラーは「false」) */ //-----------------------------------------------------------------// bool erase_check(uint16_t org, uint16_t len = data_flash_block) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } return pfdl_blank_check(org, len) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 消去 @param[in] org 開始アドレス @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool erase(uint16_t org) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } return pfdl_erase_block(org / data_flash_block) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 全消去 @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool erase_all() { for(uint16_t pos = 0; pos < data_flash_size; pos += data_flash_block) { if(!erase_check(pos)) { auto ret = erase(pos); if(!ret) { return false; } } } return true; } //-----------------------------------------------------------------// /*! @brief 書き込み @n ※仕様上、4バイト単位で書き込まれる。@n ※4バイト未満の場合は、0xFFが書き込まれる @param[in] org 開始オフセット @param[in] src ソース @param[in] len バイト数 @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool write(uint16_t org, const void* src, uint16_t len) { if(org >= data_flash_size) { error_ = error::ADDRESS; return false; } return pfdl_write(org, static_cast<const uint8_t*>(src), len) == PFDL_OK; } //-----------------------------------------------------------------// /*! @brief 書き込み @param[in] org 開始オフセット @param[in] data 書き込みデータ @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool write(uint16_t org, uint8_t data) { uint8_t d = data; return write(org, &d, 1); } }; } <|endoftext|>
<commit_before>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #include "TelegramServer.hpp" #include "TelegramServerUser.hpp" #include "DcConfiguration.hpp" #include "LocalCluster.hpp" #include "Session.hpp" #include "Utils.hpp" #include <QCoreApplication> #include <QDebug> #include <QStandardPaths> Telegram::Server::User *tryAddUser(Telegram::Server::LocalCluster *cluster, const QString &identifier, quint32 dcId, const QString &firstName, const QString &lastName, const QString &password = QString() ) { Telegram::Server::User *u = cluster->addUser(identifier, dcId); if (u) { u->setFirstName(firstName); u->setLastName(lastName); u->setPlainPassword(password); } else { qCritical() << "Unable to add a user"; } return u; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Telegram::initialize(); Telegram::DcConfiguration configuration; const QVector<Telegram::DcOption> dcOptions = { Telegram::DcOption(QStringLiteral("127.0.0.1"), 11441, 1), Telegram::DcOption(QStringLiteral("127.0.0.2"), 11442, 2), Telegram::DcOption(QStringLiteral("127.0.0.3"), 11443, 3), }; configuration.dcOptions = dcOptions; const Telegram::RsaKey key = Telegram::Utils::loadRsaPrivateKeyFromFile( QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first() + QStringLiteral("/TelegramServer/private_key.pem")); if (!key.isValid()) { qCritical() << "Unable to read RSA key"; return -1; } Telegram::Server::LocalCluster cluster; cluster.setServerPrivateRsaKey(key); cluster.setServerConfiguration(configuration); cluster.start(); tryAddUser(&cluster, QStringLiteral("5432101"), /* dc */ 1, QStringLiteral("Telegram"), QStringLiteral("Qt"), QStringLiteral("mypassword") ); tryAddUser(&cluster, QStringLiteral("5432102"), /* dc */ 2, QStringLiteral("Telegram2"), QStringLiteral("Qt2") ); tryAddUser(&cluster, QStringLiteral("5432103"), /* dc */ 3, QStringLiteral("Telegram3"), QStringLiteral("Qt3"), QStringLiteral("hispassword") ); return a.exec(); } <commit_msg>Server/main: Use Telegram::Server namespace<commit_after>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #include "TelegramServer.hpp" #include "TelegramServerUser.hpp" #include "DcConfiguration.hpp" #include "LocalCluster.hpp" #include "Session.hpp" #include "Utils.hpp" #include <QCoreApplication> #include <QDebug> #include <QStandardPaths> using namespace Telegram::Server; User *tryAddUser(LocalCluster *cluster, const QString &identifier, quint32 dcId, const QString &firstName, const QString &lastName, const QString &password = QString() ) { User *u = cluster->addUser(identifier, dcId); if (u) { u->setFirstName(firstName); u->setLastName(lastName); u->setPlainPassword(password); } else { qCritical() << "Unable to add a user"; } return u; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Telegram::initialize(); Telegram::DcConfiguration configuration; const QVector<Telegram::DcOption> dcOptions = { Telegram::DcOption(QStringLiteral("127.0.0.1"), 11441, 1), Telegram::DcOption(QStringLiteral("127.0.0.2"), 11442, 2), Telegram::DcOption(QStringLiteral("127.0.0.3"), 11443, 3), }; configuration.dcOptions = dcOptions; const Telegram::RsaKey key = Telegram::Utils::loadRsaPrivateKeyFromFile( QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first() + QStringLiteral("/TelegramServer/private_key.pem")); if (!key.isValid()) { qCritical() << "Unable to read RSA key"; return -1; } LocalCluster cluster; cluster.setServerPrivateRsaKey(key); cluster.setServerConfiguration(configuration); cluster.start(); tryAddUser(&cluster, QStringLiteral("5432101"), /* dc */ 1, QStringLiteral("Telegram"), QStringLiteral("Qt"), QStringLiteral("mypassword") ); tryAddUser(&cluster, QStringLiteral("5432102"), /* dc */ 2, QStringLiteral("Telegram2"), QStringLiteral("Qt2") ); tryAddUser(&cluster, QStringLiteral("5432103"), /* dc */ 3, QStringLiteral("Telegram3"), QStringLiteral("Qt3"), QStringLiteral("hispassword") ); return a.exec(); } <|endoftext|>
<commit_before>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <config.h> #include <glibmm.h> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #include "version.hpp" #include <glib/gstdio.h> #include <ftw.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "TransportFactory.hpp" #include <SignalHandler.hpp> #include <ServerMethods.hpp> #include <gst/gst.h> #include <boost/program_options.hpp> #include <boost/exception/diagnostic_information.hpp> #include "logging.hpp" #include "modules.hpp" #define GST_CAT_DEFAULT kurento_media_server GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaServer" const std::string DEFAULT_CONFIG_FILE = "/etc/kurento/kurento.conf.json"; const std::string ENV_PREFIX = "KURENTO_"; using namespace ::kurento; static std::shared_ptr<Transport> transport; __pid_t pid; Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (); static gchar *tmp_dir; Glib::RefPtr<Glib::IOChannel> channel; static void load_config (boost::property_tree::ptree &config, const std::string &file_name) { boost::filesystem::path configFilePath (file_name); GST_INFO ("Reading configuration from: %s", file_name.c_str () ); boost::property_tree::read_json (file_name, config); config.add ("configPath", configFilePath.parent_path().string() ); pid = getpid(); GST_INFO ("Configuration loaded successfully"); std::shared_ptr<ServerMethods> serverMethods (new ServerMethods (config) ); try { transport = TransportFactory::create_transport (config, serverMethods); } catch (std::exception &e) { GST_ERROR ("Error creating transport: %s", e.what() ); exit (1); } } static void signal_handler (uint32_t signo) { static unsigned int __terminated = 0; switch (signo) { case SIGINT: case SIGTERM: if (__terminated == 0) { GST_DEBUG ("Terminating."); loop->quit (); } __terminated = 1; break; case SIGPIPE: GST_DEBUG ("Ignore sigpipe signal"); break; case SIGSEGV: GST_DEBUG ("Segmentation fault. Aborting process execution"); abort (); default: break; } } static int delete_file (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int rv = g_remove (fpath); if (rv) { GST_WARNING ("Error deleting file: %s. %s", fpath, strerror (errno) ); } return rv; } static void remove_recursive (const gchar *path) { nftw (path, delete_file, 64, FTW_DEPTH | FTW_PHYS); } static void deleteCertificate () { // Only parent process can delete certificate if (pid != getpid() ) { return; } if (tmp_dir != NULL) { remove_recursive (tmp_dir); g_free (tmp_dir); } } static std::string environment_adaptor (std::string &input) { /* Look for KMS_ prefix and change to lower case */ if (input.find (ENV_PREFIX) == 0) { std::string aux = input.substr (ENV_PREFIX.size() ); std::transform (aux.begin(), aux.end(), aux.begin(), [] (int c) -> int { return (c == '_') ? '-' : tolower (c); }); return aux; } return ""; } int main (int argc, char **argv) { sigset_t mask; std::shared_ptr <SignalHandler> signalHandler; boost::property_tree::ptree config; std::string confFile; std::string path; Glib::init(); gst_init (&argc, &argv); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); gst_debug_remove_log_function_by_data (NULL); gst_debug_add_log_function (log_function, NULL, NULL); try { boost::program_options::options_description desc ("kurento-media-server usage"); desc.add_options() ("help,h", "Display this help message") ("version,v", "Display the version number") ("modules-path,p", boost::program_options::value<std::string> (&path), "Path where kurento modules can be found") ("conf-file,f", boost::program_options::value<std::string> (&confFile)->default_value (DEFAULT_CONFIG_FILE), "Configuration file location"); boost::program_options::variables_map vm; boost::program_options::store (boost::program_options::parse_command_line (argc, argv, desc), vm); boost::program_options::store (boost::program_options::parse_environment (desc, &environment_adaptor), vm); boost::program_options::notify (vm); if (vm.count ("help") ) { std::cout << desc << "\n"; exit (0); } loadModules (path); if (vm.count ("version") ) { print_version(); exit (0); } } catch (boost::program_options::error &e) { std::cerr << "Error : " << e.what() << std::endl; exit (1); } /* Install our signal handler */ sigemptyset (&mask); sigaddset (&mask, SIGINT); sigaddset (&mask, SIGTERM); sigaddset (&mask, SIGSEGV); sigaddset (&mask, SIGPIPE); signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask, signal_handler) ); GST_INFO ("Kmsc version: %s", get_version () ); load_config (config, confFile); /* Start transport */ transport->start (); GST_INFO ("Mediaserver started"); loop->run (); signalHandler.reset(); deleteCertificate (); transport->stop(); transport.reset(); return 0; } <commit_msg>Raise a proper error when configuration file cannot be read<commit_after>/* * (C) Copyright 2013 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ #include <config.h> #include <glibmm.h> #include <fstream> #include <iostream> #include <boost/filesystem.hpp> #include "version.hpp" #include <glib/gstdio.h> #include <ftw.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "TransportFactory.hpp" #include <SignalHandler.hpp> #include <ServerMethods.hpp> #include <gst/gst.h> #include <boost/program_options.hpp> #include <boost/exception/diagnostic_information.hpp> #include "logging.hpp" #include "modules.hpp" #define GST_CAT_DEFAULT kurento_media_server GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaServer" const std::string DEFAULT_CONFIG_FILE = "/etc/kurento/kurento.conf.json"; const std::string ENV_PREFIX = "KURENTO_"; using namespace ::kurento; static std::shared_ptr<Transport> transport; __pid_t pid; Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (); static gchar *tmp_dir; Glib::RefPtr<Glib::IOChannel> channel; static void load_config (boost::property_tree::ptree &config, const std::string &file_name) { boost::filesystem::path configFilePath (file_name); GST_INFO ("Reading configuration from: %s", file_name.c_str () ); try { boost::property_tree::read_json (file_name, config); } catch (boost::property_tree::ptree_error &e) { GST_ERROR ("Error reading configuration: %s", e.what() ); std::cerr << "Error reading configuration: " << e.what() << std::endl; exit (1); } config.add ("configPath", configFilePath.parent_path().string() ); pid = getpid(); GST_INFO ("Configuration loaded successfully"); std::shared_ptr<ServerMethods> serverMethods (new ServerMethods (config) ); try { transport = TransportFactory::create_transport (config, serverMethods); } catch (std::exception &e) { GST_ERROR ("Error creating transport: %s", e.what() ); exit (1); } } static void signal_handler (uint32_t signo) { static unsigned int __terminated = 0; switch (signo) { case SIGINT: case SIGTERM: if (__terminated == 0) { GST_DEBUG ("Terminating."); loop->quit (); } __terminated = 1; break; case SIGPIPE: GST_DEBUG ("Ignore sigpipe signal"); break; case SIGSEGV: GST_DEBUG ("Segmentation fault. Aborting process execution"); abort (); default: break; } } static int delete_file (const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int rv = g_remove (fpath); if (rv) { GST_WARNING ("Error deleting file: %s. %s", fpath, strerror (errno) ); } return rv; } static void remove_recursive (const gchar *path) { nftw (path, delete_file, 64, FTW_DEPTH | FTW_PHYS); } static void deleteCertificate () { // Only parent process can delete certificate if (pid != getpid() ) { return; } if (tmp_dir != NULL) { remove_recursive (tmp_dir); g_free (tmp_dir); } } static std::string environment_adaptor (std::string &input) { /* Look for KMS_ prefix and change to lower case */ if (input.find (ENV_PREFIX) == 0) { std::string aux = input.substr (ENV_PREFIX.size() ); std::transform (aux.begin(), aux.end(), aux.begin(), [] (int c) -> int { return (c == '_') ? '-' : tolower (c); }); return aux; } return ""; } int main (int argc, char **argv) { sigset_t mask; std::shared_ptr <SignalHandler> signalHandler; boost::property_tree::ptree config; std::string confFile; std::string path; Glib::init(); gst_init (&argc, &argv); GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); gst_debug_remove_log_function_by_data (NULL); gst_debug_add_log_function (log_function, NULL, NULL); try { boost::program_options::options_description desc ("kurento-media-server usage"); desc.add_options() ("help,h", "Display this help message") ("version,v", "Display the version number") ("modules-path,p", boost::program_options::value<std::string> (&path), "Path where kurento modules can be found") ("conf-file,f", boost::program_options::value<std::string> (&confFile)->default_value (DEFAULT_CONFIG_FILE), "Configuration file location"); boost::program_options::variables_map vm; boost::program_options::store (boost::program_options::parse_command_line (argc, argv, desc), vm); boost::program_options::store (boost::program_options::parse_environment (desc, &environment_adaptor), vm); boost::program_options::notify (vm); if (vm.count ("help") ) { std::cout << desc << "\n"; exit (0); } loadModules (path); if (vm.count ("version") ) { print_version(); exit (0); } } catch (boost::program_options::error &e) { std::cerr << "Error : " << e.what() << std::endl; exit (1); } /* Install our signal handler */ sigemptyset (&mask); sigaddset (&mask, SIGINT); sigaddset (&mask, SIGTERM); sigaddset (&mask, SIGSEGV); sigaddset (&mask, SIGPIPE); signalHandler = std::shared_ptr <SignalHandler> (new SignalHandler (mask, signal_handler) ); GST_INFO ("Kmsc version: %s", get_version () ); load_config (config, confFile); /* Start transport */ transport->start (); GST_INFO ("Mediaserver started"); loop->run (); signalHandler.reset(); deleteCertificate (); transport->stop(); transport.reset(); return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #include "TelegramServerUser.hpp" #include "DcConfiguration.hpp" #include "LocalCluster.hpp" #include "Session.hpp" #include "Utils.hpp" #include <QCoreApplication> #include <QDebug> #include <QStandardPaths> using namespace Telegram::Server; #ifdef USE_DBUS_NOTIFIER #include <QDBusConnection> #include <QDBusMessage> #include "ServerApi.hpp" #include "DefaultAuthorizationProvider.hpp" class DBusCodeAuthProvider : public Authorization::DefaultProvider { protected: Authorization::Code generateCode(Session *session, const QString &identifier) override; }; Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier) { Authorization::Code code = DefaultProvider::generateCode(session, identifier); QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"), QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("Notify")); message.setArguments({ QCoreApplication::applicationName(), QVariant::fromValue(0u), QString(), QStringLiteral("New auth code request"), QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip), QStringList(), QVariantMap(), 3000 }); // QString app_name, uint replaces_id, QString app_icon, QString summary, // QString body, QStringList actions, QVariantMap hints, int timeout QDBusConnection::sessionBus().send(message); return code; } #endif // USE_DBUS_NOTIFIER int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); a.setApplicationName(QStringLiteral("TelegramQt Server")); Telegram::initialize(); Telegram::DcConfiguration configuration; const QVector<Telegram::DcOption> dcOptions = { Telegram::DcOption(QStringLiteral("127.0.0.1"), 11441, 1), Telegram::DcOption(QStringLiteral("127.0.0.2"), 11442, 2), Telegram::DcOption(QStringLiteral("127.0.0.3"), 11443, 3), }; configuration.dcOptions = dcOptions; const Telegram::RsaKey key = Telegram::Utils::loadRsaPrivateKeyFromFile( QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first() + QStringLiteral("/TelegramServer/private_key.pem")); if (!key.isValid()) { qCritical() << "Unable to read RSA key. Please read README.md for more information."; return -1; } LocalCluster cluster; cluster.setServerPrivateRsaKey(key); cluster.setServerConfiguration(configuration); #ifdef USE_DBUS_NOTIFIER DBusCodeAuthProvider authProvider; cluster.setAuthorizationProvider(&authProvider); qInfo() << "DBus auth code provider enabled"; #endif cluster.start(); if (LocalUser *u = cluster.addUser(QStringLiteral("5432101"), /* dc */ 1)) { u->setFirstName(QStringLiteral("Dc1User1")); u->setLastName(QStringLiteral("Dc1")); u->setPlainPassword(QStringLiteral("mypassword")); } if (LocalUser *u = cluster.addUser(QStringLiteral("6432101"), /* dc */ 1)) { u->setFirstName(QStringLiteral("Dc1User2")); u->setLastName(QStringLiteral("Dc1")); u->setPlainPassword(QStringLiteral("mypassword")); } if (LocalUser *u = cluster.addUser(QStringLiteral("5432102"), /* dc */ 2)) { u->setFirstName(QStringLiteral("Dc2User1")); u->setLastName(QStringLiteral("Dc2")); } if (LocalUser *u = cluster.addUser(QStringLiteral("5432103"), /* dc */ 3)) { u->setFirstName(QStringLiteral("Dc3User1")); u->setLastName(QStringLiteral("Dc3")); u->setPlainPassword(QStringLiteral("hispassword")); } LocalUser *user1dc1 = cluster.getUser(QStringLiteral("5432101")); LocalUser *user2dc1 = cluster.getUser(QStringLiteral("6432101")); LocalUser *user3dc2 = cluster.getUser(QStringLiteral("5432102")); user1dc1->importContact(user2dc1->toContact()); user1dc1->importContact(user3dc2->toContact()); user2dc1->importContact(user1dc1->toContact()); user3dc2->importContact(user1dc1->toContact()); return a.exec(); } <commit_msg>Server: remove test users from main function<commit_after>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #include "TelegramServerUser.hpp" #include "DcConfiguration.hpp" #include "LocalCluster.hpp" #include "Session.hpp" #include "Utils.hpp" #include <QCoreApplication> #include <QDebug> #include <QStandardPaths> using namespace Telegram::Server; #ifdef USE_DBUS_NOTIFIER #include <QDBusConnection> #include <QDBusMessage> #include "ServerApi.hpp" #include "DefaultAuthorizationProvider.hpp" class DBusCodeAuthProvider : public Authorization::DefaultProvider { protected: Authorization::Code generateCode(Session *session, const QString &identifier) override; }; Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier) { Authorization::Code code = DefaultProvider::generateCode(session, identifier); QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("/org/freedesktop/Notifications"), QStringLiteral("org.freedesktop.Notifications"), QStringLiteral("Notify")); message.setArguments({ QCoreApplication::applicationName(), QVariant::fromValue(0u), QString(), QStringLiteral("New auth code request"), QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip), QStringList(), QVariantMap(), 3000 }); // QString app_name, uint replaces_id, QString app_icon, QString summary, // QString body, QStringList actions, QVariantMap hints, int timeout QDBusConnection::sessionBus().send(message); return code; } #endif // USE_DBUS_NOTIFIER int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); a.setApplicationName(QStringLiteral("TelegramQt Server")); Telegram::initialize(); Telegram::DcConfiguration configuration; const QVector<Telegram::DcOption> dcOptions = { Telegram::DcOption(QStringLiteral("127.0.0.1"), 11441, 1), Telegram::DcOption(QStringLiteral("127.0.0.2"), 11442, 2), Telegram::DcOption(QStringLiteral("127.0.0.3"), 11443, 3), }; configuration.dcOptions = dcOptions; const Telegram::RsaKey key = Telegram::Utils::loadRsaPrivateKeyFromFile( QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first() + QStringLiteral("/TelegramServer/private_key.pem")); if (!key.isValid()) { qCritical() << "Unable to read RSA key. Please read README.md for more information."; return -1; } LocalCluster cluster; cluster.setServerPrivateRsaKey(key); cluster.setServerConfiguration(configuration); #ifdef USE_DBUS_NOTIFIER DBusCodeAuthProvider authProvider; cluster.setAuthorizationProvider(&authProvider); qInfo() << "DBus auth code provider enabled"; #endif cluster.start(); return a.exec(); } <|endoftext|>
<commit_before>// // server_main.cpp // sophos // // Created by Raphael Bost on 03/04/2016. // Copyright © 2016 Raphael Bost. All rights reserved. // #include "sophos_server.hpp" #include <stdio.h> #include <csignal> grpc::Server *server_ptr__ = NULL; void exit_handler(int signal) { std::cout << "\nExiting ... " << server_ptr__ << std::endl; if (server_ptr__) { server_ptr__->Shutdown(); } }; int main(int argc, char** argv) { std::signal(SIGTERM, exit_handler); std::signal(SIGINT, exit_handler); sse::sophos::run_sophos_server("0.0.0.0:4242", "/Users/raphaelbost/Code/sse/sophos/test.ssdb", &server_ptr__); std::cout << "Done" << std::endl; return 0; }<commit_msg>Forgot a signal handler<commit_after>// // server_main.cpp // sophos // // Created by Raphael Bost on 03/04/2016. // Copyright © 2016 Raphael Bost. All rights reserved. // #include "sophos_server.hpp" #include <stdio.h> #include <csignal> grpc::Server *server_ptr__ = NULL; void exit_handler(int signal) { std::cout << "\nExiting ... " << server_ptr__ << std::endl; if (server_ptr__) { server_ptr__->Shutdown(); } }; int main(int argc, char** argv) { std::signal(SIGTERM, exit_handler); std::signal(SIGINT, exit_handler); std::signal(SIGQUIT, exit_handler); sse::sophos::run_sophos_server("0.0.0.0:4242", "/Users/raphaelbost/Code/sse/sophos/test.ssdb", &server_ptr__); std::cout << "Done" << std::endl; return 0; }<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef EP_HH #define EP_HH 1 #include <pthread.h> #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdexcept> #include <iostream> #include <queue> #include <set> #include <queue> #include <memcached/engine.h> #include "kvstore.hh" #include "locks.hh" #include "sqlite-kvstore.hh" #define DEFAULT_TXN_SIZE 100000 #define MIN_DATA_AGE 120 extern "C" { extern rel_time_t (*ep_current_time)(); } struct ep_stats { // How long it took us to load the data from disk. time_t warmupTime; // Whether we're warming up. bool warmupComplete; // Number of records warmed up. size_t warmedUp; // size of the input queue size_t queue_size; // Size of the in-process (output) queue. size_t flusher_todo; // Objects that were rejected from persistence for being too fresh. size_t tooYoung; // How long an object is dirty before written. rel_time_t dirtyAge; rel_time_t dirtyAgeHighWat; // How old persisted data was when it hit the persistence layer rel_time_t dataAge; rel_time_t dataAgeHighWat; // How long does it take to do an entire flush cycle. rel_time_t flushDuration; rel_time_t flushDurationHighWat; // Amount of time spent in the commit phase. rel_time_t commit_time; }; // Forward declaration for StoredValue class HashTable; class StoredValue { public: StoredValue() : key(), value(), flags(0), exptime(0), dirtied(0), next(NULL) { } StoredValue(std::string &k, const char *v, size_t nv, StoredValue *n) : key(k), value(), flags(0), exptime(0), dirtied(0), next(n) { setValue(v, nv); } StoredValue(const Item &itm, StoredValue *n) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.nbytes), flags(itm.flags), exptime(itm.exptime), dirtied(0), next(n) { markDirty(); } StoredValue(const Item &itm, StoredValue *n, bool setDirty) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.nbytes), flags(itm.flags), exptime(itm.exptime), dirtied(0), next(n) { if (setDirty) { markDirty(); } else { markClean(NULL, NULL); } } ~StoredValue() { } void markDirty() { data_age = ep_current_time(); if (!isDirty()) { dirtied = data_age; } } void reDirty(rel_time_t dirtyAge, rel_time_t dataAge) { data_age = dataAge; dirtied = dirtyAge; } // returns time this object was dirtied. void markClean(rel_time_t *dirtyAge, rel_time_t *dataAge) { if (dirtyAge) { *dirtyAge = dirtied; } if (dataAge) { *dataAge = data_age; } dirtied = 0; data_age = 0; } bool isDirty() const { return dirtied != 0; } bool isClean() const { return dirtied == 0; } const std::string &getKey() const { return key; } const std::string &getValue() const { return value; } rel_time_t getExptime() const { return exptime; } uint32_t getFlags() const { return flags; } void setValue(const char *v, const size_t nv) { value.assign(v, nv); markDirty(); } private: friend class HashTable; std::string key; std::string value; uint32_t flags; rel_time_t exptime; rel_time_t dirtied; rel_time_t data_age; StoredValue *next; DISALLOW_COPY_AND_ASSIGN(StoredValue); }; typedef enum { NOT_FOUND, WAS_CLEAN, WAS_DIRTY } mutation_type_t; class HashTableVisitor { public: virtual ~HashTableVisitor() {} virtual void visit(StoredValue *v) = 0; }; class HashTable { public: // Construct with number of buckets and locks. HashTable(size_t s = 196613, size_t l = 193) { size = s; n_locks = l; active = true; values = (StoredValue**)calloc(s, sizeof(StoredValue**)); mutexes = new Mutex[l]; } ~HashTable() { clear(); delete []mutexes; free(values); } void clear() { assert(active); for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); while (values[i]) { StoredValue *v = values[i]; values[i] = v->next; delete v; } } } StoredValue *find(std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); return unlocked_find(key, bucket_num); } mutation_type_t set(const Item &val) { assert(active); mutation_type_t rv = NOT_FOUND; int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); Item &itm = const_cast<Item&>(val); if (v) { rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY; v->setValue(itm.getData(), itm.nbytes); } else { v = new StoredValue(itm, values[bucket_num]); values[bucket_num] = v; } return rv; } bool add(const Item &val, bool isDirty) { assert(active); int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); if (v) { return false; } else { v = new StoredValue(const_cast<Item&>(val), values[bucket_num], isDirty); values[bucket_num] = v; } return true; } bool add(const Item &val) { return add(val, true); } StoredValue *unlocked_find(const std::string &key, int bucket_num) { StoredValue *v = values[bucket_num]; while (v) { if (key.compare(v->key) == 0) { return v; } v = v->next; } return NULL; } inline int bucket(const std::string &key) { assert(active); int h=5381; int i=0; const char *str = key.c_str(); for(i=0; str[i] != 0x00; i++) { h = ((h << 5) + h) ^ str[i]; } return abs(h) % (int)size; } // Get the mutex for a bucket (for doing your own lock management) inline Mutex &getMutex(int bucket_num) { assert(active); assert(bucket_num < (int)size); assert(bucket_num >= 0); int lock_num = bucket_num % (int)n_locks; assert(lock_num < (int)n_locks); assert(lock_num >= 0); return mutexes[lock_num]; } // True if it existed bool del(const std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); StoredValue *v = values[bucket_num]; // Special case empty bucket. if (!v) { return false; } // Special case the first one if (key.compare(v->key) == 0) { values[bucket_num] = v->next; delete v; return true; } while (v->next) { if (key.compare(v->next->key) == 0) { StoredValue *tmp = v->next; v->next = v->next->next; delete tmp; return true; } } return false; } void visit(HashTableVisitor &visitor) { for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); StoredValue *v = values[i]; while (v) { visitor.visit(v); v = v->next; } } } private: size_t size; size_t n_locks; bool active; StoredValue **values; Mutex *mutexes; DISALLOW_COPY_AND_ASSIGN(HashTable); }; // Forward declaration class Flusher; /** * Helper class used to insert items into the storage by using * the KVStore::dump method to load items from the database */ class LoadStorageKVPairCallback : public Callback<GetValue> { public: LoadStorageKVPairCallback(HashTable &ht, struct ep_stats &st) : hashtable(ht), stats(st) { } void callback(GetValue &val) { if (val.value != NULL) { hashtable.add(*val.value, false); delete val.value; } stats.warmedUp++; } private: HashTable &hashtable; struct ep_stats &stats; }; typedef enum { STOPPED=0, RUNNING=1, SHUTTING_DOWN=2 } flusher_state; class EventuallyPersistentStore : public KVStore { public: EventuallyPersistentStore(KVStore *t, size_t est=32768); ~EventuallyPersistentStore(); void set(const Item &item, Callback<bool> &cb); void get(const std::string &key, Callback<GetValue> &cb); void del(const std::string &key, Callback<bool> &cb); void getStats(struct ep_stats *out); void resetStats(void); void stopFlusher(void); void startFlusher(void); flusher_state getFlusherState(); virtual void dump(Callback<GetValue>&) { throw std::runtime_error("not implemented"); } void reset(); void visit(HashTableVisitor &visitor) { storage.visit(visitor); } void warmup() { static_cast<MultiDBSqlite3*>(underlying)->dump(loadStorageKVPairCallback); } private: /* Queue an item to be written to persistent layer. */ void queueDirty(const std::string &key) { if (doPersistence) { // Assume locked. towrite->push(key); stats.queue_size++; mutex.notify(); } } void flush(bool shouldWait); void flushSome(std::queue<std::string> *q, Callback<bool> &cb, std::queue<std::string> *rejectQueue); void flushOne(std::queue<std::string> *q, Callback<bool> &cb, std::queue<std::string> *rejectQueue); void flusherStopped(); void initQueue(); friend class Flusher; bool doPersistence; KVStore *underlying; size_t est_size; Flusher *flusher; HashTable storage; SyncObject mutex; std::queue<std::string> *towrite; pthread_t thread; struct ep_stats stats; LoadStorageKVPairCallback loadStorageKVPairCallback; flusher_state flusherState; int txnSize; DISALLOW_COPY_AND_ASSIGN(EventuallyPersistentStore); }; class Flusher { public: Flusher(EventuallyPersistentStore *st) { store = st; running = true; } ~Flusher() { stop(); } void stop() { running = false; } void run() { running = true; time_t start = time(NULL); store->warmup(); store->stats.warmupTime = time(NULL) - start; store->stats.warmupComplete = true; try { while(running) { store->flush(true); } std::cout << "Shutting down flusher." << std::endl; store->flush(false); std::cout << "Flusher stopped" << std::endl; } catch(std::runtime_error &e) { std::cerr << "Exception in executor loop: " << e.what() << std::endl; assert(false); } // Signal our completion. store->flusherStopped(); } private: EventuallyPersistentStore *store; volatile bool running; }; #endif /* EP_HH */ <commit_msg>Larger txn size.<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef EP_HH #define EP_HH 1 #include <pthread.h> #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <stdexcept> #include <iostream> #include <queue> #include <set> #include <queue> #include <memcached/engine.h> #include "kvstore.hh" #include "locks.hh" #include "sqlite-kvstore.hh" #define DEFAULT_TXN_SIZE 500000 #define MIN_DATA_AGE 120 extern "C" { extern rel_time_t (*ep_current_time)(); } struct ep_stats { // How long it took us to load the data from disk. time_t warmupTime; // Whether we're warming up. bool warmupComplete; // Number of records warmed up. size_t warmedUp; // size of the input queue size_t queue_size; // Size of the in-process (output) queue. size_t flusher_todo; // Objects that were rejected from persistence for being too fresh. size_t tooYoung; // How long an object is dirty before written. rel_time_t dirtyAge; rel_time_t dirtyAgeHighWat; // How old persisted data was when it hit the persistence layer rel_time_t dataAge; rel_time_t dataAgeHighWat; // How long does it take to do an entire flush cycle. rel_time_t flushDuration; rel_time_t flushDurationHighWat; // Amount of time spent in the commit phase. rel_time_t commit_time; }; // Forward declaration for StoredValue class HashTable; class StoredValue { public: StoredValue() : key(), value(), flags(0), exptime(0), dirtied(0), next(NULL) { } StoredValue(std::string &k, const char *v, size_t nv, StoredValue *n) : key(k), value(), flags(0), exptime(0), dirtied(0), next(n) { setValue(v, nv); } StoredValue(const Item &itm, StoredValue *n) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.nbytes), flags(itm.flags), exptime(itm.exptime), dirtied(0), next(n) { markDirty(); } StoredValue(const Item &itm, StoredValue *n, bool setDirty) : key(itm.getKey()), value(const_cast<Item&>(itm).getData(), itm.nbytes), flags(itm.flags), exptime(itm.exptime), dirtied(0), next(n) { if (setDirty) { markDirty(); } else { markClean(NULL, NULL); } } ~StoredValue() { } void markDirty() { data_age = ep_current_time(); if (!isDirty()) { dirtied = data_age; } } void reDirty(rel_time_t dirtyAge, rel_time_t dataAge) { data_age = dataAge; dirtied = dirtyAge; } // returns time this object was dirtied. void markClean(rel_time_t *dirtyAge, rel_time_t *dataAge) { if (dirtyAge) { *dirtyAge = dirtied; } if (dataAge) { *dataAge = data_age; } dirtied = 0; data_age = 0; } bool isDirty() const { return dirtied != 0; } bool isClean() const { return dirtied == 0; } const std::string &getKey() const { return key; } const std::string &getValue() const { return value; } rel_time_t getExptime() const { return exptime; } uint32_t getFlags() const { return flags; } void setValue(const char *v, const size_t nv) { value.assign(v, nv); markDirty(); } private: friend class HashTable; std::string key; std::string value; uint32_t flags; rel_time_t exptime; rel_time_t dirtied; rel_time_t data_age; StoredValue *next; DISALLOW_COPY_AND_ASSIGN(StoredValue); }; typedef enum { NOT_FOUND, WAS_CLEAN, WAS_DIRTY } mutation_type_t; class HashTableVisitor { public: virtual ~HashTableVisitor() {} virtual void visit(StoredValue *v) = 0; }; class HashTable { public: // Construct with number of buckets and locks. HashTable(size_t s = 196613, size_t l = 193) { size = s; n_locks = l; active = true; values = (StoredValue**)calloc(s, sizeof(StoredValue**)); mutexes = new Mutex[l]; } ~HashTable() { clear(); delete []mutexes; free(values); } void clear() { assert(active); for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); while (values[i]) { StoredValue *v = values[i]; values[i] = v->next; delete v; } } } StoredValue *find(std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); return unlocked_find(key, bucket_num); } mutation_type_t set(const Item &val) { assert(active); mutation_type_t rv = NOT_FOUND; int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); Item &itm = const_cast<Item&>(val); if (v) { rv = v->isClean() ? WAS_CLEAN : WAS_DIRTY; v->setValue(itm.getData(), itm.nbytes); } else { v = new StoredValue(itm, values[bucket_num]); values[bucket_num] = v; } return rv; } bool add(const Item &val, bool isDirty) { assert(active); int bucket_num = bucket(val.getKey()); LockHolder lh(getMutex(bucket_num)); StoredValue *v = unlocked_find(val.getKey(), bucket_num); if (v) { return false; } else { v = new StoredValue(const_cast<Item&>(val), values[bucket_num], isDirty); values[bucket_num] = v; } return true; } bool add(const Item &val) { return add(val, true); } StoredValue *unlocked_find(const std::string &key, int bucket_num) { StoredValue *v = values[bucket_num]; while (v) { if (key.compare(v->key) == 0) { return v; } v = v->next; } return NULL; } inline int bucket(const std::string &key) { assert(active); int h=5381; int i=0; const char *str = key.c_str(); for(i=0; str[i] != 0x00; i++) { h = ((h << 5) + h) ^ str[i]; } return abs(h) % (int)size; } // Get the mutex for a bucket (for doing your own lock management) inline Mutex &getMutex(int bucket_num) { assert(active); assert(bucket_num < (int)size); assert(bucket_num >= 0); int lock_num = bucket_num % (int)n_locks; assert(lock_num < (int)n_locks); assert(lock_num >= 0); return mutexes[lock_num]; } // True if it existed bool del(const std::string &key) { assert(active); int bucket_num = bucket(key); LockHolder lh(getMutex(bucket_num)); StoredValue *v = values[bucket_num]; // Special case empty bucket. if (!v) { return false; } // Special case the first one if (key.compare(v->key) == 0) { values[bucket_num] = v->next; delete v; return true; } while (v->next) { if (key.compare(v->next->key) == 0) { StoredValue *tmp = v->next; v->next = v->next->next; delete tmp; return true; } } return false; } void visit(HashTableVisitor &visitor) { for (int i = 0; i < (int)size; i++) { LockHolder lh(getMutex(i)); StoredValue *v = values[i]; while (v) { visitor.visit(v); v = v->next; } } } private: size_t size; size_t n_locks; bool active; StoredValue **values; Mutex *mutexes; DISALLOW_COPY_AND_ASSIGN(HashTable); }; // Forward declaration class Flusher; /** * Helper class used to insert items into the storage by using * the KVStore::dump method to load items from the database */ class LoadStorageKVPairCallback : public Callback<GetValue> { public: LoadStorageKVPairCallback(HashTable &ht, struct ep_stats &st) : hashtable(ht), stats(st) { } void callback(GetValue &val) { if (val.value != NULL) { hashtable.add(*val.value, false); delete val.value; } stats.warmedUp++; } private: HashTable &hashtable; struct ep_stats &stats; }; typedef enum { STOPPED=0, RUNNING=1, SHUTTING_DOWN=2 } flusher_state; class EventuallyPersistentStore : public KVStore { public: EventuallyPersistentStore(KVStore *t, size_t est=32768); ~EventuallyPersistentStore(); void set(const Item &item, Callback<bool> &cb); void get(const std::string &key, Callback<GetValue> &cb); void del(const std::string &key, Callback<bool> &cb); void getStats(struct ep_stats *out); void resetStats(void); void stopFlusher(void); void startFlusher(void); flusher_state getFlusherState(); virtual void dump(Callback<GetValue>&) { throw std::runtime_error("not implemented"); } void reset(); void visit(HashTableVisitor &visitor) { storage.visit(visitor); } void warmup() { static_cast<MultiDBSqlite3*>(underlying)->dump(loadStorageKVPairCallback); } private: /* Queue an item to be written to persistent layer. */ void queueDirty(const std::string &key) { if (doPersistence) { // Assume locked. towrite->push(key); stats.queue_size++; mutex.notify(); } } void flush(bool shouldWait); void flushSome(std::queue<std::string> *q, Callback<bool> &cb, std::queue<std::string> *rejectQueue); void flushOne(std::queue<std::string> *q, Callback<bool> &cb, std::queue<std::string> *rejectQueue); void flusherStopped(); void initQueue(); friend class Flusher; bool doPersistence; KVStore *underlying; size_t est_size; Flusher *flusher; HashTable storage; SyncObject mutex; std::queue<std::string> *towrite; pthread_t thread; struct ep_stats stats; LoadStorageKVPairCallback loadStorageKVPairCallback; flusher_state flusherState; int txnSize; DISALLOW_COPY_AND_ASSIGN(EventuallyPersistentStore); }; class Flusher { public: Flusher(EventuallyPersistentStore *st) { store = st; running = true; } ~Flusher() { stop(); } void stop() { running = false; } void run() { running = true; time_t start = time(NULL); store->warmup(); store->stats.warmupTime = time(NULL) - start; store->stats.warmupComplete = true; try { while(running) { store->flush(true); } std::cout << "Shutting down flusher." << std::endl; store->flush(false); std::cout << "Flusher stopped" << std::endl; } catch(std::runtime_error &e) { std::cerr << "Exception in executor loop: " << e.what() << std::endl; assert(false); } // Signal our completion. store->flusherStopped(); } private: EventuallyPersistentStore *store; volatile bool running; }; #endif /* EP_HH */ <|endoftext|>
<commit_before>#include <parseopt.h> #include <arpc.h> #include "lsdctl_prot.h" /* Much of the structure and code here is taken from sfskey.C which is GPL2'd. * See http://www.fs.net/ */ bool opt_verbose; bool opt_quiet; char *control_socket = "/tmp/lsdctl-sock"; /* Prototypes for table. */ void lsdctl_help (int argc, char *argv[]); void lsdctl_exit (int argc, char *argv[]); void lsdctl_trace (int argc, char *argv[]); void lsdctl_stabilize (int argc, char *argv[]); void lsdctl_replicate (int argc, char *argv[]); void lsdctl_getloctab (int argc, char *argv[]); void lsdctl_getrpcstats (int argc, char *argv[]); void lsdctl_getmyids (int argc, char *argv[]); void lsdctl_getdhashstats (int argc, char *argv[]); struct modevec { const char *name; void (*fn) (int argc, char **argv); const char *usage; }; const modevec modes[] = { { "help", lsdctl_help, "help" }, { "exit", lsdctl_exit, "exit" }, { "trace", lsdctl_trace, "trace crit|warning|info|trace" }, { "stabilize", lsdctl_stabilize, "stabilize start|stop" }, { "replicate", lsdctl_replicate, "replicate [-r] start|stop" }, { "loctab", lsdctl_getloctab, "loctab [vnodenum]" }, { "rpcstats", lsdctl_getrpcstats, "rpcstats [-rf]" }, { "myids", lsdctl_getmyids, "myids" }, { "dhashstats", lsdctl_getdhashstats, "dhashstats [-l] [vnodenum]" }, { NULL, NULL, NULL } }; static const modevec *lsdctl_mode; void usage (void) { warnx << "usage: " << progname << " [-S sock] [-vq] "; if (lsdctl_mode && lsdctl_mode->usage) warnx << lsdctl_mode->usage << "\n"; else warnx << "command [args]\n"; exit (1); } /**************************************/ /* The commands that do the real work */ /**************************************/ void lsdctl_help (int argc, char *argv[]) { strbuf msg; msg << "usage: " << progname << " [-S sock] [-vq] command [args]\n"; for (const modevec *mp = modes; mp->name; mp++) if (mp->usage) msg << " " << progname << " " << mp->usage << "\n"; make_sync (1); msg.tosuio ()->output (1); exit (0); } ptr<aclnt> lsdctl_connect (str sockname) { int fd = unixsocket_connect (sockname); if (fd < 0) { fatal ("lsdctl_connect: Error connecting to %s: %s\n", sockname.cstr (), strerror (errno)); } ptr<aclnt> c = aclnt::alloc (axprt_unix::alloc (fd, 1024*1025), lsdctl_prog_1); return c; } void lsdctl_exit (int argc, char *argv[]) { // Ignore arguments ptr<aclnt> c = lsdctl_connect (control_socket); clnt_stat err = c->scall (LSDCTL_EXIT, NULL, NULL); if (err) fatal << "lsdctl_exit: " << err << "\n"; exit (0); } void lsdctl_trace (int argc, char *argv[]) { if (optind + 1 != argc) usage (); char *level = argv[optind]; int lvl = 0; // XXX wouldn't it be nice to cleanly derive from utils/modlogger.h? if (!strcmp ("crit", level)) lvl = -1; else if (!strcmp ("warning", level)) lvl = 0; else if (!strcmp ("info", level)) lvl = 1; else if (!strcmp ("trace", level)) lvl = 2; else usage (); ptr<aclnt> c = lsdctl_connect (control_socket); clnt_stat err = c->scall (LSDCTL_SETTRACELEVEL, &lvl, NULL); if (err) fatal << "lsdctl_trace: " << err << "\n"; exit (0); } void lsdctl_stabilize (int argc, char *argv[]) { if (optind + 1 != argc) usage (); bool t = false; char *toggle = argv[optind]; if (!strcmp ("start", toggle)) t = true; else if (!strcmp ("stop", toggle)) t = false; ptr<aclnt> c = lsdctl_connect (control_socket); bool res = !t; clnt_stat err = c->scall (LSDCTL_SETSTABILIZE, &t, &res); if (err) fatal << "lsdctl_stabilize: " << err << "\n"; if (res != t) warnx << "lsdctl_stabilize: lsd did not switch to new state.\n"; exit (0); } void lsdctl_replicate (int argc, char *argv[]) { ptr<lsdctl_setreplicate_arg> t = New refcounted<lsdctl_setreplicate_arg> (); t->randomize = false; int ch; while ((ch = getopt (argc, argv, "r")) != -1) switch (ch) { case 'r': t->randomize = true; break; default: usage (); break; } if (optind + 1 != argc) usage (); char *toggle = argv[optind]; if (!strcmp ("start", toggle)) t->enable = true; else if (!strcmp ("stop", toggle)) t->enable = false; ptr<aclnt> c = lsdctl_connect (control_socket); bool res = !t; clnt_stat err = c->scall (LSDCTL_SETREPLICATE, t, &res); if (err) fatal << "lsdctl_replicate: " << err << "\n"; if (res != t->enable) warnx << "lsdctl_replicate: lsd did not switch to new state.\n"; exit (0); } strbuf lsdctl_nlist_printer (ptr<lsdctl_nodeinfolist> nl) { strbuf out; for (size_t i = 0; i < nl->nlist.size (); i++) { out << nl->nlist[i].n << " " << nl->nlist[i].addr.hostname << " " << nl->nlist[i].addr.port << " " << nl->nlist[i].vnode_num << " "; for (size_t j = 0; j < nl->nlist[i].coords.size (); j++) out << nl->nlist[i].coords[j] << " "; out << nl->nlist[i].a_lat << " " << nl->nlist[i].a_var << " " << nl->nlist[i].nrpc << " " << nl->nlist[i].pinned << " " << nl->nlist[i].alive << " " << nl->nlist[i].dead_time << "\n"; } return out; } void lsdctl_getmyids (int argc, char *argv[]) { ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> (); ptr<aclnt> c = lsdctl_connect (control_socket); clnt_stat err = c->scall (LSDCTL_GETMYIDS, NULL, nl); if (err) fatal << "lsdctl_getmyids: " << err << "\n"; strbuf out (lsdctl_nlist_printer (nl)); make_sync (1); out.tosuio ()->output (1); exit (0); } void lsdctl_getloctab (int argc, char *argv[]) { int vnode = 0; // XXX should actually get vnode from cmd line. ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> (); ptr<aclnt> c = lsdctl_connect (control_socket); clnt_stat err = c->scall (LSDCTL_GETLOCTABLE, &vnode, nl); if (err) fatal << "lsdctl_getloctab: " << err << "\n"; strbuf out (lsdctl_nlist_printer (nl)); make_sync (1); out.tosuio ()->output (1); exit (0); } static int statcmp (const void *a, const void *b) { return strcmp (((lsdctl_rpcstat *) a)->key.cstr (), ((lsdctl_rpcstat *) b)->key.cstr ()); } void lsdctl_getrpcstats (int argc, char *argv[]) { int ch; bool clear = false; bool formatted = false; while ((ch = getopt (argc, argv, "rf")) != -1) switch (ch) { case 'r': clear = true; break; case 'f': formatted = true; break; default: usage (); break; } ptr<lsdctl_rpcstatlist> nl = New refcounted <lsdctl_rpcstatlist> (); ptr<aclnt> c = lsdctl_connect (control_socket); clnt_stat err = c->scall (LSDCTL_GETRPCSTATS, &clear, nl); if (err) fatal << "lsdctl_rpcstats: " << err << "\n"; strbuf out; out.fmt ("Interval %llu.%llu s\n", nl->interval / 1000000, nl->interval % 1000000); if (formatted) out.fmt ("%54s | %-15s | %-15s | %-15s\n", "Proc", "Calls (bytes/#)", "Rexmits", "Replies"); lsdctl_rpcstat *ndx = New lsdctl_rpcstat[nl->stats.size ()]; for (size_t i = 0; i < nl->stats.size (); i++) ndx[i] = nl->stats[i]; qsort (ndx, nl->stats.size (), sizeof (lsdctl_rpcstat), &statcmp); str fmt; if (formatted) fmt = "%-54s | %7llu %7llu | %7llu %7llu | %7llu %7llu\n"; else fmt = "%s %llu %llu %llu %llu %llu %llu\n"; for (size_t i = 0; i < nl->stats.size (); i++) { out.fmt (fmt, ndx[i].key.cstr (), ndx[i].call_bytes, ndx[i].ncall, ndx[i].rexmit_bytes, ndx[i].nrexmit, ndx[i].reply_bytes, ndx[i].nreply); } delete[] ndx; make_sync (1); out.tosuio ()->output (1); exit (0); } void lsdctl_getdhashstats (int argc, char *argv[]) { int ch; lsdctl_getdhashstats_arg a; a.vnode = 0; a.doblockinfo = false; while ((ch = getopt (argc, argv, "l")) != -1) switch (ch) { case 'l': a.doblockinfo = true; break; default: usage (); break; } if (optind != argc) if (!convertint (argv[optind], &a.vnode)) usage (); ptr<aclnt> c = lsdctl_connect (control_socket); ptr<lsdctl_dhashstats> ds = New refcounted <lsdctl_dhashstats> (); clnt_stat err = c->scall (LSDCTL_GETDHASHSTATS, &a, ds); if (err) fatal << "lsdctl_getdhashstats: " << err << "\n"; strbuf out; out << "Statistics:\n"; for (size_t i = 0; i < ds->stats.size (); i++) out << " " << ds->stats[i].desc << " " << ds->stats[i].value << "\n"; for (size_t i = 0; i < ds->blocks.size (); i++) out << ds->blocks[i].id << "\t" << ds->blocks[i].missing.size () << "\n"; if (a.doblockinfo) out << ds->hack; make_sync (1); out.tosuio ()->output (1); exit (0); } int main (int argc, char *argv[]) { setprogname (argv[0]); putenv ("POSIXLY_CORRECT=1"); // Prevents Linux from reordering options int ch; while ((ch = getopt (argc, argv, "S:vq")) != -1) switch (ch) { case 'S': control_socket = optarg; break; case 'v': opt_verbose = true; break; case 'q': opt_quiet = true; break; default: usage (); break; } if (optind >= argc) usage (); // Prepare to dispatch on command name const modevec *mp; for (mp = modes; mp->name; mp++) if (!strcmp (argv[optind], mp->name)) break; if (!mp->name) usage (); lsdctl_mode = mp; // Skip over command name... optind++; mp->fn (argc, argv); // amain (); return 0; } <commit_msg>Add [-t timeout] option (defaulting to 2min) so that we don't get hundreds of lsdctl processes blocking on hung lsd processes (on PlanetLab). Switched to using timedcall and amain instead of scall because scall's timeout doesn't work.<commit_after>#include <parseopt.h> #include <arpc.h> #include "lsdctl_prot.h" /* Much of the structure and code here is taken from sfskey.C which is GPL2'd. * See http://www.fs.net/ */ bool opt_verbose; bool opt_quiet; int opt_timeout (120); char *control_socket = "/tmp/lsdctl-sock"; /* Prototypes for table. */ void lsdctl_help (int argc, char *argv[]); void lsdctl_exit (int argc, char *argv[]); void lsdctl_trace (int argc, char *argv[]); void lsdctl_stabilize (int argc, char *argv[]); void lsdctl_replicate (int argc, char *argv[]); void lsdctl_getloctab (int argc, char *argv[]); void lsdctl_getrpcstats (int argc, char *argv[]); void lsdctl_getmyids (int argc, char *argv[]); void lsdctl_getdhashstats (int argc, char *argv[]); struct modevec { const char *name; void (*fn) (int argc, char **argv); const char *usage; }; const modevec modes[] = { { "help", lsdctl_help, "help" }, { "exit", lsdctl_exit, "exit" }, { "trace", lsdctl_trace, "trace crit|warning|info|trace" }, { "stabilize", lsdctl_stabilize, "stabilize start|stop" }, { "replicate", lsdctl_replicate, "replicate [-r] start|stop" }, { "loctab", lsdctl_getloctab, "loctab [vnodenum]" }, { "rpcstats", lsdctl_getrpcstats, "rpcstats [-rf]" }, { "myids", lsdctl_getmyids, "myids" }, { "dhashstats", lsdctl_getdhashstats, "dhashstats [-l] [vnodenum]" }, { NULL, NULL, NULL } }; static const modevec *lsdctl_mode; void usage (void) { warnx << "usage: " << progname << " [-S sock] [-t timeout] [-vq] "; if (lsdctl_mode && lsdctl_mode->usage) warnx << lsdctl_mode->usage << "\n"; else warnx << "command [args]\n"; exit (1); } /**************************************/ /* The commands that do the real work */ /**************************************/ void lsdctl_help (int argc, char *argv[]) { strbuf msg; msg << "usage: " << progname << " [-S sock] [-vq] command [args]\n"; for (const modevec *mp = modes; mp->name; mp++) if (mp->usage) msg << " " << progname << " " << mp->usage << "\n"; make_sync (1); msg.tosuio ()->output (1); exit (0); } ptr<aclnt> lsdctl_connect (str sockname) { int fd = unixsocket_connect (sockname); if (fd < 0) { fatal ("lsdctl_connect: Error connecting to %s: %s\n", sockname.cstr (), strerror (errno)); } ptr<aclnt> c = aclnt::alloc (axprt_unix::alloc (fd, 1024*1025), lsdctl_prog_1); return c; } void lsdctl_default (str name, clnt_stat err) { if (err) fatal << name << ": " << err << "\n"; exit (0); } void lsdctl_exit (int argc, char *argv[]) { // Ignore arguments ptr<aclnt> c = lsdctl_connect (control_socket); c->timedcall (opt_timeout, LSDCTL_EXIT, NULL, NULL, wrap (&lsdctl_default, "lsdctl_exit")); } void lsdctl_trace (int argc, char *argv[]) { if (optind + 1 != argc) usage (); char *level = argv[optind]; int lvl = 0; // XXX wouldn't it be nice to cleanly derive from utils/modlogger.h? if (!strcmp ("crit", level)) lvl = -1; else if (!strcmp ("warning", level)) lvl = 0; else if (!strcmp ("info", level)) lvl = 1; else if (!strcmp ("trace", level)) lvl = 2; else usage (); ptr<aclnt> c = lsdctl_connect (control_socket); c->timedcall (opt_timeout, LSDCTL_SETTRACELEVEL, &lvl, NULL, wrap (&lsdctl_default, "lsdctl_trace")); } void lsdctl_toggle_cb (ptr<bool> res, bool t, str name, clnt_stat err) { if (err) fatal << name << ": " << err << "\n"; if (*res != t) warnx << name << ": lsd did not switch to new state.\n"; exit (0); } void lsdctl_stabilize (int argc, char *argv[]) { if (optind + 1 != argc) usage (); bool t = false; char *toggle = argv[optind]; if (!strcmp ("start", toggle)) t = true; else if (!strcmp ("stop", toggle)) t = false; ptr<aclnt> c = lsdctl_connect (control_socket); ptr<bool> res = New refcounted<bool> (!t); c->timedcall (opt_timeout, LSDCTL_SETSTABILIZE, &t, res, wrap (&lsdctl_toggle_cb, res, t, "lsdctl_stabilize")); } void lsdctl_replicate (int argc, char *argv[]) { ptr<lsdctl_setreplicate_arg> t = New refcounted<lsdctl_setreplicate_arg> (); t->randomize = false; int ch; while ((ch = getopt (argc, argv, "r")) != -1) switch (ch) { case 'r': t->randomize = true; break; default: usage (); break; } if (optind + 1 != argc) usage (); char *toggle = argv[optind]; if (!strcmp ("start", toggle)) t->enable = true; else if (!strcmp ("stop", toggle)) t->enable = false; ptr<aclnt> c = lsdctl_connect (control_socket); ptr<bool> res = New refcounted<bool> (!t->enable); c->timedcall (opt_timeout, LSDCTL_SETREPLICATE, t, res, wrap (&lsdctl_toggle_cb, res, t->enable, "lsdctl_replicate")); } void lsdctl_nlist_printer_cb (ptr<lsdctl_nodeinfolist> nl, str name, clnt_stat err) { if (err) fatal << name << ": " << err << "\n"; strbuf out; for (size_t i = 0; i < nl->nlist.size (); i++) { out << nl->nlist[i].n << " " << nl->nlist[i].addr.hostname << " " << nl->nlist[i].addr.port << " " << nl->nlist[i].vnode_num << " "; for (size_t j = 0; j < nl->nlist[i].coords.size (); j++) out << nl->nlist[i].coords[j] << " "; out << nl->nlist[i].a_lat << " " << nl->nlist[i].a_var << " " << nl->nlist[i].nrpc << " " << nl->nlist[i].pinned << " " << nl->nlist[i].alive << " " << nl->nlist[i].dead_time << "\n"; } make_sync (1); out.tosuio ()->output (1); exit (0); } void lsdctl_getmyids (int argc, char *argv[]) { ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> (); ptr<aclnt> c = lsdctl_connect (control_socket); c->timedcall (opt_timeout, LSDCTL_GETMYIDS, NULL, nl, wrap (&lsdctl_nlist_printer_cb, nl, "lsdctl_getmyids")); } void lsdctl_getloctab (int argc, char *argv[]) { int vnode = 0; // XXX should actually get vnode from cmd line. ptr<lsdctl_nodeinfolist> nl = New refcounted <lsdctl_nodeinfolist> (); ptr<aclnt> c = lsdctl_connect (control_socket); c->timedcall (opt_timeout, LSDCTL_GETLOCTABLE, &vnode, nl, wrap (&lsdctl_nlist_printer_cb, nl, "lsdctl_getloctab")); } static int statcmp (const void *a, const void *b) { return strcmp (((lsdctl_rpcstat *) a)->key.cstr (), ((lsdctl_rpcstat *) b)->key.cstr ()); } void lsdctl_getrpcstats_cb (bool formatted, ptr<lsdctl_rpcstatlist> nl, clnt_stat err) { if (err) fatal << "lsdctl_rpcstats: " << err << "\n"; strbuf out; out.fmt ("Interval %llu.%llu s\n", nl->interval / 1000000, nl->interval % 1000000); if (formatted) out.fmt ("%54s | %-15s | %-15s | %-15s\n", "Proc", "Calls (bytes/#)", "Rexmits", "Replies"); lsdctl_rpcstat *ndx = New lsdctl_rpcstat[nl->stats.size ()]; for (size_t i = 0; i < nl->stats.size (); i++) ndx[i] = nl->stats[i]; qsort (ndx, nl->stats.size (), sizeof (lsdctl_rpcstat), &statcmp); str fmt; if (formatted) fmt = "%-54s | %7llu %7llu | %7llu %7llu | %7llu %7llu\n"; else fmt = "%s %llu %llu %llu %llu %llu %llu\n"; for (size_t i = 0; i < nl->stats.size (); i++) { out.fmt (fmt, ndx[i].key.cstr (), ndx[i].call_bytes, ndx[i].ncall, ndx[i].rexmit_bytes, ndx[i].nrexmit, ndx[i].reply_bytes, ndx[i].nreply); } delete[] ndx; make_sync (1); out.tosuio ()->output (1); exit (0); } void lsdctl_getrpcstats (int argc, char *argv[]) { int ch; bool clear = false; bool formatted = false; while ((ch = getopt (argc, argv, "rf")) != -1) switch (ch) { case 'r': clear = true; break; case 'f': formatted = true; break; default: usage (); break; } ptr<lsdctl_rpcstatlist> nl = New refcounted <lsdctl_rpcstatlist> (); ptr<aclnt> c = lsdctl_connect (control_socket); c->timedcall (opt_timeout, LSDCTL_GETRPCSTATS, &clear, nl, wrap (&lsdctl_getrpcstats_cb, formatted, nl)); } void lsdctl_getdhashstats_cb (ptr<lsdctl_getdhashstats_arg> a, ptr<lsdctl_dhashstats> ds, clnt_stat err) { if (err) fatal << "lsdctl_getdhashstats: " << err << "\n"; strbuf out; out << "Statistics:\n"; for (size_t i = 0; i < ds->stats.size (); i++) out << " " << ds->stats[i].desc << " " << ds->stats[i].value << "\n"; for (size_t i = 0; i < ds->blocks.size (); i++) out << ds->blocks[i].id << "\t" << ds->blocks[i].missing.size () << "\n"; if (a->doblockinfo) out << ds->hack; make_sync (1); out.tosuio ()->output (1); exit (0); } void lsdctl_getdhashstats (int argc, char *argv[]) { int ch; ptr<lsdctl_getdhashstats_arg> a = New refcounted<lsdctl_getdhashstats_arg> (); a->vnode = 0; a->doblockinfo = false; while ((ch = getopt (argc, argv, "l")) != -1) switch (ch) { case 'l': a->doblockinfo = true; break; default: usage (); break; } if (optind != argc) if (!convertint (argv[optind], &a->vnode)) usage (); ptr<aclnt> c = lsdctl_connect (control_socket); ptr<lsdctl_dhashstats> ds = New refcounted <lsdctl_dhashstats> (); c->timedcall (opt_timeout, LSDCTL_GETDHASHSTATS, a, ds, wrap (&lsdctl_getdhashstats_cb, a, ds)); } int main (int argc, char *argv[]) { setprogname (argv[0]); putenv ("POSIXLY_CORRECT=1"); // Prevents Linux from reordering options int ch; while ((ch = getopt (argc, argv, "S:t:vq")) != -1) switch (ch) { case 'S': control_socket = optarg; break; case 't': if (!convertint (optarg, &opt_timeout)) usage (); break; case 'v': opt_verbose = true; break; case 'q': opt_quiet = true; break; default: usage (); break; } if (optind >= argc) usage (); // Prepare to dispatch on command name const modevec *mp; for (mp = modes; mp->name; mp++) if (!strcmp (argv[optind], mp->name)) break; if (!mp->name) usage (); lsdctl_mode = mp; // Skip over command name... optind++; mp->fn (argc, argv); amain (); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hazelcast/client/HazelcastClient.h> #include <hazelcast/client/serialization/IdentifiedDataSerializable.h> #include <hazelcast/client/serialization/ObjectDataInput.h> #include <hazelcast/client/serialization/ObjectDataOutput.h> class Person { public: Person() { } Person(const std::string& n) : name(n) { } void setName(const std::string& n) { name = n; } const std::string& getName() const { return name; } private: std::string name; }; int getHazelcastTypeId(const Person* p){ return 666; } class CustomSerializer : public hazelcast::client::serialization::Serializer<Person> { public: void write(hazelcast::client::serialization::ObjectDataOutput & out, const Person& object) { out.writeInt(666); out.writeUTF(&(object.getName())); out.writeInt(666); } void read(hazelcast::client::serialization::ObjectDataInput & in, Person& object) { int i = in.readInt(); assert(i == 666); object.setName(*(in.readUTF())); i = in.readInt(); assert(i == 666); } int getHazelcastTypeId() const { return 666; }; }; std::ostream &operator<<(std::ostream &out, const Person &p) { const std::string & str = p.getName(); out << str; return out; } int main() { hazelcast::client::ClientConfig config; hazelcast::client::SerializationConfig serializationConfig; serializationConfig.registerSerializer(boost::shared_ptr<hazelcast::client::serialization::SerializerBase>(new CustomSerializer())); config.setSerializationConfig(serializationConfig); hazelcast::client::HazelcastClient hz(config); hazelcast::client::IMap<std::string, Person> map = hz.getMap<std::string, Person>("map"); Person testPerson("bar"); map.put("foo", testPerson); std::cout << *(map.get("foo")) << std::endl; std::cout << "Finished" << std::endl; return 0; } <commit_msg>Enhanced custom serialization example to use namespace for the object.<commit_after>/* * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hazelcast/client/HazelcastClient.h> #include <hazelcast/client/serialization/IdentifiedDataSerializable.h> #include <hazelcast/client/serialization/ObjectDataInput.h> #include <hazelcast/client/serialization/ObjectDataOutput.h> namespace test1 { namespace test2 { class Person { public: Person() { } Person(const std::string& n) : name(n) { } void setName(const std::string& n) { name = n; } const std::string& getName() const { return name; } private: std::string name; }; /** * Put the free function in the same namespace as the object it operates on */ int getHazelcastTypeId(const Person* p){ return 666; } } } class CustomSerializer : public hazelcast::client::serialization::Serializer<test1::test2::Person> { public: void write(hazelcast::client::serialization::ObjectDataOutput & out, const test1::test2::Person& object) { out.writeInt(666); out.writeUTF(&(object.getName())); out.writeInt(666); } void read(hazelcast::client::serialization::ObjectDataInput & in, test1::test2::Person& object) { int i = in.readInt(); assert(i == 666); object.setName(*(in.readUTF())); i = in.readInt(); assert(i == 666); } int getHazelcastTypeId() const { return 666; }; }; std::ostream &operator<<(std::ostream &out, const test1::test2::Person &p) { const std::string & str = p.getName(); out << str; return out; } int main() { hazelcast::client::ClientConfig config; hazelcast::client::SerializationConfig serializationConfig; serializationConfig.registerSerializer(boost::shared_ptr<hazelcast::client::serialization::SerializerBase>(new CustomSerializer())); config.setSerializationConfig(serializationConfig); hazelcast::client::HazelcastClient hz(config); hazelcast::client::IMap<std::string, test1::test2::Person> map = hz.getMap<std::string, test1::test2::Person>("map"); test1::test2::Person testPerson("bar"); map.put("foo", testPerson); std::cout << *(map.get("foo")) << std::endl; std::cout << "Finished" << std::endl; return 0; } <|endoftext|>
<commit_before>#include "sotauptaneclient.h" #include <unistd.h> #include <boost/make_shared.hpp> #include "crypto.h" #include "httpclient.h" #include "json/json.h" #include "logger.h" #include "uptane/exceptions.h" #include "utils.h" SotaUptaneClient::SotaUptaneClient(const Config &config_in, event::Channel *events_channel_in, Uptane::Repository &repo) : config(config_in), events_channel(events_channel_in), uptane_repo(repo), last_targets_version(-1) {} void SotaUptaneClient::run(command::Channel *commands_channel) { while (true) { *commands_channel << boost::make_shared<command::GetUpdateRequests>(); boost::this_thread::sleep_for(boost::chrono::seconds(config.uptane.polling_sec)); } } bool SotaUptaneClient::isInstalled(const Uptane::Target &target) { if (target.ecu_identifier() == uptane_repo.getPrimaryEcuSerial()) { return target.filename() == OstreePackage::getEcu(uptane_repo.getPrimaryEcuSerial(), config.ostree.sysroot).ref_name; } else { // TODO: iterate through secondaries, compare version when found, throw exception otherwise return true; } } std::vector<Uptane::Target> SotaUptaneClient::findForEcu(const std::vector<Uptane::Target> &targets, std::string ecu_id) { std::vector<Uptane::Target> result; for (std::vector<Uptane::Target>::const_iterator it = targets.begin(); it != targets.end(); ++it) { if (it->ecu_identifier() == ecu_id) { result.push_back(*it); } } return result; } data::InstallOutcome SotaUptaneClient::OstreeInstall(const Uptane::Target &target) { std::size_t pos = target.filename().find_last_of("-"); if (pos == std::string::npos) return data::InstallOutcome(data::INSTALL_FAILED, "Invalid refname"); std::string branch_name = target.filename().substr(0, pos); std::string refhash = target.filename().substr(pos + 1, std::string::npos); if (branch_name.empty() || refhash.empty()) return data::InstallOutcome(data::INSTALL_FAILED, "Invalid refname"); OstreePackage package(target.ecu_identifier(), target.filename(), branch_name, refhash, "", config.uptane.ostree_server); data::PackageManagerCredentials cred; // TODO: use storage cred.ca_file = config.tls.ca_file(); #ifdef BUILD_P11 if (config.tls.pkey_source == kPkcs11) cred.pkey_file = uptane_repo.pkcs11_tls_keyname; else // TODO: use storage cred.pkey_file = config.tls.pkey_file(); if (config.tls.cert_source == kPkcs11) cred.cert_file = uptane_repo.pkcs11_tls_certname; else // TODO: use storage cred.cert_file = config.tls.client_certificate(); #else // TODO: use storage cred.pkey_file = config.tls.pkey_file(); // TODO: use storage cred.cert_file = config.tls.client_certificate(); #endif return package.install(cred, config.ostree); } Json::Value SotaUptaneClient::OstreeInstallAndManifest(const Uptane::Target &target) { Json::Value operation_result; if (isInstalled(target)) { data::InstallOutcome outcome(data::UpdateResultCode::ALREADY_PROCESSED, "Package already installed"); operation_result["operation_result"] = data::OperationResult::fromOutcome(target.filename(), outcome).toJson(); } else if ((!target.format().empty() && target.format() != "OSTREE") || target.length() != 0) { data::InstallOutcome outcome(data::UpdateResultCode::VALIDATION_FAILED, "Cannot install a non-OSTree package on an OSTree system"); operation_result["operation_result"] = data::OperationResult::fromOutcome(target.filename(), outcome).toJson(); } else { data::OperationResult result = data::OperationResult::fromOutcome(target.filename(), OstreeInstall(target)); operation_result["operation_result"] = result.toJson(); } Json::Value unsigned_ecu_version = OstreePackage::getEcu(uptane_repo.getPrimaryEcuSerial(), config.ostree.sysroot).toEcuVersion(operation_result); ENGINE *crypto_engine = NULL; #ifdef BUILD_P11 if ((uptane_repo.key_source == kPkcs11)) crypto_engine = uptane_repo.p11.getEngine(); #endif Json::Value ecu_version_signed = Crypto::signTuf(crypto_engine, uptane_repo.primary_private_key, uptane_repo.primary_public_key_id, unsigned_ecu_version); return ecu_version_signed; } void SotaUptaneClient::reportHWInfo() { Json::Value hw_info = Utils::getHardwareInfo(); if (!hw_info.empty()) uptane_repo.http.put(config.tls.server + "/core/system_info", hw_info); } void SotaUptaneClient::reportInstalledPackages() { uptane_repo.http.put(config.tls.server + "/core/installed", Ostree::getInstalledPackages(config.ostree.packages_file)); } void SotaUptaneClient::runForever(command::Channel *commands_channel) { LOGGER_LOG(LVL_debug, "Checking if device is provisioned..."); if (!uptane_repo.initialize()) { throw std::runtime_error("Fatal error of tls or ecu device registration"); } LOGGER_LOG(LVL_debug, "... provisioned OK"); reportHWInfo(); reportInstalledPackages(); boost::thread polling_thread(boost::bind(&SotaUptaneClient::run, this, commands_channel)); boost::shared_ptr<command::BaseCommand> command; while (*commands_channel >> command) { LOGGER_LOG(LVL_info, "got " + command->variant + " command"); try { if (command->variant == "GetUpdateRequests") { Json::Value unsigned_ecu_version = OstreePackage::getEcu(uptane_repo.getPrimaryEcuSerial(), config.ostree.sysroot) .toEcuVersion(Json::nullValue); uptane_repo.putManifest(uptane_repo.getCurrentVersionManifests(unsigned_ecu_version)); std::pair<int, std::vector<Uptane::Target> > updates = uptane_repo.getTargets(); if (updates.second.size() && updates.first > last_targets_version) { LOGGER_LOG(LVL_info, "got new updates"); *events_channel << boost::make_shared<event::UptaneTargetsUpdated>(updates.second); last_targets_version = updates.first; // What if we fail install targets? } else { LOGGER_LOG(LVL_info, "no new updates, sending UptaneTimestampUpdated event"); *events_channel << boost::make_shared<event::UptaneTimestampUpdated>(); } } else if (command->variant == "UptaneInstall") { std::vector<Uptane::Target> updates = command->toChild<command::UptaneInstall>()->packages; std::vector<Uptane::Target> primary_updates = findForEcu(updates, uptane_repo.getPrimaryEcuSerial()); Json::Value manifests(Json::arrayValue); manifests = uptane_repo.updateSecondaries(updates); if (primary_updates.size()) { // assuming one OSTree OS per primary => there can be only one OSTree update for (std::vector<Uptane::Target>::const_iterator it = primary_updates.begin(); it != primary_updates.end(); ++it) { Json::Value p_manifest = OstreeInstallAndManifest(*it); manifests.append(p_manifest); break; } // TODO: other updates for primary } uptane_repo.putManifest(manifests); } else if (command->variant == "Shutdown") { polling_thread.interrupt(); polling_thread.join(); return; } } catch (Uptane::Exception e) { LOGGER_LOG(LVL_error, e.what()); } catch (const std::exception &ex) { LOGGER_LOG(LVL_error, "Unknown exception was thrown: " << ex.what()); } } } <commit_msg>Fix build failure<commit_after>#include "sotauptaneclient.h" #include <unistd.h> #include <boost/make_shared.hpp> #include "crypto.h" #include "httpclient.h" #include "json/json.h" #include "logger.h" #include "uptane/exceptions.h" #include "utils.h" SotaUptaneClient::SotaUptaneClient(const Config &config_in, event::Channel *events_channel_in, Uptane::Repository &repo) : config(config_in), events_channel(events_channel_in), uptane_repo(repo), last_targets_version(-1) {} void SotaUptaneClient::run(command::Channel *commands_channel) { while (true) { *commands_channel << boost::make_shared<command::GetUpdateRequests>(); boost::this_thread::sleep_for(boost::chrono::seconds(config.uptane.polling_sec)); } } bool SotaUptaneClient::isInstalled(const Uptane::Target &target) { if (target.ecu_identifier() == uptane_repo.getPrimaryEcuSerial()) { return target.filename() == OstreePackage::getEcu(uptane_repo.getPrimaryEcuSerial(), config.ostree.sysroot).ref_name; } else { // TODO: iterate through secondaries, compare version when found, throw exception otherwise return true; } } std::vector<Uptane::Target> SotaUptaneClient::findForEcu(const std::vector<Uptane::Target> &targets, std::string ecu_id) { std::vector<Uptane::Target> result; for (std::vector<Uptane::Target>::const_iterator it = targets.begin(); it != targets.end(); ++it) { if (it->ecu_identifier() == ecu_id) { result.push_back(*it); } } return result; } data::InstallOutcome SotaUptaneClient::OstreeInstall(const Uptane::Target &target) { std::size_t pos = target.filename().find_last_of("-"); if (pos == std::string::npos) return data::InstallOutcome(data::INSTALL_FAILED, "Invalid refname"); std::string branch_name = target.filename().substr(0, pos); std::string refhash = target.filename().substr(pos + 1, std::string::npos); if (branch_name.empty() || refhash.empty()) return data::InstallOutcome(data::INSTALL_FAILED, "Invalid refname"); OstreePackage package(target.ecu_identifier(), target.filename(), branch_name, refhash, "", config.uptane.ostree_server); data::PackageManagerCredentials cred; // TODO: use storage cred.ca_file = config.tls.ca_file(); #ifdef BUILD_P11 if (config.tls.pkey_source == kPkcs11) cred.pkey_file = uptane_repo.pkcs11_tls_keyname; else // TODO: use storage cred.pkey_file = config.tls.pkey_file(); if (config.tls.cert_source == kPkcs11) cred.cert_file = uptane_repo.pkcs11_tls_certname; else // TODO: use storage cred.cert_file = config.tls.client_certificate(); #else // TODO: use storage cred.pkey_file = config.tls.pkey_file(); // TODO: use storage cred.cert_file = config.tls.client_certificate(); #endif return package.install(cred, config.ostree); } Json::Value SotaUptaneClient::OstreeInstallAndManifest(const Uptane::Target &target) { Json::Value operation_result; if (isInstalled(target)) { data::InstallOutcome outcome(data::ALREADY_PROCESSED, "Package already installed"); operation_result["operation_result"] = data::OperationResult::fromOutcome(target.filename(), outcome).toJson(); } else if ((!target.format().empty() && target.format() != "OSTREE") || target.length() != 0) { data::InstallOutcome outcome(data::VALIDATION_FAILED, "Cannot install a non-OSTree package on an OSTree system"); operation_result["operation_result"] = data::OperationResult::fromOutcome(target.filename(), outcome).toJson(); } else { data::OperationResult result = data::OperationResult::fromOutcome(target.filename(), OstreeInstall(target)); operation_result["operation_result"] = result.toJson(); } Json::Value unsigned_ecu_version = OstreePackage::getEcu(uptane_repo.getPrimaryEcuSerial(), config.ostree.sysroot).toEcuVersion(operation_result); ENGINE *crypto_engine = NULL; #ifdef BUILD_P11 if ((uptane_repo.key_source == kPkcs11)) crypto_engine = uptane_repo.p11.getEngine(); #endif Json::Value ecu_version_signed = Crypto::signTuf(crypto_engine, uptane_repo.primary_private_key, uptane_repo.primary_public_key_id, unsigned_ecu_version); return ecu_version_signed; } void SotaUptaneClient::reportHWInfo() { Json::Value hw_info = Utils::getHardwareInfo(); if (!hw_info.empty()) uptane_repo.http.put(config.tls.server + "/core/system_info", hw_info); } void SotaUptaneClient::reportInstalledPackages() { uptane_repo.http.put(config.tls.server + "/core/installed", Ostree::getInstalledPackages(config.ostree.packages_file)); } void SotaUptaneClient::runForever(command::Channel *commands_channel) { LOGGER_LOG(LVL_debug, "Checking if device is provisioned..."); if (!uptane_repo.initialize()) { throw std::runtime_error("Fatal error of tls or ecu device registration"); } LOGGER_LOG(LVL_debug, "... provisioned OK"); reportHWInfo(); reportInstalledPackages(); boost::thread polling_thread(boost::bind(&SotaUptaneClient::run, this, commands_channel)); boost::shared_ptr<command::BaseCommand> command; while (*commands_channel >> command) { LOGGER_LOG(LVL_info, "got " + command->variant + " command"); try { if (command->variant == "GetUpdateRequests") { Json::Value unsigned_ecu_version = OstreePackage::getEcu(uptane_repo.getPrimaryEcuSerial(), config.ostree.sysroot) .toEcuVersion(Json::nullValue); uptane_repo.putManifest(uptane_repo.getCurrentVersionManifests(unsigned_ecu_version)); std::pair<int, std::vector<Uptane::Target> > updates = uptane_repo.getTargets(); if (updates.second.size() && updates.first > last_targets_version) { LOGGER_LOG(LVL_info, "got new updates"); *events_channel << boost::make_shared<event::UptaneTargetsUpdated>(updates.second); last_targets_version = updates.first; // What if we fail install targets? } else { LOGGER_LOG(LVL_info, "no new updates, sending UptaneTimestampUpdated event"); *events_channel << boost::make_shared<event::UptaneTimestampUpdated>(); } } else if (command->variant == "UptaneInstall") { std::vector<Uptane::Target> updates = command->toChild<command::UptaneInstall>()->packages; std::vector<Uptane::Target> primary_updates = findForEcu(updates, uptane_repo.getPrimaryEcuSerial()); Json::Value manifests(Json::arrayValue); manifests = uptane_repo.updateSecondaries(updates); if (primary_updates.size()) { // assuming one OSTree OS per primary => there can be only one OSTree update for (std::vector<Uptane::Target>::const_iterator it = primary_updates.begin(); it != primary_updates.end(); ++it) { Json::Value p_manifest = OstreeInstallAndManifest(*it); manifests.append(p_manifest); break; } // TODO: other updates for primary } uptane_repo.putManifest(manifests); } else if (command->variant == "Shutdown") { polling_thread.interrupt(); polling_thread.join(); return; } } catch (Uptane::Exception e) { LOGGER_LOG(LVL_error, e.what()); } catch (const std::exception &ex) { LOGGER_LOG(LVL_error, "Unknown exception was thrown: " << ex.what()); } } } <|endoftext|>
<commit_before>/* * StubModule.cpp * Copyright (C) 2017 by MegaMol Team * All rights reserved. Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/special/StubModule.h" #include "mmcore/CoreInstance.h" #include "mmcore/factories/CallAutoDescription.h" using namespace megamol; using namespace megamol::core; special::StubModule::StubModule(void) : Module(), inSlot("inSlot", "Inbound call"), outSlot("outSlot", "Outbound call") { } special::StubModule::~StubModule(void) { this->Release(); } bool special::StubModule::create(void) { for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) { this->inSlot.SetCompatibleCall(cd); for (unsigned int idx = 0; idx < cd->FunctionCount(); idx++) { this->outSlot.SetCallback(cd->ClassName(), cd->FunctionName(idx), &StubModule::stub); } } this->MakeSlotAvailable(&this->inSlot); this->MakeSlotAvailable(&this->outSlot); return true; } void special::StubModule::release(void) { } bool megamol::core::special::StubModule::stub(Call& c) { for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) { if (cd->IsDescribing(&c)) { for (unsigned int idx = 0; idx < cd->FunctionCount(); idx++) { try { c(idx); } catch (...) { return false; } } } } return true; } <commit_msg>Calls are now propagated to inbound calls<commit_after>/* * StubModule.cpp * Copyright (C) 2017 by MegaMol Team * All rights reserved. Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/special/StubModule.h" #include "mmcore/CoreInstance.h" #include "mmcore/factories/CallAutoDescription.h" using namespace megamol; using namespace megamol::core; special::StubModule::StubModule(void) : Module(), inSlot("inSlot", "Inbound call"), outSlot("outSlot", "Outbound call") { } special::StubModule::~StubModule(void) { this->Release(); } bool special::StubModule::create(void) { for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) { this->inSlot.SetCompatibleCall(cd); for (unsigned int idx = 0; idx < cd->FunctionCount(); idx++) { this->outSlot.SetCallback(cd->ClassName(), cd->FunctionName(idx), &StubModule::stub); } } this->MakeSlotAvailable(&this->inSlot); this->MakeSlotAvailable(&this->outSlot); return true; } void special::StubModule::release(void) { } bool megamol::core::special::StubModule::stub(Call& c) { for (auto cd : this->GetCoreInstance()->GetCallDescriptionManager()) { if (cd->IsDescribing(&c)) { for (unsigned int idx = 0; idx < cd->FunctionCount(); idx++) { try { this->inSlot.Call(idx); } catch (...) { return false; } } } } return true; } <|endoftext|>
<commit_before>// // Projectname: amos-ss16-proj5 // // Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5 // // This file is part of the AMOS Project 2016 @ FAU // (Friedrich-Alexander University Erlangen-Nürnberg) // // 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/>. // //opencv #include <opencv2/opencv.hpp> //local #include "../ObjectDetection/cascade_vehicle_detector.h" // #include "../ObjectDetection/daimler_people_detector.h" #include "../ObjectDetection/detection.h" #include "../ObjectDetection/hog_people_detector.h" #include "../StreamDecoder/image_view.h" #include "../ScenarioAnalysation/scenario.h" #include "../ScenarioAnalysation/humans_in_front_of_bus_scenario.h" #include "../ScenarioAnalysation/analyser.h" #include "controller.h" //define keys const int KEY_ESC = 27; const int KEY_SPACE = 32; void Controller::PlayAsVideo(std::string videofile) { FrameSelectorFactory frame_selector_factory(videofile); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); ImageView image_view; int protobuf_counts = pipeline->GetImageCount(); for (int i=0; i<protobuf_counts; i++) { Image * current_image = pipeline->ReadImage(i); image_view.ShowImage(current_image); delete current_image; current_image = NULL; if( cvWaitKey(5) == KEY_ESC ) break; } } void Controller::AnalyseVideo(std::string videofile) { ImageView image_view; FrameSelectorFactory frame_selector_factory(videofile); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); int protobuf_counts = pipeline->GetImageCount(); // DaimlerPeopleDetector peopleDetector; HOGPeopleDetector people_detector; CascadeVehicleDetector vehicle_detector; Detection detection(&people_detector, &vehicle_detector); // set up all objects needed for analysing std::vector<Scenario*> possible_scenarios; possible_scenarios.push_back(new HumansInFrontOfBusScenario()); Analyser analyser(possible_scenarios); for (int i=0; i<protobuf_counts; i++) { Image * current_image = pipeline->ReadImage(i); FrameDetectionData* current_detections = detection.ProcessFrame(current_image); if(!current_detections){ continue; } Scenario* scenario = analyser.Analyse(*current_detections); if(!scenario){ std::cout << "No scenario in frame " << i << " was detected!" <<std::endl; }else{ if( HumansInFrontOfBusScenario* result = dynamic_cast<HumansInFrontOfBusScenario*>(scenario) ){ // TODO here for later: inform the communication module that a "Humans in front of bus" scenario was detected std::cout << "HUMANS IN FRONT OF BUS !!!!!!!" << std::endl; } // for demo: show information about scenario in current frame std::cout << "Current detected scenario: " << scenario->GetScenarioInformation() << " in frame: " << i << std::endl; } int key = cvWaitKey(10); if(key == KEY_ESC) break; if (key == KEY_SPACE) key = cvWaitKey(0); delete current_image; current_image = NULL; delete current_detections; current_detections = NULL; delete scenario; scenario = NULL; } } void Controller::SaveAllImagesAsJPEG(std::string videofile) { FrameSelectorFactory frame_selector_factory(videofile); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); int protobuf_counts = pipeline->GetImageCount(); std::string filename = videofile.substr(videofile.find_last_of("/\\")+1); std::ostringstream os; for (int i=0; i<protobuf_counts; i++){ os << i; cv::imwrite(filename+"_"+os.str()+".jpeg", pipeline->ReadImage(i)->GetRGBImage()); } } <commit_msg>Removed segfault from controller in case when a scenario was detected<commit_after>// // Projectname: amos-ss16-proj5 // // Copyright (c) 2016 de.fau.cs.osr.amos2016.gruppe5 // // This file is part of the AMOS Project 2016 @ FAU // (Friedrich-Alexander University Erlangen-Nürnberg) // // 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/>. // //opencv #include <opencv2/opencv.hpp> //local #include "../ObjectDetection/cascade_vehicle_detector.h" // #include "../ObjectDetection/daimler_people_detector.h" #include "../ObjectDetection/detection.h" #include "../ObjectDetection/hog_people_detector.h" #include "../StreamDecoder/image_view.h" #include "../ScenarioAnalysation/scenario.h" #include "../ScenarioAnalysation/humans_in_front_of_bus_scenario.h" #include "../ScenarioAnalysation/analyser.h" #include "controller.h" //define keys const int KEY_ESC = 27; const int KEY_SPACE = 32; void Controller::PlayAsVideo(std::string videofile) { FrameSelectorFactory frame_selector_factory(videofile); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); ImageView image_view; int protobuf_counts = pipeline->GetImageCount(); for (int i=0; i<protobuf_counts; i++) { Image * current_image = pipeline->ReadImage(i); image_view.ShowImage(current_image); delete current_image; current_image = NULL; if( cvWaitKey(5) == KEY_ESC ) break; } } void Controller::AnalyseVideo(std::string videofile) { ImageView image_view; FrameSelectorFactory frame_selector_factory(videofile); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); int protobuf_counts = pipeline->GetImageCount(); // DaimlerPeopleDetector peopleDetector; HOGPeopleDetector people_detector; CascadeVehicleDetector vehicle_detector; Detection detection(&people_detector, &vehicle_detector); // set up all objects needed for analysing std::vector<Scenario*> possible_scenarios; possible_scenarios.push_back(new HumansInFrontOfBusScenario()); Analyser analyser(possible_scenarios); for (int i=0; i<protobuf_counts; i++) { Image * current_image = pipeline->ReadImage(i); FrameDetectionData* current_detections = detection.ProcessFrame(current_image); if(!current_detections){ continue; } Scenario* scenario = analyser.Analyse(*current_detections); if(!scenario){ std::cout << "No scenario in frame " << i << " was detected!" <<std::endl; }else{ if( HumansInFrontOfBusScenario* result = dynamic_cast<HumansInFrontOfBusScenario*>(scenario) ){ // TODO here for later: inform the communication module that a "Humans in front of bus" scenario was detected std::cout << "HUMANS IN FRONT OF BUS !!!!!!!" << std::endl; } // for demo: show information about scenario in current frame std::cout << "Current detected scenario: " << scenario->GetScenarioInformation() << " in frame: " << i << std::endl; } int key = cvWaitKey(10); if(key == KEY_ESC) break; if (key == KEY_SPACE) key = cvWaitKey(0); delete current_image; current_image = NULL; delete current_detections; current_detections = NULL; //delete scenario; scenario = NULL; } } void Controller::SaveAllImagesAsJPEG(std::string videofile) { FrameSelectorFactory frame_selector_factory(videofile); FrameSelector* pipeline = frame_selector_factory.GetFrameSelector(); int protobuf_counts = pipeline->GetImageCount(); std::string filename = videofile.substr(videofile.find_last_of("/\\")+1); std::ostringstream os; for (int i=0; i<protobuf_counts; i++){ os << i; cv::imwrite(filename+"_"+os.str()+".jpeg", pipeline->ReadImage(i)->GetRGBImage()); } } <|endoftext|>
<commit_before>#include "Arduino.h" #include "Nokia_5110.h" #include "Font.h" Nokia_5110::Nokia_5110(unsigned short RST, unsigned short CE, unsigned short DC, unsigned short DIN, unsigned short CLK){ _RST = RST; _CE = CE; _DC = DC; _DIN = DIN; _CLK = CLK; pinMode(RST, OUTPUT); pinMode(CE, OUTPUT); pinMode(DC, OUTPUT); pinMode(DIN, OUTPUT); pinMode(CLK, OUTPUT); reset(); extendedInstruction(); execute(0x14); // LCD bias mode 1:40 } void Nokia_5110::startTransmission(){ digitalWrite(_CE, LOW); } void Nokia_5110::endTransmission(){ digitalWrite(_CE, HIGH); } void Nokia_5110::transmitInformation(byte information){ startTransmission(); shiftOut(_DIN, _CLK, MSBFIRST, information); endTransmission(); } void Nokia_5110::execute(byte command){ initializeForSendingCommand(); transmitInformation(command); } void Nokia_5110::initializeForSendingCommand(){ digitalWrite(_DC, LOW); } /** * @param contrast could be 0 to 127 */ void Nokia_5110::setContrast(unsigned short value){ if(value > 127) return; extendedInstruction(); const unsigned short leastValue = 128; execute(byte(leastValue + value)); } void Nokia_5110::extendedInstruction(){ execute(0x21); } void Nokia_5110::basicInstruction(){ execute(0x20); } /** * Temperature Coefficient value could be one of 0, 1, 2 or 3; */ void Nokia_5110::setTemperatureCoefficient(unsigned short value){ if(value > 3) return; extendedInstruction(); const unsigned short leastValue = 4; execute(byte(leastValue + value)); } void Nokia_5110::reset(){ digitalWrite(_RST, LOW); digitalWrite(_RST, HIGH); clear(); } void Nokia_5110::turnOnAllSegments(){ basicInstruction(); execute(0x09); } void Nokia_5110::initializeForSendingData(){ digitalWrite(_DC, HIGH); } void Nokia_5110::print(char text[]){ setCursor(_cursorPositionX, _cursorPositionY); basicInstruction(); execute(0xC); //display normal mode initializeForSendingData(); int i = 0; while(text[i]){ byte fontByte[5]; unsigned short int byteArrayLength; findCorespondingByte(text[i], fontByte, byteArrayLength); for(short int i = 0; i < byteArrayLength ;i++){ transmitInformation(fontByte[i]); } transmitInformation(0x0); // add an empty line after each chars moveCursorInXAxis(byteArrayLength + 1); i++; } } void Nokia_5110::println(char text[]){ print(text); moveCursorInYAxis(1); } /** * Moves cursor in x axis by a number sepcified in method's parameter */ void Nokia_5110::moveCursorInXAxis(unsigned int by){ if(by == 0) return; _cursorPositionX++; if(_cursorPositionX > 83){ moveCursorInYAxis(1); _cursorPositionX = 0; } moveCursorInXAxis(--by); } /** * Moves cursor in y axis by a number sepcified in method's parameter */ void Nokia_5110::moveCursorInYAxis(unsigned int by){ if(by == 0) return; _cursorPositionY++; _cursorPositionX = 0; // for each y incrementation, reset the x axis :D if(_cursorPositionY > 5){ _cursorPositionY = 0; } moveCursorInYAxis(--by); } void Nokia_5110::setCursor(unsigned int xPosition, unsigned int yPosition){ _cursorPositionX = xPosition; _cursorPositionY = yPosition; basicInstruction(); //set x position unsigned short int leastXPositionValue = 128; execute(byte(leastXPositionValue + xPosition)); //set y position unsigned short int leastYPositionValue = 64; execute(byte(leastYPositionValue + yPosition)); } void Nokia_5110::clear(){ initializeForSendingData(); int i = 504; while(i >= 0){ transmitInformation(0x0); i--; } } void Nokia_5110::clear(unsigned int inRow, unsigned int fromColumn, unsigned int toColumn){ // toColumn has to be more than from Column, otherwise flip the values :D unsigned int temp; if(fromColumn > toColumn){ temp = fromColumn; fromColumn = toColumn; toColumn = temp; } unsigned int counter = fromColumn; while(counter <= toColumn){ setCursor(counter, inRow); initializeForSendingData(); transmitInformation(0x0); counter++; } setCursor(fromColumn, inRow); } <commit_msg>move to the first row and column after clearing the dislapy<commit_after>#include "Arduino.h" #include "Nokia_5110.h" #include "Font.h" Nokia_5110::Nokia_5110(unsigned short RST, unsigned short CE, unsigned short DC, unsigned short DIN, unsigned short CLK){ _RST = RST; _CE = CE; _DC = DC; _DIN = DIN; _CLK = CLK; pinMode(RST, OUTPUT); pinMode(CE, OUTPUT); pinMode(DC, OUTPUT); pinMode(DIN, OUTPUT); pinMode(CLK, OUTPUT); reset(); extendedInstruction(); execute(0x14); // LCD bias mode 1:40 } void Nokia_5110::startTransmission(){ digitalWrite(_CE, LOW); } void Nokia_5110::endTransmission(){ digitalWrite(_CE, HIGH); } void Nokia_5110::transmitInformation(byte information){ startTransmission(); shiftOut(_DIN, _CLK, MSBFIRST, information); endTransmission(); } void Nokia_5110::execute(byte command){ initializeForSendingCommand(); transmitInformation(command); } void Nokia_5110::initializeForSendingCommand(){ digitalWrite(_DC, LOW); } /** * @param contrast could be 0 to 127 */ void Nokia_5110::setContrast(unsigned short value){ if(value > 127) return; extendedInstruction(); const unsigned short leastValue = 128; execute(byte(leastValue + value)); } void Nokia_5110::extendedInstruction(){ execute(0x21); } void Nokia_5110::basicInstruction(){ execute(0x20); } /** * Temperature Coefficient value could be one of 0, 1, 2 or 3; */ void Nokia_5110::setTemperatureCoefficient(unsigned short value){ if(value > 3) return; extendedInstruction(); const unsigned short leastValue = 4; execute(byte(leastValue + value)); } void Nokia_5110::reset(){ digitalWrite(_RST, LOW); digitalWrite(_RST, HIGH); clear(); } void Nokia_5110::turnOnAllSegments(){ basicInstruction(); execute(0x09); } void Nokia_5110::initializeForSendingData(){ digitalWrite(_DC, HIGH); } void Nokia_5110::print(char text[]){ setCursor(_cursorPositionX, _cursorPositionY); basicInstruction(); execute(0xC); //display normal mode initializeForSendingData(); int i = 0; while(text[i]){ byte fontByte[5]; unsigned short int byteArrayLength; findCorespondingByte(text[i], fontByte, byteArrayLength); for(short int i = 0; i < byteArrayLength ;i++){ transmitInformation(fontByte[i]); } transmitInformation(0x0); // add an empty line after each chars moveCursorInXAxis(byteArrayLength + 1); i++; } } void Nokia_5110::println(char text[]){ print(text); moveCursorInYAxis(1); } /** * Moves cursor in x axis by a number sepcified in method's parameter */ void Nokia_5110::moveCursorInXAxis(unsigned int by){ if(by == 0) return; _cursorPositionX++; if(_cursorPositionX > 83){ moveCursorInYAxis(1); _cursorPositionX = 0; } moveCursorInXAxis(--by); } /** * Moves cursor in y axis by a number sepcified in method's parameter */ void Nokia_5110::moveCursorInYAxis(unsigned int by){ if(by == 0) return; _cursorPositionY++; _cursorPositionX = 0; // for each y incrementation, reset the x axis :D if(_cursorPositionY > 5){ _cursorPositionY = 0; } moveCursorInYAxis(--by); } void Nokia_5110::setCursor(unsigned int xPosition, unsigned int yPosition){ _cursorPositionX = xPosition; _cursorPositionY = yPosition; basicInstruction(); //set x position unsigned short int leastXPositionValue = 128; execute(byte(leastXPositionValue + xPosition)); //set y position unsigned short int leastYPositionValue = 64; execute(byte(leastYPositionValue + yPosition)); } void Nokia_5110::clear(){ initializeForSendingData(); int i = 504; while(i >= 0){ transmitInformation(0x0); i--; } setCursor(0, 0); } void Nokia_5110::clear(unsigned int inRow, unsigned int fromColumn, unsigned int toColumn){ // toColumn has to be more than from Column, otherwise flip the values :D unsigned int temp; if(fromColumn > toColumn){ temp = fromColumn; fromColumn = toColumn; toColumn = temp; } unsigned int counter = fromColumn; while(counter <= toColumn){ setCursor(counter, inRow); initializeForSendingData(); transmitInformation(0x0); counter++; } setCursor(fromColumn, inRow); } <|endoftext|>
<commit_before>#ifndef VERTEX_FORMAT_HPP #define VERTEX_FORMAT_HPP #include <glm/glm.hpp> namespace plush { /// A vertex structure that has only two elements: a position in 3d, /// and a color. struct Vertex_pos_color { glm::vec3 pos; glm::vec3 color; }; } #endif<commit_msg>Added TexturedVertex, removed the testing struct.<commit_after>#ifndef VERTEX_FORMAT_HPP #define VERTEX_FORMAT_HPP #include <glm/glm.hpp> namespace plush { /** * A vertex description to be used with simple texturing. * It contains a coordinate, a normal, and a texture coordinate. */ struct TexturedVertex { glm::vec3 coord; glm::vec3 normal; glm::vec2 texCoord; }; } #endif<|endoftext|>
<commit_before>//===- RustWrapper.cpp - Rust wrapper for core functions --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines alternate interfaces to core functions that are more // readily callable by Rust's FFI. // //===----------------------------------------------------------------------===// #include "llvm/Linker.h" #include "llvm/PassManager.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/Host.h" #include "llvm-c/Core.h" #include "llvm-c/BitReader.h" #include "llvm-c/Object.h" #include <cstdlib> using namespace llvm; static const char *LLVMRustError; extern "C" LLVMMemoryBufferRef LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) { LLVMMemoryBufferRef MemBuf = NULL; LLVMCreateMemoryBufferWithContentsOfFile(Path, &MemBuf, const_cast<char **>(&LLVMRustError)); return MemBuf; } extern "C" const char *LLVMRustGetLastError(void) { return LLVMRustError; } extern "C" void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef PM); extern "C" bool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src) { static std::string err; // For some strange reason, unwrap() doesn't work here. "No matching // function" error. Module *DM = reinterpret_cast<Module *>(Dest); Module *SM = reinterpret_cast<Module *>(Src); if (Linker::LinkModules(DM, SM, &err)) { LLVMRustError = err.c_str(); return false; } return true; } extern "C" void LLVMRustWriteOutputFile(LLVMPassManagerRef PMR, LLVMModuleRef M, const char *triple, const char *path, TargetMachine::CodeGenFileType FileType, CodeGenOpt::Level OptLevel) { // Set compilation options. llvm::NoFramePointerElim = true; InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); std::string Err; const Target *TheTarget = TargetRegistry::lookupTarget(triple, Err); std::string FeaturesStr; std::string Trip(triple); std::string CPUStr = llvm::sys::getHostCPUName(); TargetMachine *Target = TheTarget->createTargetMachine(Trip, CPUStr, FeaturesStr, Reloc::PIC_); bool NoVerify = false; PassManager *PM = unwrap<PassManager>(PMR); std::string ErrorInfo; raw_fd_ostream OS(path, ErrorInfo, raw_fd_ostream::F_Binary); formatted_raw_ostream FOS(OS); bool foo = Target->addPassesToEmitFile(*PM, FOS, FileType, OptLevel, NoVerify); assert(!foo); (void)foo; PM->run(*unwrap(M)); delete Target; } extern "C" LLVMModuleRef LLVMRustParseBitcode(LLVMMemoryBufferRef MemBuf) { LLVMModuleRef M; return LLVMParseBitcode(MemBuf, &M, const_cast<char **>(&LLVMRustError)) ? NULL : M; } extern "C" const char *LLVMRustGetHostTriple(void) { static std::string str = llvm::sys::getHostTriple(); return str.c_str(); } extern "C" LLVMValueRef LLVMRustConstSmallInt(LLVMTypeRef IntTy, unsigned N, LLVMBool SignExtend) { return LLVMConstInt(IntTy, (unsigned long long)N, SignExtend); } extern bool llvm::TimePassesIsEnabled; extern "C" void LLVMRustEnableTimePasses() { TimePassesIsEnabled = true; } extern "C" void LLVMRustPrintPassTimings() { raw_fd_ostream OS (2, false); // stderr. TimerGroup::printAll(OS); } <commit_msg>Update LinkModules invocation to use new prototype<commit_after>//===- RustWrapper.cpp - Rust wrapper for core functions --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines alternate interfaces to core functions that are more // readily callable by Rust's FFI. // //===----------------------------------------------------------------------===// #include "llvm/Linker.h" #include "llvm/PassManager.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/Host.h" #include "llvm-c/Core.h" #include "llvm-c/BitReader.h" #include "llvm-c/Object.h" #include <cstdlib> using namespace llvm; static const char *LLVMRustError; extern "C" LLVMMemoryBufferRef LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) { LLVMMemoryBufferRef MemBuf = NULL; LLVMCreateMemoryBufferWithContentsOfFile(Path, &MemBuf, const_cast<char **>(&LLVMRustError)); return MemBuf; } extern "C" const char *LLVMRustGetLastError(void) { return LLVMRustError; } extern "C" void LLVMAddBasicAliasAnalysisPass(LLVMPassManagerRef PM); extern "C" bool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src) { static std::string err; // For some strange reason, unwrap() doesn't work here. "No matching // function" error. Module *DM = reinterpret_cast<Module *>(Dest); Module *SM = reinterpret_cast<Module *>(Src); if (Linker::LinkModules(DM, SM, Linker::DestroySource, &err)) { LLVMRustError = err.c_str(); return false; } return true; } extern "C" void LLVMRustWriteOutputFile(LLVMPassManagerRef PMR, LLVMModuleRef M, const char *triple, const char *path, TargetMachine::CodeGenFileType FileType, CodeGenOpt::Level OptLevel) { // Set compilation options. llvm::NoFramePointerElim = true; InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmPrinters(); InitializeAllAsmParsers(); std::string Err; const Target *TheTarget = TargetRegistry::lookupTarget(triple, Err); std::string FeaturesStr; std::string Trip(triple); std::string CPUStr = llvm::sys::getHostCPUName(); TargetMachine *Target = TheTarget->createTargetMachine(Trip, CPUStr, FeaturesStr, Reloc::PIC_); bool NoVerify = false; PassManager *PM = unwrap<PassManager>(PMR); std::string ErrorInfo; raw_fd_ostream OS(path, ErrorInfo, raw_fd_ostream::F_Binary); formatted_raw_ostream FOS(OS); bool foo = Target->addPassesToEmitFile(*PM, FOS, FileType, OptLevel, NoVerify); assert(!foo); (void)foo; PM->run(*unwrap(M)); delete Target; } extern "C" LLVMModuleRef LLVMRustParseBitcode(LLVMMemoryBufferRef MemBuf) { LLVMModuleRef M; return LLVMParseBitcode(MemBuf, &M, const_cast<char **>(&LLVMRustError)) ? NULL : M; } extern "C" const char *LLVMRustGetHostTriple(void) { static std::string str = llvm::sys::getHostTriple(); return str.c_str(); } extern "C" LLVMValueRef LLVMRustConstSmallInt(LLVMTypeRef IntTy, unsigned N, LLVMBool SignExtend) { return LLVMConstInt(IntTy, (unsigned long long)N, SignExtend); } extern bool llvm::TimePassesIsEnabled; extern "C" void LLVMRustEnableTimePasses() { TimePassesIsEnabled = true; } extern "C" void LLVMRustPrintPassTimings() { raw_fd_ostream OS (2, false); // stderr. TimerGroup::printAll(OS); } <|endoftext|>
<commit_before>#include "TemplateMatch.h" #include "PI3OpencvCompat.h" int lowThreshold; void CannyThreshold(int, void*) { } TemplateMatch::TemplateMatch() { initialize(); } TemplateMatch::~TemplateMatch() { } void TemplateMatch::sortCorners(std::vector<cv::Point2f>& corners, cv::Point2f center) { std::vector<cv::Point2f> top, bot; for (unsigned int i = 0; i < corners.size(); i++) { if (corners[i].y < center.y) top.push_back(corners[i]); else bot.push_back(corners[i]); } cv::Point2f tl = top[0].x > top[1].x ? top[1] : top[0]; cv::Point2f tr = top[0].x > top[1].x ? top[0] : top[1]; cv::Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0]; cv::Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1]; corners.clear(); corners.push_back(tl); corners.push_back(tr); corners.push_back(br); corners.push_back(bl); } int TemplateMatch::Recognize(Mat& camera) { if (!IsPi3 && m_bDebug) { namedWindow("A", CV_WINDOW_AUTOSIZE); namedWindow("B", CV_WINDOW_AUTOSIZE); namedWindow("C", CV_WINDOW_AUTOSIZE); createTrackbar("Min Threshold:", "A", &lowThreshold, 100, CannyThreshold); } int match=-1; Mat new_image,greyImg; cvtColor(camera, greyImg, CV_RGB2GRAY); //threshold(greyImg, greyImg, 100, 255, 0); Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; GaussianBlur(greyImg, greyImg, Size(9, 9), 2, 2); /// Detect edges using canny Canny(greyImg, canny_output, lowThreshold, lowThreshold * 3, 3); // imshow("B",canny_output); /// Find contours findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); vector<Point> approxRect; for (size_t i = 0; i < contours.size(); i++) { approxPolyDP(contours[i], approxRect, arcLength(Mat(contours[i]), true) * 0.01, true); if (approxRect.size() == 4) { float area = contourArea(contours[i]); if (area > 10000) { std::vector<cv::Point2f> corners; vector<Point>::iterator vertex; vertex = approxRect.begin(); //vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); Moments mu; mu = moments(contours[i], false); Point2f center(mu.m10 / mu.m00, mu.m01 / mu.m00); sortCorners(corners, center); // Define the destination image Mat correctedImg = ::Mat::zeros(195, 271, CV_8UC3); // Corners of the destination image std::vector<cv::Point2f> quad_pts; quad_pts.push_back(Point2f(0, 0)); quad_pts.push_back(Point2f(correctedImg.cols, 0)); quad_pts.push_back( Point2f(correctedImg.cols, correctedImg.rows)); quad_pts.push_back(Point2f(0, correctedImg.rows)); // Get transformation matrix Mat transmtx = getPerspectiveTransform(corners, quad_pts); // Apply perspective transformation warpPerspective(camera, correctedImg, transmtx, correctedImg.size()); Mat correctedImgBin; cvtColor(correctedImg, correctedImgBin, CV_RGB2GRAY); //equalizeHist(correctedImgBin, correctedImgBin); correctedImgBin.copyTo(new_image); threshold(correctedImgBin, correctedImgBin, 140, 255, 0); if (!IsPi3 && m_bDebug) imshow("B", correctedImgBin); double minVal, maxVal, medVal; minMaxLoc(new_image, &minVal, &maxVal); medVal = (maxVal - minVal) / 2; threshold(new_image, new_image, medVal, 255, 0); if (!IsPi3 && m_bDebug) imshow("C", new_image); Mat diffImg; int minDiff, diff; minDiff = 12000; match = -1; for (int i = 0; i < NumOfSigns; i++) { //diffImg = symbols[i].img-correctedImgBin; bitwise_xor(new_image, symbols[i].img, diffImg, noArray()); diff = countNonZero(diffImg); if (diff < minDiff) { minDiff = diff; match = i; } if (i == 0) { // imshow("B",diffImg); } } //imshow("B", correctedImg); if (match != -1) { putText(camera, symbols[match].name, Point(320, 30), 1, 2, Scalar(0, 255, 0), 2); printf("Match %s\n", symbols[match].name.c_str()); } else printf("No Match\n"); //break; } } } if (!IsPi3 && m_bDebug) imshow("A", camera); m_mRecogResult[match]++; return match; } int TemplateMatch::initialize() { m_mRecogResult[-1] = 0; // no match for (int i = 0; i < NumOfSigns; i++) { m_mRecogResult[i] = 0; } return 0; } int TemplateMatch::getRecognitionResult() { auto max = std::max_element(m_mRecogResult.begin(), m_mRecogResult.end(), LessBySecond()); cout << "!!!!!!!!!!!!!!!!!!" << endl; //map<int,int >::iterator max = std::max_element(m_mRecogResult.begin(), m_mRecogResult.end(), m_mRecogResult.value_comp()); for (int i = 0; i < m_mRecogResult.size()-1; i++) { cout << m_mRecogResult[i] << " "; } cout << m_mRecogResult[-1] << endl; initialize(); return max->first; } <commit_msg>template match 테스트 코드 삭제<commit_after>#include "TemplateMatch.h" #include "PI3OpencvCompat.h" int lowThreshold; void CannyThreshold(int, void*) { } TemplateMatch::TemplateMatch() { initialize(); } TemplateMatch::~TemplateMatch() { } void TemplateMatch::sortCorners(std::vector<cv::Point2f>& corners, cv::Point2f center) { std::vector<cv::Point2f> top, bot; for (unsigned int i = 0; i < corners.size(); i++) { if (corners[i].y < center.y) top.push_back(corners[i]); else bot.push_back(corners[i]); } cv::Point2f tl = top[0].x > top[1].x ? top[1] : top[0]; cv::Point2f tr = top[0].x > top[1].x ? top[0] : top[1]; cv::Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0]; cv::Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1]; corners.clear(); corners.push_back(tl); corners.push_back(tr); corners.push_back(br); corners.push_back(bl); } int TemplateMatch::Recognize(Mat& camera) { if (!IsPi3 && m_bDebug) { namedWindow("A", CV_WINDOW_AUTOSIZE); namedWindow("B", CV_WINDOW_AUTOSIZE); namedWindow("C", CV_WINDOW_AUTOSIZE); createTrackbar("Min Threshold:", "A", &lowThreshold, 100, CannyThreshold); } int match=-1; Mat new_image,greyImg; cvtColor(camera, greyImg, CV_RGB2GRAY); //threshold(greyImg, greyImg, 100, 255, 0); Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; GaussianBlur(greyImg, greyImg, Size(9, 9), 2, 2); /// Detect edges using canny Canny(greyImg, canny_output, lowThreshold, lowThreshold * 3, 3); // imshow("B",canny_output); /// Find contours findContours(canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); vector<Point> approxRect; for (size_t i = 0; i < contours.size(); i++) { approxPolyDP(contours[i], approxRect, arcLength(Mat(contours[i]), true) * 0.01, true); if (approxRect.size() == 4) { float area = contourArea(contours[i]); if (area > 10000) { std::vector<cv::Point2f> corners; vector<Point>::iterator vertex; vertex = approxRect.begin(); //vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); vertex++; if (m_bDebug) circle(camera, *vertex, 2, Scalar(0, 0, 255), -1, 8, 0); corners.push_back(*vertex); Moments mu; mu = moments(contours[i], false); Point2f center(mu.m10 / mu.m00, mu.m01 / mu.m00); sortCorners(corners, center); // Define the destination image Mat correctedImg = ::Mat::zeros(195, 271, CV_8UC3); // Corners of the destination image std::vector<cv::Point2f> quad_pts; quad_pts.push_back(Point2f(0, 0)); quad_pts.push_back(Point2f(correctedImg.cols, 0)); quad_pts.push_back( Point2f(correctedImg.cols, correctedImg.rows)); quad_pts.push_back(Point2f(0, correctedImg.rows)); // Get transformation matrix Mat transmtx = getPerspectiveTransform(corners, quad_pts); // Apply perspective transformation warpPerspective(camera, correctedImg, transmtx, correctedImg.size()); Mat correctedImgBin; cvtColor(correctedImg, correctedImgBin, CV_RGB2GRAY); //equalizeHist(correctedImgBin, correctedImgBin); correctedImgBin.copyTo(new_image); threshold(correctedImgBin, correctedImgBin, 140, 255, 0); if (!IsPi3 && m_bDebug) imshow("B", correctedImgBin); double minVal, maxVal, medVal; minMaxLoc(new_image, &minVal, &maxVal); medVal = (maxVal - minVal) / 2; threshold(new_image, new_image, medVal, 255, 0); if (!IsPi3 && m_bDebug) imshow("C", new_image); Mat diffImg; int minDiff, diff; minDiff = 12000; match = -1; for (int i = 0; i < NumOfSigns; i++) { //diffImg = symbols[i].img-correctedImgBin; bitwise_xor(new_image, symbols[i].img, diffImg, noArray()); diff = countNonZero(diffImg); if (diff < minDiff) { minDiff = diff; match = i; } if (i == 0) { // imshow("B",diffImg); } } //imshow("B", correctedImg); if (match != -1) { putText(camera, symbols[match].name, Point(320, 30), 1, 2, Scalar(0, 255, 0), 2); printf("Match %s\n", symbols[match].name.c_str()); } else printf("No Match\n"); //break; } } } if (!IsPi3 && m_bDebug) imshow("A", camera); m_mRecogResult[match]++; return match; } int TemplateMatch::initialize() { m_mRecogResult[-1] = 0; // no match for (int i = 0; i < NumOfSigns; i++) { m_mRecogResult[i] = 0; } return 0; } int TemplateMatch::getRecognitionResult() { auto max = std::max_element(m_mRecogResult.begin(), m_mRecogResult.end(), LessBySecond()); initialize(); return max->first; } <|endoftext|>
<commit_before>// Copyright 2013 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/sync_file_system/drive_backend/local_to_remote_syncer.h" #include "base/bind.h" #include "base/callback.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/run_loop.h" #include "chrome/browser/drive/drive_uploader.h" #include "chrome/browser/drive/fake_drive_service.h" #include "chrome/browser/google_apis/gdata_errorcode.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_test_util.h" #include "chrome/browser/sync_file_system/drive_backend/list_changes_task.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_context.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_initializer.h" #include "chrome/browser/sync_file_system/drive_backend_v1/fake_drive_service_helper.h" #include "chrome/browser/sync_file_system/drive_backend_v1/fake_drive_uploader.h" #include "chrome/browser/sync_file_system/fake_remote_change_processor.h" #include "chrome/browser/sync_file_system/sync_file_system_test_util.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace sync_file_system { namespace drive_backend { namespace { fileapi::FileSystemURL URL(const GURL& origin, const std::string& path) { return CreateSyncableFileSystemURL( origin, base::FilePath::FromUTF8Unsafe(path)); } } // namespace class LocalToRemoteSyncerTest : public testing::Test, public SyncEngineContext { public: LocalToRemoteSyncerTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {} virtual ~LocalToRemoteSyncerTest() {} virtual void SetUp() OVERRIDE { ASSERT_TRUE(database_dir_.CreateUniqueTempDir()); fake_drive_service_.reset(new FakeDriveServiceWrapper); ASSERT_TRUE(fake_drive_service_->LoadAccountMetadataForWapi( "sync_file_system/account_metadata.json")); ASSERT_TRUE(fake_drive_service_->LoadResourceListForWapi( "gdata/empty_feed.json")); drive_uploader_.reset(new FakeDriveUploader(fake_drive_service_.get())); fake_drive_helper_.reset(new FakeDriveServiceHelper( fake_drive_service_.get(), drive_uploader_.get())); fake_remote_change_processor_.reset(new FakeRemoteChangeProcessor); RegisterSyncableFileSystem(); } virtual void TearDown() OVERRIDE { RevokeSyncableFileSystem(); fake_remote_change_processor_.reset(); metadata_database_.reset(); fake_drive_helper_.reset(); drive_uploader_.reset(); fake_drive_service_.reset(); base::RunLoop().RunUntilIdle(); } void InitializeMetadataDatabase() { SyncEngineInitializer initializer(base::MessageLoopProxy::current(), fake_drive_service_.get(), database_dir_.path()); SyncStatusCode status = SYNC_STATUS_UNKNOWN; initializer.Run(CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SYNC_STATUS_OK, status); metadata_database_ = initializer.PassMetadataDatabase(); } void RegisterApp(const std::string& app_id, const std::string& app_root_folder_id) { SyncStatusCode status = SYNC_STATUS_FAILED; metadata_database_->RegisterApp(app_id, app_root_folder_id, CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SYNC_STATUS_OK, status); } virtual drive::DriveServiceInterface* GetDriveService() OVERRIDE { return fake_drive_service_.get(); } virtual drive::DriveUploaderInterface* GetDriveUploader() OVERRIDE { return drive_uploader_.get(); } virtual MetadataDatabase* GetMetadataDatabase() OVERRIDE { return metadata_database_.get(); } virtual RemoteChangeProcessor* GetRemoteChangeProcessor() OVERRIDE { return fake_remote_change_processor_.get(); } virtual base::SequencedTaskRunner* GetBlockingTaskRunner() OVERRIDE { return base::MessageLoopProxy::current().get(); } protected: std::string CreateSyncRoot() { std::string sync_root_folder_id; EXPECT_EQ(google_apis::HTTP_CREATED, fake_drive_helper_->AddOrphanedFolder( kSyncRootFolderTitle, &sync_root_folder_id)); return sync_root_folder_id; } std::string CreateRemoteFolder(const std::string& parent_folder_id, const std::string& title) { std::string folder_id; EXPECT_EQ(google_apis::HTTP_CREATED, fake_drive_helper_->AddFolder( parent_folder_id, title, &folder_id)); return folder_id; } std::string CreateRemoteFile(const std::string& parent_folder_id, const std::string& title, const std::string& content) { std::string file_id; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->AddFile( parent_folder_id, title, content, &file_id)); return file_id; } SyncStatusCode RunSyncer(FileChange file_change, const fileapi::FileSystemURL& url) { SyncStatusCode status = SYNC_STATUS_UNKNOWN; base::FilePath local_path = base::FilePath::FromUTF8Unsafe("dummy"); scoped_ptr<LocalToRemoteSyncer> syncer(new LocalToRemoteSyncer( this, file_change, local_path, url)); syncer->Run(CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); return status; } SyncStatusCode ListChanges() { ListChangesTask list_changes(this); SyncStatusCode status = SYNC_STATUS_UNKNOWN; list_changes.Run(CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); return status; } ScopedVector<google_apis::ResourceEntry> GetResourceEntriesForParentAndTitle(const std::string& parent_folder_id, const std::string& title) { ScopedVector<google_apis::ResourceEntry> entries; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->SearchByTitle( parent_folder_id, title, &entries)); return entries.Pass(); } void VerifyTitleUniqueness(const std::string& parent_folder_id, const std::string& title, google_apis::DriveEntryKind kind) { ScopedVector<google_apis::ResourceEntry> entries; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->SearchByTitle( parent_folder_id, title, &entries)); ASSERT_EQ(1u, entries.size()); EXPECT_EQ(kind, entries[0]->kind()); } void VerifyFileDeletion(const std::string& parent_folder_id, const std::string& title) { ScopedVector<google_apis::ResourceEntry> entries; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->SearchByTitle( parent_folder_id, title, &entries)); EXPECT_TRUE(entries.empty()); } private: content::TestBrowserThreadBundle thread_bundle_; base::ScopedTempDir database_dir_; scoped_ptr<FakeDriveServiceWrapper> fake_drive_service_; scoped_ptr<FakeDriveUploader> drive_uploader_; scoped_ptr<FakeDriveServiceHelper> fake_drive_helper_; scoped_ptr<MetadataDatabase> metadata_database_; scoped_ptr<FakeRemoteChangeProcessor> fake_remote_change_processor_; DISALLOW_COPY_AND_ASSIGN(LocalToRemoteSyncerTest); }; TEST_F(LocalToRemoteSyncerTest, CreateLocalFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "file"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "folder"))); VerifyTitleUniqueness(app_root, "file", google_apis::ENTRY_KIND_FILE); VerifyTitleUniqueness(app_root, "folder", google_apis::ENTRY_KIND_FOLDER); // TODO(nhiroki): Test nested files case. } TEST_F(LocalToRemoteSyncerTest, DeleteLocalFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "file"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "folder"))); VerifyTitleUniqueness(app_root, "file", google_apis::ENTRY_KIND_FILE); VerifyTitleUniqueness(app_root, "folder", google_apis::ENTRY_KIND_FOLDER); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "file"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "folder"))); VerifyFileDeletion(app_root, "file"); VerifyFileDeletion(app_root, "folder"); } TEST_F(LocalToRemoteSyncerTest, Conflict_CreateFileOnFolder) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateRemoteFolder(app_root, "foo"); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "foo"))); // There should exist both file and folder on remote. ScopedVector<google_apis::ResourceEntry> entries = GetResourceEntriesForParentAndTitle(app_root, "foo"); ASSERT_EQ(2u, entries.size()); EXPECT_EQ(google_apis::ENTRY_KIND_FOLDER, entries[0]->kind()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[1]->kind()); } TEST_F(LocalToRemoteSyncerTest, Conflict_FolderOnFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateRemoteFile(app_root, "foo", "data"); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "foo"))); // There should exist both file and folder on remote. ScopedVector<google_apis::ResourceEntry> entries = GetResourceEntriesForParentAndTitle(app_root, "foo"); ASSERT_EQ(2u, entries.size()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[0]->kind()); EXPECT_EQ(google_apis::ENTRY_KIND_FOLDER, entries[1]->kind()); } TEST_F(LocalToRemoteSyncerTest, Conflict_CreateFileOnFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateRemoteFile(app_root, "foo", "data"); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "foo"))); // There should exist both files on remote. ScopedVector<google_apis::ResourceEntry> entries = GetResourceEntriesForParentAndTitle(app_root, "foo"); ASSERT_EQ(2u, entries.size()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[0]->kind()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[1]->kind()); } // TODO(nhiroki): Add folder-folder conflict (reusing remote folder) case. } // namespace drive_backend } // namespace sync_file_system <commit_msg>SyncFS: Add nested cases to LocalToRemoteSyncerTest<commit_after>// Copyright 2013 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/sync_file_system/drive_backend/local_to_remote_syncer.h" #include "base/bind.h" #include "base/callback.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" #include "base/run_loop.h" #include "chrome/browser/drive/drive_uploader.h" #include "chrome/browser/drive/fake_drive_service.h" #include "chrome/browser/google_apis/gdata_errorcode.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_constants.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_test_util.h" #include "chrome/browser/sync_file_system/drive_backend/list_changes_task.h" #include "chrome/browser/sync_file_system/drive_backend/metadata_database.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_context.h" #include "chrome/browser/sync_file_system/drive_backend/sync_engine_initializer.h" #include "chrome/browser/sync_file_system/drive_backend_v1/fake_drive_service_helper.h" #include "chrome/browser/sync_file_system/drive_backend_v1/fake_drive_uploader.h" #include "chrome/browser/sync_file_system/fake_remote_change_processor.h" #include "chrome/browser/sync_file_system/sync_file_system_test_util.h" #include "chrome/browser/sync_file_system/syncable_file_system_util.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace sync_file_system { namespace drive_backend { namespace { fileapi::FileSystemURL URL(const GURL& origin, const std::string& path) { return CreateSyncableFileSystemURL( origin, base::FilePath::FromUTF8Unsafe(path)); } } // namespace class LocalToRemoteSyncerTest : public testing::Test, public SyncEngineContext { public: LocalToRemoteSyncerTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {} virtual ~LocalToRemoteSyncerTest() {} virtual void SetUp() OVERRIDE { ASSERT_TRUE(database_dir_.CreateUniqueTempDir()); fake_drive_service_.reset(new FakeDriveServiceWrapper); ASSERT_TRUE(fake_drive_service_->LoadAccountMetadataForWapi( "sync_file_system/account_metadata.json")); ASSERT_TRUE(fake_drive_service_->LoadResourceListForWapi( "gdata/empty_feed.json")); drive_uploader_.reset(new FakeDriveUploader(fake_drive_service_.get())); fake_drive_helper_.reset(new FakeDriveServiceHelper( fake_drive_service_.get(), drive_uploader_.get())); fake_remote_change_processor_.reset(new FakeRemoteChangeProcessor); RegisterSyncableFileSystem(); } virtual void TearDown() OVERRIDE { RevokeSyncableFileSystem(); fake_remote_change_processor_.reset(); metadata_database_.reset(); fake_drive_helper_.reset(); drive_uploader_.reset(); fake_drive_service_.reset(); base::RunLoop().RunUntilIdle(); } void InitializeMetadataDatabase() { SyncEngineInitializer initializer(base::MessageLoopProxy::current(), fake_drive_service_.get(), database_dir_.path()); SyncStatusCode status = SYNC_STATUS_UNKNOWN; initializer.Run(CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SYNC_STATUS_OK, status); metadata_database_ = initializer.PassMetadataDatabase(); } void RegisterApp(const std::string& app_id, const std::string& app_root_folder_id) { SyncStatusCode status = SYNC_STATUS_FAILED; metadata_database_->RegisterApp(app_id, app_root_folder_id, CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(SYNC_STATUS_OK, status); } virtual drive::DriveServiceInterface* GetDriveService() OVERRIDE { return fake_drive_service_.get(); } virtual drive::DriveUploaderInterface* GetDriveUploader() OVERRIDE { return drive_uploader_.get(); } virtual MetadataDatabase* GetMetadataDatabase() OVERRIDE { return metadata_database_.get(); } virtual RemoteChangeProcessor* GetRemoteChangeProcessor() OVERRIDE { return fake_remote_change_processor_.get(); } virtual base::SequencedTaskRunner* GetBlockingTaskRunner() OVERRIDE { return base::MessageLoopProxy::current().get(); } protected: std::string CreateSyncRoot() { std::string sync_root_folder_id; EXPECT_EQ(google_apis::HTTP_CREATED, fake_drive_helper_->AddOrphanedFolder( kSyncRootFolderTitle, &sync_root_folder_id)); return sync_root_folder_id; } std::string CreateRemoteFolder(const std::string& parent_folder_id, const std::string& title) { std::string folder_id; EXPECT_EQ(google_apis::HTTP_CREATED, fake_drive_helper_->AddFolder( parent_folder_id, title, &folder_id)); return folder_id; } std::string CreateRemoteFile(const std::string& parent_folder_id, const std::string& title, const std::string& content) { std::string file_id; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->AddFile( parent_folder_id, title, content, &file_id)); return file_id; } SyncStatusCode RunSyncer(FileChange file_change, const fileapi::FileSystemURL& url) { SyncStatusCode status = SYNC_STATUS_UNKNOWN; base::FilePath local_path = base::FilePath::FromUTF8Unsafe("dummy"); scoped_ptr<LocalToRemoteSyncer> syncer(new LocalToRemoteSyncer( this, file_change, local_path, url)); syncer->Run(CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); return status; } SyncStatusCode ListChanges() { ListChangesTask list_changes(this); SyncStatusCode status = SYNC_STATUS_UNKNOWN; list_changes.Run(CreateResultReceiver(&status)); base::RunLoop().RunUntilIdle(); return status; } ScopedVector<google_apis::ResourceEntry> GetResourceEntriesForParentAndTitle(const std::string& parent_folder_id, const std::string& title) { ScopedVector<google_apis::ResourceEntry> entries; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->SearchByTitle( parent_folder_id, title, &entries)); return entries.Pass(); } std::string GetFileIDForParentAndTitle(const std::string& parent_folder_id, const std::string& title) { ScopedVector<google_apis::ResourceEntry> entries = GetResourceEntriesForParentAndTitle(parent_folder_id, title); if (entries.size() != 1) return std::string(); return entries[0]->resource_id(); } void VerifyTitleUniqueness(const std::string& parent_folder_id, const std::string& title, google_apis::DriveEntryKind kind) { ScopedVector<google_apis::ResourceEntry> entries; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->SearchByTitle( parent_folder_id, title, &entries)); ASSERT_EQ(1u, entries.size()); EXPECT_EQ(kind, entries[0]->kind()); } void VerifyFileDeletion(const std::string& parent_folder_id, const std::string& title) { ScopedVector<google_apis::ResourceEntry> entries; EXPECT_EQ(google_apis::HTTP_SUCCESS, fake_drive_helper_->SearchByTitle( parent_folder_id, title, &entries)); EXPECT_TRUE(entries.empty()); } private: content::TestBrowserThreadBundle thread_bundle_; base::ScopedTempDir database_dir_; scoped_ptr<FakeDriveServiceWrapper> fake_drive_service_; scoped_ptr<FakeDriveUploader> drive_uploader_; scoped_ptr<FakeDriveServiceHelper> fake_drive_helper_; scoped_ptr<MetadataDatabase> metadata_database_; scoped_ptr<FakeRemoteChangeProcessor> fake_remote_change_processor_; DISALLOW_COPY_AND_ASSIGN(LocalToRemoteSyncerTest); }; TEST_F(LocalToRemoteSyncerTest, CreateFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "file1"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "folder"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "folder/file2"))); std::string folder_id = GetFileIDForParentAndTitle(app_root, "folder"); ASSERT_FALSE(folder_id.empty()); VerifyTitleUniqueness(app_root, "file1", google_apis::ENTRY_KIND_FILE); VerifyTitleUniqueness(app_root, "folder", google_apis::ENTRY_KIND_FOLDER); VerifyTitleUniqueness(folder_id, "file2", google_apis::ENTRY_KIND_FILE); } TEST_F(LocalToRemoteSyncerTest, CreateFileOnMissingPath) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); // Run the syncer 3 times to create missing folder1 and folder2. EXPECT_EQ(SYNC_STATUS_RETRY, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "folder1/folder2/file"))); EXPECT_EQ(SYNC_STATUS_RETRY, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "folder1/folder2/file"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "folder1/folder2/file"))); std::string folder_id1 = GetFileIDForParentAndTitle(app_root, "folder1"); ASSERT_FALSE(folder_id1.empty()); std::string folder_id2 = GetFileIDForParentAndTitle(folder_id1, "folder2"); ASSERT_FALSE(folder_id2.empty()); VerifyTitleUniqueness(app_root, "folder1", google_apis::ENTRY_KIND_FOLDER); VerifyTitleUniqueness(folder_id1, "folder2", google_apis::ENTRY_KIND_FOLDER); VerifyTitleUniqueness(folder_id2, "file", google_apis::ENTRY_KIND_FILE); } TEST_F(LocalToRemoteSyncerTest, DeleteFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "file"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "folder"))); VerifyTitleUniqueness(app_root, "file", google_apis::ENTRY_KIND_FILE); VerifyTitleUniqueness(app_root, "folder", google_apis::ENTRY_KIND_FOLDER); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "file"))); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_DELETE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "folder"))); VerifyFileDeletion(app_root, "file"); VerifyFileDeletion(app_root, "folder"); } TEST_F(LocalToRemoteSyncerTest, Conflict_CreateFileOnFolder) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateRemoteFolder(app_root, "foo"); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "foo"))); // There should exist both file and folder on remote. ScopedVector<google_apis::ResourceEntry> entries = GetResourceEntriesForParentAndTitle(app_root, "foo"); ASSERT_EQ(2u, entries.size()); EXPECT_EQ(google_apis::ENTRY_KIND_FOLDER, entries[0]->kind()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[1]->kind()); } TEST_F(LocalToRemoteSyncerTest, Conflict_CreateFolderOnFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateRemoteFile(app_root, "foo", "data"); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_DIRECTORY), URL(kOrigin, "foo"))); // There should exist both file and folder on remote. ScopedVector<google_apis::ResourceEntry> entries = GetResourceEntriesForParentAndTitle(app_root, "foo"); ASSERT_EQ(2u, entries.size()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[0]->kind()); EXPECT_EQ(google_apis::ENTRY_KIND_FOLDER, entries[1]->kind()); } TEST_F(LocalToRemoteSyncerTest, Conflict_CreateFileOnFile) { const GURL kOrigin("chrome-extension://example"); const std::string sync_root = CreateSyncRoot(); const std::string app_root = CreateRemoteFolder(sync_root, kOrigin.host()); InitializeMetadataDatabase(); RegisterApp(kOrigin.host(), app_root); CreateRemoteFile(app_root, "foo", "data"); EXPECT_EQ(SYNC_STATUS_OK, ListChanges()); EXPECT_EQ(SYNC_STATUS_OK, RunSyncer( FileChange(FileChange::FILE_CHANGE_ADD_OR_UPDATE, SYNC_FILE_TYPE_FILE), URL(kOrigin, "foo"))); // There should exist both files on remote. ScopedVector<google_apis::ResourceEntry> entries = GetResourceEntriesForParentAndTitle(app_root, "foo"); ASSERT_EQ(2u, entries.size()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[0]->kind()); EXPECT_EQ(google_apis::ENTRY_KIND_FILE, entries[1]->kind()); } // TODO(nhiroki): Add folder-folder conflict (reusing remote folder) case. } // namespace drive_backend } // namespace sync_file_system <|endoftext|>
<commit_before>//snippet-sourcedescription:[s3-demo.cpp demonstrates how to perform various operations for Amazon Simple Storage Service (Amazon S3).] //snippet-keyword:[AWS SDK for C++] //snippet-keyword:[Code Sample] //snippet-service:[Amazon S3] //snippet-sourcetype:[full-example] //snippet-sourcedate:[12/15/2021] //snippet-sourceauthor:[scmacdon - aws] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ #include <awsdoc/s3/s3-demo.h> #include <iostream> #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/Bucket.h> #include <aws/s3/model/CreateBucketConfiguration.h> #include <aws/s3/model/CreateBucketRequest.h> #include <aws/s3/model/DeleteBucketRequest.h> // Look for a bucket among all currently available Amazon S3 buckets. bool FindTheBucket(const Aws::S3::S3Client& s3Client, const Aws::String& bucketName) { Aws::S3::Model::ListBucketsOutcome outcome = s3Client.ListBuckets(); if (outcome.IsSuccess()) { std::cout << "Looking for a bucket named '" << bucketName << "'..." << std::endl << std::endl; Aws::Vector<Aws::S3::Model::Bucket> bucket_list = outcome.GetResult().GetBuckets(); for (Aws::S3::Model::Bucket const& bucket : bucket_list) { if (bucket.GetName() == bucketName) { std::cout << "Found the bucket." << std::endl << std::endl; return true; } } std::cout << "Could not find the bucket." << std::endl << std::endl; return true; } else { std::cout << "ListBuckets error: " << outcome.GetError().GetMessage() << std::endl; } return false; } // Create an Amazon S3 bucket. bool CreateTheBucket(const Aws::S3::S3Client& s3Client, const Aws::String& bucketName) { std::cout << "Creating a bucket named '" << bucketName << "'..." << std::endl << std::endl; Aws::S3::Model::CreateBucketRequest request; request.SetBucket(bucketName); Aws::S3::Model::CreateBucketOutcome outcome = s3Client.CreateBucket(request); if (outcome.IsSuccess()) { std::cout << "Bucket created." << std::endl << std::endl; return true; } else { std::cout << "CreateBucket error: " << outcome.GetError().GetMessage() << std::endl; return false; } } // Delete an existing Amazon S3 bucket. bool DeleteTheBucket(const Aws::S3::S3Client& s3Client, const Aws::String& bucketName) { std::cout << "Deleting the bucket named '" << bucketName << "'..." << std::endl << std::endl; Aws::S3::Model::DeleteBucketRequest request; request.SetBucket(bucketName); Aws::S3::Model::DeleteBucketOutcome outcome = s3Client.DeleteBucket(request); if (outcome.IsSuccess()) { std::cout << "Bucket deleted." << std::endl << std::endl; return true; } else { std::cout << "DeleteBucket error: " << outcome.GetError().GetMessage() << std::endl; return false; } } // Create an Amazon S3 bucket and then delete it. // Before and after creating the bucket, and then after deleting the bucket, // try to determine whether that bucket still exists. int main(int argc, char* argv[]) { Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String bucket_name = "scottaug1011"; Aws::String region = "us-east-1"; Aws::Client::ClientConfiguration config; config.region = region; Aws::S3::S3Client s3_client(config); if (!FindTheBucket(s3_client, bucket_name)) { return 1; } if (!CreateTheBucket(s3_client, bucket_name)) { return 1; } if (!FindTheBucket(s3_client, bucket_name)) { return 1; } if (!DeleteTheBucket(s3_client, bucket_name)) { return 1; } if (!FindTheBucket(s3_client, bucket_name)) { return 1; } } Aws::ShutdownAPI(options); return 0; } // snippet-end:[s3.cpp.bucket_operations.list_create_delete] <commit_msg>Update s3-demo.cpp<commit_after>//snippet-sourcedescription:[s3-demo.cpp demonstrates how to perform various operations for Amazon Simple Storage Service (Amazon S3).] //snippet-keyword:[AWS SDK for C++] //snippet-keyword:[Code Sample] //snippet-service:[Amazon S3] //snippet-sourcetype:[full-example] //snippet-sourcedate:[12/15/2021] //snippet-sourceauthor:[scmacdon - aws] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ #include <awsdoc/s3/s3-demo.h> // snippet-start:[s3.cpp.bucket_operations.list_create_delete] #include <iostream> #include <aws/core/Aws.h> #include <aws/s3/S3Client.h> #include <aws/s3/model/Bucket.h> #include <aws/s3/model/CreateBucketConfiguration.h> #include <aws/s3/model/CreateBucketRequest.h> #include <aws/s3/model/DeleteBucketRequest.h> // Look for a bucket among all currently available Amazon S3 buckets. bool FindTheBucket(const Aws::S3::S3Client& s3Client, const Aws::String& bucketName) { Aws::S3::Model::ListBucketsOutcome outcome = s3Client.ListBuckets(); if (outcome.IsSuccess()) { std::cout << "Looking for a bucket named '" << bucketName << "'..." << std::endl << std::endl; Aws::Vector<Aws::S3::Model::Bucket> bucket_list = outcome.GetResult().GetBuckets(); for (Aws::S3::Model::Bucket const& bucket : bucket_list) { if (bucket.GetName() == bucketName) { std::cout << "Found the bucket." << std::endl << std::endl; return true; } } std::cout << "Could not find the bucket." << std::endl << std::endl; return true; } else { std::cout << "ListBuckets error: " << outcome.GetError().GetMessage() << std::endl; } return false; } // Create an Amazon S3 bucket. bool CreateTheBucket(const Aws::S3::S3Client& s3Client, const Aws::String& bucketName) { std::cout << "Creating a bucket named '" << bucketName << "'..." << std::endl << std::endl; Aws::S3::Model::CreateBucketRequest request; request.SetBucket(bucketName); Aws::S3::Model::CreateBucketOutcome outcome = s3Client.CreateBucket(request); if (outcome.IsSuccess()) { std::cout << "Bucket created." << std::endl << std::endl; return true; } else { std::cout << "CreateBucket error: " << outcome.GetError().GetMessage() << std::endl; return false; } } // Delete an existing Amazon S3 bucket. bool DeleteTheBucket(const Aws::S3::S3Client& s3Client, const Aws::String& bucketName) { std::cout << "Deleting the bucket named '" << bucketName << "'..." << std::endl << std::endl; Aws::S3::Model::DeleteBucketRequest request; request.SetBucket(bucketName); Aws::S3::Model::DeleteBucketOutcome outcome = s3Client.DeleteBucket(request); if (outcome.IsSuccess()) { std::cout << "Bucket deleted." << std::endl << std::endl; return true; } else { std::cout << "DeleteBucket error: " << outcome.GetError().GetMessage() << std::endl; return false; } } // Create an Amazon S3 bucket and then delete it. // Before and after creating the bucket, and then after deleting the bucket, // try to determine whether that bucket still exists. int main(int argc, char* argv[]) { if (argc < 3) { std::cout << "Usage: s3-demo <bucket name> <AWS Region>" << std::endl << "Example: s3-demo my-bucket us-east-1" << std::endl; return false; } Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String bucket_name = argv[1]; Aws::String region = argv[2]; Aws::Client::ClientConfiguration config; config.region = region; Aws::S3::S3Client s3_client(config); if (!FindTheBucket(s3_client, bucket_name)) { return 1; } if (!CreateTheBucket(s3_client, bucket_name)) { return 1; } if (!FindTheBucket(s3_client, bucket_name)) { return 1; } if (!DeleteTheBucket(s3_client, bucket_name)) { return 1; } if (!FindTheBucket(s3_client, bucket_name)) { return 1; } } Aws::ShutdownAPI(options); return 0; } // snippet-end:[s3.cpp.bucket_operations.list_create_delete] <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "tagged_struct.h" int main() { tagged_struct<member<"hello", auto_, [] { return 5; }>, member<"world", std::string,[]{}>, member<"test", auto_, [](auto& t) { return 2 * get<"hello">(t) + get<"world">(t).size(); }>, member<"last", int, [] { return 0; }>> ts{arg<"hello"> = 1, arg<"world"> = "Universe"}; using T = decltype(ts); T t2{arg<"world"> = "JRB"}; std::cout << get<"hello">(ts) << "\n"; std::cout << get<"world">(ts) << "\n"; std::cout << get<"test">(ts) << "\n"; std::cout << get<"hello">(t2) << "\n"; std::cout << get<"world">(t2) << "\n"; std::cout << get<"test">(t2) << "\n"; }<commit_msg>Improve example for tagged_struct<commit_after>#include <iostream> #include <string> #include "tagged_struct.h" int main() { tagged_struct<member<"hello", auto_, [] { return 5; }>, member<"world", std::string, [] {}>, member<"test", auto_, [](auto& t) { return 2 * get<"hello">(t) + get<"world">(t).size(); }>, member<"last", int, [] { return 0; }>> ts{arg<"world"> = "Universe", arg<"hello"> = 1}; using T = decltype(ts); T t2{arg<"world"> = "JRB"}; std::cout << get<"hello">(ts) << "\n"; std::cout << get<"world">(ts) << "\n"; std::cout << get<"test">(ts) << "\n"; std::cout << get<"hello">(t2) << "\n"; std::cout << get<"world">(t2) << "\n"; std::cout << get<"test">(t2) << "\n"; }<|endoftext|>
<commit_before>#include "master.hpp" namespace factor { HMODULE hFactorDll; bool set_memory_locked(cell base, cell size, bool locked) { int prot = locked ? PAGE_NOACCESS : PAGE_READWRITE; DWORD ignore; int status = VirtualProtect((char*)base, size, prot, &ignore); return status != 0; } void factor_vm::init_ffi() { hFactorDll = GetModuleHandle(NULL); if (!hFactorDll) fatal_error("GetModuleHandle() failed", 0); } void factor_vm::ffi_dlopen(dll* dll) { dll->handle = LoadLibraryEx((WCHAR*)alien_offset(dll->path), NULL, 0); } cell factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) { return (cell)GetProcAddress(dll ? (HMODULE) dll->handle : hFactorDll, symbol); } cell factor_vm::ffi_dlsym_raw(dll* dll, symbol_char* symbol) { return ffi_dlsym(dll, symbol); } void factor_vm::ffi_dlclose(dll* dll) { FreeLibrary((HMODULE) dll->handle); dll->handle = NULL; } BOOL factor_vm::windows_stat(vm_char* path) { BY_HANDLE_FILE_INFORMATION bhfi; HANDLE h = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (h == INVALID_HANDLE_VALUE) { // FindFirstFile is the only call that can stat c:\pagefile.sys WIN32_FIND_DATA st; HANDLE h; if (INVALID_HANDLE_VALUE == (h = FindFirstFile(path, &st))) return false; FindClose(h); return true; } BOOL ret = GetFileInformationByHandle(h, &bhfi); CloseHandle(h); return ret; } /* You must free() this yourself. */ const vm_char* factor_vm::default_image_path() { vm_char full_path[MAX_UNICODE_PATH]; vm_char* ptr; vm_char temp_path[MAX_UNICODE_PATH]; if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH)) fatal_error("GetModuleFileName() failed", 0); if ((ptr = wcsrchr(full_path, '.'))) *ptr = 0; wcsncpy(temp_path, full_path, MAX_UNICODE_PATH - 1); size_t full_path_len = wcslen(full_path); if (full_path_len < MAX_UNICODE_PATH - 1) wcsncat(temp_path, L".image", MAX_UNICODE_PATH - full_path_len - 1); temp_path[MAX_UNICODE_PATH - 1] = 0; return safe_strdup(temp_path); } /* You must free() this yourself. */ const vm_char* factor_vm::vm_executable_path() { vm_char full_path[MAX_UNICODE_PATH]; if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH)) fatal_error("GetModuleFileName() failed", 0); return safe_strdup(full_path); } void factor_vm::primitive_existsp() { vm_char* path = untag_check<byte_array>(ctx->pop())->data<vm_char>(); ctx->push(tag_boolean(windows_stat(path))); } segment::segment(cell size_, bool executable_p) { size = size_; char* mem; cell alloc_size = getpagesize() * 2 + size; if ((mem = (char*)VirtualAlloc( NULL, alloc_size, MEM_COMMIT, executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) == 0) { fatal_error("Out of memory in VirtualAlloc", alloc_size); } start = (cell)mem + getpagesize(); end = start + size; set_border_locked(true); } void segment::set_border_locked(bool locked) { int pagesize = getpagesize(); cell lo = start - pagesize; if (!set_memory_locked(lo, pagesize, locked)) { fatal_error("Cannot (un)protect low guard page", lo); } cell hi = end; if (!set_memory_locked(hi, pagesize, locked)) { fatal_error("Cannot (un)protect high guard page", hi); } } segment::~segment() { SYSTEM_INFO si; GetSystemInfo(&si); if (!VirtualFree((void*)(start - si.dwPageSize), 0, MEM_RELEASE)) fatal_error("Segment deallocation failed", 0); } long getpagesize() { static long g_pagesize = 0; if (!g_pagesize) { SYSTEM_INFO system_info; GetSystemInfo(&system_info); g_pagesize = system_info.dwPageSize; } return g_pagesize; } bool move_file(const vm_char* path1, const vm_char* path2) { /* MoveFileEx returns FALSE on fail. */ BOOL val = MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING); if (val == FALSE) { /* MoveFileEx doesn't set errno, which primitive_save_image() reads the error code from. Instead of converting from GetLastError() to errno values, we ust set it to the generic EIO value. */ errno = EIO; } return val == TRUE; } void factor_vm::init_signals() {} THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) { return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine, args, 0, 0); } uint64_t nano_count() { static double scale_factor; static uint32_t hi = 0; static uint32_t lo = 0; LARGE_INTEGER count; BOOL ret = QueryPerformanceCounter(&count); if (ret == 0) fatal_error("QueryPerformanceCounter", 0); if (scale_factor == 0.0) { LARGE_INTEGER frequency; BOOL ret = QueryPerformanceFrequency(&frequency); if (ret == 0) fatal_error("QueryPerformanceFrequency", 0); scale_factor = (1000000000.0 / frequency.QuadPart); } #ifdef FACTOR_64 hi = count.HighPart; #else /* On VirtualBox, QueryPerformanceCounter does not increment the high part every time the low part overflows. Workaround. */ if (lo > count.LowPart) hi++; #endif lo = count.LowPart; return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor); } void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); } typedef enum _EXCEPTION_DISPOSITION { ExceptionContinueExecution = 0, ExceptionContinueSearch = 1, ExceptionNestedException = 2, ExceptionCollidedUnwind = 3 } EXCEPTION_DISPOSITION; LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c, void* dispatch) { switch (e->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: signal_fault_addr = e->ExceptionInformation[1]; signal_fault_pc = c->EIP; verify_memory_protection_error(signal_fault_addr); dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP, (cell)factor::memory_signal_handler_impl); break; case STATUS_FLOAT_DENORMAL_OPERAND: case STATUS_FLOAT_DIVIDE_BY_ZERO: case STATUS_FLOAT_INEXACT_RESULT: case STATUS_FLOAT_INVALID_OPERATION: case STATUS_FLOAT_OVERFLOW: case STATUS_FLOAT_STACK_CHECK: case STATUS_FLOAT_UNDERFLOW: case STATUS_FLOAT_MULTIPLE_FAULTS: case STATUS_FLOAT_MULTIPLE_TRAPS: #ifdef FACTOR_64 signal_fpu_status = fpu_status(MXCSR(c)); #else signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c)); /* This seems to have no effect */ X87SW(c) = 0; #endif MXCSR(c) &= 0xffffffc0; dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP, (cell)factor::fp_signal_handler_impl); break; default: signal_number = e->ExceptionCode; dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP, (cell)factor::synchronous_signal_handler_impl); break; } return ExceptionContinueExecution; } VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c, void* dispatch) { factor_vm* vm = current_vm_p(); if (factor_vm::fatal_erroring_p || !vm) return ExceptionContinueSearch; return vm->exception_handler(e, frame, c, dispatch); } /* On Unix SIGINT (ctrl-c) automatically interrupts blocking io system calls. It doesn't on Windows, so we need to manually send some cancellation requests to unblock the thread. */ VOID CALLBACK dummy_cb (ULONG_PTR dwParam) { } // CancelSynchronousIo is not in Windows XP #if _WIN32_WINNT >= 0x0600 static void wake_up_thread(HANDLE thread) { if (!CancelSynchronousIo(thread)) { DWORD err = GetLastError(); /* CancelSynchronousIo() didn't find anything to cancel, let's try with QueueUserAPC() instead. */ if (err == ERROR_NOT_FOUND) { if (!QueueUserAPC(&dummy_cb, thread, NULL)) { fatal_error("QueueUserAPC() failed", GetLastError()); } } else { fatal_error("CancelSynchronousIo() failed", err); } } } #else static void wake_up_thread(HANDLE thread) {} #endif static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: { /* The CtrlHandler runs in its own thread without stopping the main thread. Since in practice nobody uses the multi-VM stuff yet, we just grab the first VM we can get. This will not be a good idea when we actually support native threads. */ FACTOR_ASSERT(thread_vms.size() == 1); factor_vm* vm = thread_vms.begin()->second; vm->safepoint.enqueue_fep(vm); /* Before leaving the ctrl_handler, try and wake up the main thread. */ wake_up_thread(factor::boot_thread); return TRUE; } default: return FALSE; } } void open_console() { handle_ctrl_c(); } void ignore_ctrl_c() { SetConsoleCtrlHandler(factor::ctrl_handler, FALSE); } void handle_ctrl_c() { SetConsoleCtrlHandler(factor::ctrl_handler, TRUE); } void lock_console() {} void unlock_console() {} void close_console() {} cell get_thread_pc(THREADHANDLE th) { DWORD suscount = SuspendThread(th); FACTOR_ASSERT(suscount == 0); CONTEXT context; memset((void*)&context, 0, sizeof(CONTEXT)); context.ContextFlags = CONTEXT_CONTROL; BOOL context_ok = GetThreadContext(th, &context); FACTOR_ASSERT(context_ok); suscount = ResumeThread(th); FACTOR_ASSERT(suscount == 1); return context.EIP; } void factor_vm::sampler_thread_loop() { LARGE_INTEGER counter, new_counter, units_per_second; DWORD ok; ok = QueryPerformanceFrequency(&units_per_second); FACTOR_ASSERT(ok); ok = QueryPerformanceCounter(&counter); FACTOR_ASSERT(ok); counter.QuadPart *= samples_per_second; while (atomic::load(&sampling_profiler_p)) { SwitchToThread(); ok = QueryPerformanceCounter(&new_counter); FACTOR_ASSERT(ok); new_counter.QuadPart *= samples_per_second; cell samples = 0; while (new_counter.QuadPart - counter.QuadPart > units_per_second.QuadPart) { ++samples; counter.QuadPart += units_per_second.QuadPart; } if (samples == 0) continue; cell pc = get_thread_pc(thread); safepoint.enqueue_samples(this, samples, pc, false); } } static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) { static_cast<factor_vm*>(parent_vm)->sampler_thread_loop(); return 0; } void factor_vm::start_sampling_profiler_timer() { sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry, static_cast<LPVOID>(this), 0, NULL); } void factor_vm::end_sampling_profiler_timer() { atomic::store(&sampling_profiler_p, false); DWORD wait_result = WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second); if (wait_result != WAIT_OBJECT_0) TerminateThread(sampler_thread, 0); sampler_thread = NULL; } void abort() { ::abort(); } } <commit_msg>VM: fix the sampler_thread handle leak<commit_after>#include "master.hpp" namespace factor { HMODULE hFactorDll; bool set_memory_locked(cell base, cell size, bool locked) { int prot = locked ? PAGE_NOACCESS : PAGE_READWRITE; DWORD ignore; int status = VirtualProtect((char*)base, size, prot, &ignore); return status != 0; } void factor_vm::init_ffi() { hFactorDll = GetModuleHandle(NULL); if (!hFactorDll) fatal_error("GetModuleHandle() failed", 0); } void factor_vm::ffi_dlopen(dll* dll) { dll->handle = LoadLibraryEx((WCHAR*)alien_offset(dll->path), NULL, 0); } cell factor_vm::ffi_dlsym(dll* dll, symbol_char* symbol) { return (cell)GetProcAddress(dll ? (HMODULE) dll->handle : hFactorDll, symbol); } cell factor_vm::ffi_dlsym_raw(dll* dll, symbol_char* symbol) { return ffi_dlsym(dll, symbol); } void factor_vm::ffi_dlclose(dll* dll) { FreeLibrary((HMODULE) dll->handle); dll->handle = NULL; } BOOL factor_vm::windows_stat(vm_char* path) { BY_HANDLE_FILE_INFORMATION bhfi; HANDLE h = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (h == INVALID_HANDLE_VALUE) { // FindFirstFile is the only call that can stat c:\pagefile.sys WIN32_FIND_DATA st; HANDLE h; if (INVALID_HANDLE_VALUE == (h = FindFirstFile(path, &st))) return false; FindClose(h); return true; } BOOL ret = GetFileInformationByHandle(h, &bhfi); CloseHandle(h); return ret; } /* You must free() this yourself. */ const vm_char* factor_vm::default_image_path() { vm_char full_path[MAX_UNICODE_PATH]; vm_char* ptr; vm_char temp_path[MAX_UNICODE_PATH]; if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH)) fatal_error("GetModuleFileName() failed", 0); if ((ptr = wcsrchr(full_path, '.'))) *ptr = 0; wcsncpy(temp_path, full_path, MAX_UNICODE_PATH - 1); size_t full_path_len = wcslen(full_path); if (full_path_len < MAX_UNICODE_PATH - 1) wcsncat(temp_path, L".image", MAX_UNICODE_PATH - full_path_len - 1); temp_path[MAX_UNICODE_PATH - 1] = 0; return safe_strdup(temp_path); } /* You must free() this yourself. */ const vm_char* factor_vm::vm_executable_path() { vm_char full_path[MAX_UNICODE_PATH]; if (!GetModuleFileName(NULL, full_path, MAX_UNICODE_PATH)) fatal_error("GetModuleFileName() failed", 0); return safe_strdup(full_path); } void factor_vm::primitive_existsp() { vm_char* path = untag_check<byte_array>(ctx->pop())->data<vm_char>(); ctx->push(tag_boolean(windows_stat(path))); } segment::segment(cell size_, bool executable_p) { size = size_; char* mem; cell alloc_size = getpagesize() * 2 + size; if ((mem = (char*)VirtualAlloc( NULL, alloc_size, MEM_COMMIT, executable_p ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE)) == 0) { fatal_error("Out of memory in VirtualAlloc", alloc_size); } start = (cell)mem + getpagesize(); end = start + size; set_border_locked(true); } void segment::set_border_locked(bool locked) { int pagesize = getpagesize(); cell lo = start - pagesize; if (!set_memory_locked(lo, pagesize, locked)) { fatal_error("Cannot (un)protect low guard page", lo); } cell hi = end; if (!set_memory_locked(hi, pagesize, locked)) { fatal_error("Cannot (un)protect high guard page", hi); } } segment::~segment() { SYSTEM_INFO si; GetSystemInfo(&si); if (!VirtualFree((void*)(start - si.dwPageSize), 0, MEM_RELEASE)) fatal_error("Segment deallocation failed", 0); } long getpagesize() { static long g_pagesize = 0; if (!g_pagesize) { SYSTEM_INFO system_info; GetSystemInfo(&system_info); g_pagesize = system_info.dwPageSize; } return g_pagesize; } bool move_file(const vm_char* path1, const vm_char* path2) { /* MoveFileEx returns FALSE on fail. */ BOOL val = MoveFileEx((path1), (path2), MOVEFILE_REPLACE_EXISTING); if (val == FALSE) { /* MoveFileEx doesn't set errno, which primitive_save_image() reads the error code from. Instead of converting from GetLastError() to errno values, we ust set it to the generic EIO value. */ errno = EIO; } return val == TRUE; } void factor_vm::init_signals() {} THREADHANDLE start_thread(void* (*start_routine)(void*), void* args) { return (void*)CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) start_routine, args, 0, 0); } uint64_t nano_count() { static double scale_factor; static uint32_t hi = 0; static uint32_t lo = 0; LARGE_INTEGER count; BOOL ret = QueryPerformanceCounter(&count); if (ret == 0) fatal_error("QueryPerformanceCounter", 0); if (scale_factor == 0.0) { LARGE_INTEGER frequency; BOOL ret = QueryPerformanceFrequency(&frequency); if (ret == 0) fatal_error("QueryPerformanceFrequency", 0); scale_factor = (1000000000.0 / frequency.QuadPart); } #ifdef FACTOR_64 hi = count.HighPart; #else /* On VirtualBox, QueryPerformanceCounter does not increment the high part every time the low part overflows. Workaround. */ if (lo > count.LowPart) hi++; #endif lo = count.LowPart; return (uint64_t)((((uint64_t)hi << 32) | (uint64_t)lo) * scale_factor); } void sleep_nanos(uint64_t nsec) { Sleep((DWORD)(nsec / 1000000)); } typedef enum _EXCEPTION_DISPOSITION { ExceptionContinueExecution = 0, ExceptionContinueSearch = 1, ExceptionNestedException = 2, ExceptionCollidedUnwind = 3 } EXCEPTION_DISPOSITION; LONG factor_vm::exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c, void* dispatch) { switch (e->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: signal_fault_addr = e->ExceptionInformation[1]; signal_fault_pc = c->EIP; verify_memory_protection_error(signal_fault_addr); dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP, (cell)factor::memory_signal_handler_impl); break; case STATUS_FLOAT_DENORMAL_OPERAND: case STATUS_FLOAT_DIVIDE_BY_ZERO: case STATUS_FLOAT_INEXACT_RESULT: case STATUS_FLOAT_INVALID_OPERATION: case STATUS_FLOAT_OVERFLOW: case STATUS_FLOAT_STACK_CHECK: case STATUS_FLOAT_UNDERFLOW: case STATUS_FLOAT_MULTIPLE_FAULTS: case STATUS_FLOAT_MULTIPLE_TRAPS: #ifdef FACTOR_64 signal_fpu_status = fpu_status(MXCSR(c)); #else signal_fpu_status = fpu_status(X87SW(c) | MXCSR(c)); /* This seems to have no effect */ X87SW(c) = 0; #endif MXCSR(c) &= 0xffffffc0; dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP, (cell)factor::fp_signal_handler_impl); break; default: signal_number = e->ExceptionCode; dispatch_signal_handler((cell*)&c->ESP, (cell*)&c->EIP, (cell)factor::synchronous_signal_handler_impl); break; } return ExceptionContinueExecution; } VM_C_API LONG exception_handler(PEXCEPTION_RECORD e, void* frame, PCONTEXT c, void* dispatch) { factor_vm* vm = current_vm_p(); if (factor_vm::fatal_erroring_p || !vm) return ExceptionContinueSearch; return vm->exception_handler(e, frame, c, dispatch); } /* On Unix SIGINT (ctrl-c) automatically interrupts blocking io system calls. It doesn't on Windows, so we need to manually send some cancellation requests to unblock the thread. */ VOID CALLBACK dummy_cb (ULONG_PTR dwParam) { } // CancelSynchronousIo is not in Windows XP #if _WIN32_WINNT >= 0x0600 static void wake_up_thread(HANDLE thread) { if (!CancelSynchronousIo(thread)) { DWORD err = GetLastError(); /* CancelSynchronousIo() didn't find anything to cancel, let's try with QueueUserAPC() instead. */ if (err == ERROR_NOT_FOUND) { if (!QueueUserAPC(&dummy_cb, thread, NULL)) { fatal_error("QueueUserAPC() failed", GetLastError()); } } else { fatal_error("CancelSynchronousIo() failed", err); } } } #else static void wake_up_thread(HANDLE thread) {} #endif static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_C_EVENT: { /* The CtrlHandler runs in its own thread without stopping the main thread. Since in practice nobody uses the multi-VM stuff yet, we just grab the first VM we can get. This will not be a good idea when we actually support native threads. */ FACTOR_ASSERT(thread_vms.size() == 1); factor_vm* vm = thread_vms.begin()->second; vm->safepoint.enqueue_fep(vm); /* Before leaving the ctrl_handler, try and wake up the main thread. */ wake_up_thread(factor::boot_thread); return TRUE; } default: return FALSE; } } void open_console() { handle_ctrl_c(); } void ignore_ctrl_c() { SetConsoleCtrlHandler(factor::ctrl_handler, FALSE); } void handle_ctrl_c() { SetConsoleCtrlHandler(factor::ctrl_handler, TRUE); } void lock_console() {} void unlock_console() {} void close_console() {} cell get_thread_pc(THREADHANDLE th) { DWORD suscount = SuspendThread(th); FACTOR_ASSERT(suscount == 0); CONTEXT context; memset((void*)&context, 0, sizeof(CONTEXT)); context.ContextFlags = CONTEXT_CONTROL; BOOL context_ok = GetThreadContext(th, &context); FACTOR_ASSERT(context_ok); suscount = ResumeThread(th); FACTOR_ASSERT(suscount == 1); return context.EIP; } void factor_vm::sampler_thread_loop() { LARGE_INTEGER counter, new_counter, units_per_second; DWORD ok; ok = QueryPerformanceFrequency(&units_per_second); FACTOR_ASSERT(ok); ok = QueryPerformanceCounter(&counter); FACTOR_ASSERT(ok); counter.QuadPart *= samples_per_second; while (atomic::load(&sampling_profiler_p)) { SwitchToThread(); ok = QueryPerformanceCounter(&new_counter); FACTOR_ASSERT(ok); new_counter.QuadPart *= samples_per_second; cell samples = 0; while (new_counter.QuadPart - counter.QuadPart > units_per_second.QuadPart) { ++samples; counter.QuadPart += units_per_second.QuadPart; } if (samples == 0) continue; cell pc = get_thread_pc(thread); safepoint.enqueue_samples(this, samples, pc, false); } } static DWORD WINAPI sampler_thread_entry(LPVOID parent_vm) { static_cast<factor_vm*>(parent_vm)->sampler_thread_loop(); return 0; } void factor_vm::start_sampling_profiler_timer() { sampler_thread = CreateThread(NULL, 0, &sampler_thread_entry, static_cast<LPVOID>(this), 0, NULL); } void factor_vm::end_sampling_profiler_timer() { atomic::store(&sampling_profiler_p, false); DWORD wait_result = WaitForSingleObject(sampler_thread, 3000 * (DWORD) samples_per_second); if (wait_result != WAIT_OBJECT_0) TerminateThread(sampler_thread, 0); CloseHandle(sampler_thread); sampler_thread = NULL; } void abort() { ::abort(); } } <|endoftext|>
<commit_before>#ifndef GCL_TMP_H_ # define GCL_TMP_H_ #include <array> namespace gcl::mp { // C++17 template <typename ... ts> struct super : ts... {}; template <template <typename...> class trait_type, typename ... ts> struct partial_template { template <typename ... us> using type = trait_type<ts..., us...>; template <typename ... us> static constexpr bool value = trait_type<ts..., us...>::value; }; template <template <typename> class ... constraint_type> struct require { // todo : std::conjunction ? template <typename T> static constexpr void on() { (check_constraint<constraint_type, T>(), ...); } template <typename T> static inline constexpr std::array<bool, sizeof...(constraint_type)> values_on{ std::move(constraint_type<T>::value)... }; private: template <template <typename> class constraint_type, typename T> static constexpr void check_constraint() { static_assert(constraint_type<T>::value, "constraint failed to apply. see template context for more infos"); } }; template <typename T, typename ... ts> static constexpr inline bool contains = std::disjunction<std::is_same<T, ts>...>::value; template <typename to_find, typename ... ts> constexpr auto get_index() { return index_of<to_find, ts...>; // [C++20] constexpr => std::count, std::find /*static_assert(contains<to_find, ts...>); constexpr auto result = gcl::mp::require < gcl::mp::partial_template<std::is_same, ts>::type ... >::values_on<to_find>; auto count = std::count(std::cbegin(result), std::cend(result), true); if (count > 1) throw std::runtime_error("get_index : duplicate type"); if (count == 0) throw std::out_of_range("get_index : no match"); return std::distance ( std::cbegin(result), std::find(std::cbegin(result), std::cend(result), true) );*/ } // C++17 constexpr index_of. Use recursion. remove when C++20 is ready. see get_index comments for more infos. template <typename T, typename ...ts> static constexpr inline auto index_of = index_of_impl<T, ts...>(); template <typename T, typename T_it = void, typename... ts> static constexpr std::size_t index_of_impl() { if constexpr (std::is_same_v<T, T_it>) return 0; if constexpr (sizeof...(ts) == 0) throw 0; // "index_of : no match found"; return 1 + index_of_impl<T, ts...>(); } struct filter { // allow filtering operation on variadic type, // using gcl::mp::contains and std::bitset // or_as_bitset impl is : // { T0, T1, T2 } | {T4, T1, T5} => 010 using std_bitset_initializer_type = unsigned long long; static_assert(std::is_constructible_v<std::bitset<8>, std_bitset_initializer_type>); template <typename ... ts, typename ... us> constexpr static auto or_as_bitset_initializer(std::tuple<ts...> const&, std::tuple<us...> const&) { return or_as_bitset_initializer_impl(std::tuple<ts...>{}, std::tuple<us...>{}, 0); } template <typename ... ts, typename ... us> constexpr static auto or_as_bitset(std::tuple<ts...> const&, std::tuple<us...> const&) { const auto initializer = or_as_bitset_initializer(std::tuple<ts...>{}, std::tuple<us...>{}); return std::bitset<sizeof...(ts)>{initializer}; } private: template <typename T_it, typename ... ts, typename ... us> constexpr static auto or_as_bitset_initializer_impl(std::tuple<T_it, ts...> const&, std::tuple<us...> const&, std_bitset_initializer_type value = 0) { // todo : no recursion. something like : // return ((value |= std_bitset_initializer_type{ gcl::mp::contains<ts, us...> }) << 1), ...; value |= gcl::mp::contains<T_it, us...>; if constexpr (sizeof...(ts) == 0) return value; else return or_as_bitset_initializer_impl(std::tuple<ts...>{}, std::tuple<us...>{}, value << 1); } }; } namespace gcl::deprecated::mp { // C++98 template <class T, class ... T_Classes> struct super { struct Type : T, super<T_Classes...>::Type {}; }; template <class T> struct super<T> { using Type = T; }; // constexpr if template <bool condition, typename _THEN, typename _ELSE> struct IF {}; template <typename _THEN, typename _ELSE> struct IF<true, _THEN, _ELSE> { using _Type = _THEN; }; template <typename _THEN, typename _ELSE> struct IF<false, _THEN, _ELSE> { using _Type = _ELSE; }; struct out_of_range {}; template <size_t N_id = 0> struct list { static constexpr size_t id = N_id; using type_t = list<id>; using next = list<id + 1>; using previous = mp::IF<(id == 0), out_of_range, list<id - 1> >; constexpr static const bool is_head = mp::IF<(id == 0), true, false>; }; template <template <typename> class T_trait> struct apply_trait { template <typename T> static constexpr bool value = T_trait<T>::value; }; template <template <typename> class T_Constraint> struct require { template <typename T> static constexpr void on() { static_assert(T_Constraint<T>::value, "gcl::mp::apply_constraint : constraint not matched"); } }; template <typename ... T> struct for_each; template <typename T0, typename ... T> struct for_each<T0, T...> { for_each() = delete; for_each(const for_each &) = delete; for_each(const for_each &&) = delete; template <template <typename> class T_Constraint> struct require { T_Constraint<T0> _check; // Check by generation, not value typename for_each<T...>::template require<T_Constraint> _next; }; template <template <typename> class T_Functor> static void call(void) { T_Functor<T0>::call(); for_each<T...>::call<T_Functor>(); } template <template <typename> class T_Functor, size_t N = 0> static void call_at(const size_t pos) { if (N == pos) T_Functor<T0>::call(); else for_each<T...>::call_at<T_Functor, (N + 1)>(pos); } template <template <typename> class T_Functor, size_t N = 0> static typename T_Functor<T0>::return_type call_at_with_return_value(const size_t pos) { if (N == pos) return T_Functor<T0>::call(); else return for_each<T...>::call_at_with_return_value<T_Functor, (N + 1)>(pos); } }; template <> struct for_each<> { for_each() = delete; for_each(const for_each &) = delete; for_each(const for_each &&) = delete; template <template <typename> class T_Constraint> struct require {}; template <template <typename> class T_Functor> static void call(void) {} template <template <typename> class T_Functor, size_t N = 0> static void call_at(const size_t pos) { throw std::out_of_range("template <typename ... T> struct for_each::call_at"); } template <template <typename> class T_Functor, size_t N = 0> static typename T_Functor<void>::return_type call_at_with_return_value(const size_t pos) { throw std::out_of_range("template <typename ... T> struct for_each::call_at_with_return_value"); } }; } #endif // GCL_TMP_H_ <commit_msg>gcl::mp::filter : replace std::tuple by gcl::mp::type_pack, as it is a constexpr, empty type<commit_after>#ifndef GCL_TMP_H_ # define GCL_TMP_H_ #include <array> namespace gcl::mp { // C++17 template <typename ... ts> struct type_pack { // constexpr type that has variadic parameter // use this instead of std::tuple for viariadic-as-std-tuple-parameter }; template <typename ... ts> struct super : ts... {}; template <template <typename...> class trait_type, typename ... ts> struct partial_template { template <typename ... us> using type = trait_type<ts..., us...>; template <typename ... us> static constexpr bool value = trait_type<ts..., us...>::value; }; template <template <typename> class ... constraint_type> struct require { // todo : std::conjunction ? template <typename T> static constexpr void on() { (check_constraint<constraint_type, T>(), ...); } template <typename T> static inline constexpr std::array<bool, sizeof...(constraint_type)> values_on{ std::move(constraint_type<T>::value)... }; private: template <template <typename> class constraint_type, typename T> static constexpr void check_constraint() { static_assert(constraint_type<T>::value, "constraint failed to apply. see template context for more infos"); } }; template <typename T, typename ... ts> static constexpr inline bool contains = std::disjunction<std::is_same<T, ts>...>::value; template <typename to_find, typename ... ts> constexpr auto get_index() { return index_of<to_find, ts...>; // [C++20] constexpr => std::count, std::find /*static_assert(contains<to_find, ts...>); constexpr auto result = gcl::mp::require < gcl::mp::partial_template<std::is_same, ts>::type ... >::values_on<to_find>; auto count = std::count(std::cbegin(result), std::cend(result), true); if (count > 1) throw std::runtime_error("get_index : duplicate type"); if (count == 0) throw std::out_of_range("get_index : no match"); return std::distance ( std::cbegin(result), std::find(std::cbegin(result), std::cend(result), true) );*/ } // C++17 constexpr index_of. Use recursion. remove when C++20 is ready. see get_index comments for more infos. template <typename T, typename ...ts> static constexpr inline auto index_of = index_of_impl<T, ts...>(); template <typename T, typename T_it = void, typename... ts> static constexpr std::size_t index_of_impl() { if constexpr (std::is_same_v<T, T_it>) return 0; if constexpr (sizeof...(ts) == 0) throw 0; // "index_of : no match found"; return 1 + index_of_impl<T, ts...>(); } struct filter { // allow filtering operation on variadic type, // using gcl::mp::contains and std::bitset // or_as_bitset impl is : // { T0, T1, T2 } | {T4, T1, T5} => 010 using std_bitset_initializer_type = unsigned long long; static_assert(std::is_constructible_v<std::bitset<8>, std_bitset_initializer_type>); template <typename ... ts, typename ... us> constexpr static auto or_as_bitset_initializer(type_pack<ts...> const&, type_pack<us...> const&) { return or_as_bitset_initializer_impl(type_pack<ts...>{}, type_pack<us...>{}, 0); } template <typename ... ts, typename ... us> constexpr static auto or_as_bitset(type_pack<ts...> const&, type_pack<us...> const&) { const auto initializer = or_as_bitset_initializer(type_pack<ts...>{}, type_pack<us...>{}); return std::bitset<sizeof...(ts)>{initializer}; } private: template <typename T_it, typename ... ts, typename ... us> constexpr static auto or_as_bitset_initializer_impl(type_pack<T_it, ts...> const&, type_pack<us...> const&, std_bitset_initializer_type value = 0) { // todo : no recursion. something like : // return ((value |= std_bitset_initializer_type{ gcl::mp::contains<ts, us...> }) << 1), ...; value |= gcl::mp::contains<T_it, us...>; if constexpr (sizeof...(ts) == 0) return value; else return or_as_bitset_initializer_impl(type_pack<ts...>{}, type_pack<us...>{}, value << 1); } }; } namespace gcl::deprecated::mp { // C++98 template <class T, class ... T_Classes> struct super { struct Type : T, super<T_Classes...>::Type {}; }; template <class T> struct super<T> { using Type = T; }; // constexpr if template <bool condition, typename _THEN, typename _ELSE> struct IF {}; template <typename _THEN, typename _ELSE> struct IF<true, _THEN, _ELSE> { using _Type = _THEN; }; template <typename _THEN, typename _ELSE> struct IF<false, _THEN, _ELSE> { using _Type = _ELSE; }; struct out_of_range {}; template <size_t N_id = 0> struct list { static constexpr size_t id = N_id; using type_t = list<id>; using next = list<id + 1>; using previous = mp::IF<(id == 0), out_of_range, list<id - 1> >; constexpr static const bool is_head = mp::IF<(id == 0), true, false>; }; template <template <typename> class T_trait> struct apply_trait { template <typename T> static constexpr bool value = T_trait<T>::value; }; template <template <typename> class T_Constraint> struct require { template <typename T> static constexpr void on() { static_assert(T_Constraint<T>::value, "gcl::mp::apply_constraint : constraint not matched"); } }; template <typename ... T> struct for_each; template <typename T0, typename ... T> struct for_each<T0, T...> { for_each() = delete; for_each(const for_each &) = delete; for_each(const for_each &&) = delete; template <template <typename> class T_Constraint> struct require { T_Constraint<T0> _check; // Check by generation, not value typename for_each<T...>::template require<T_Constraint> _next; }; template <template <typename> class T_Functor> static void call(void) { T_Functor<T0>::call(); for_each<T...>::call<T_Functor>(); } template <template <typename> class T_Functor, size_t N = 0> static void call_at(const size_t pos) { if (N == pos) T_Functor<T0>::call(); else for_each<T...>::call_at<T_Functor, (N + 1)>(pos); } template <template <typename> class T_Functor, size_t N = 0> static typename T_Functor<T0>::return_type call_at_with_return_value(const size_t pos) { if (N == pos) return T_Functor<T0>::call(); else return for_each<T...>::call_at_with_return_value<T_Functor, (N + 1)>(pos); } }; template <> struct for_each<> { for_each() = delete; for_each(const for_each &) = delete; for_each(const for_each &&) = delete; template <template <typename> class T_Constraint> struct require {}; template <template <typename> class T_Functor> static void call(void) {} template <template <typename> class T_Functor, size_t N = 0> static void call_at(const size_t pos) { throw std::out_of_range("template <typename ... T> struct for_each::call_at"); } template <template <typename> class T_Functor, size_t N = 0> static typename T_Functor<void>::return_type call_at_with_return_value(const size_t pos) { throw std::out_of_range("template <typename ... T> struct for_each::call_at_with_return_value"); } }; } #endif // GCL_TMP_H_ <|endoftext|>
<commit_before>#include "lightstep_span.h" #include "utility.h" using opentracing::SystemTime; using opentracing::SystemClock; using opentracing::SteadyClock; using opentracing::SteadyTime; namespace lightstep { //------------------------------------------------------------------------------ // ComputeStartTimestamps //------------------------------------------------------------------------------ static std::tuple<SystemTime, SteadyTime> ComputeStartTimestamps( const SystemTime& start_system_timestamp, const SteadyTime& start_steady_timestamp) { // If neither the system nor steady timestamps are set, get the tme from the // respective clocks; otherwise, use the set timestamp to initialize the // other. if (start_system_timestamp == SystemTime() && start_steady_timestamp == SteadyTime()) { return {SystemClock::now(), SteadyClock::now()}; } if (start_system_timestamp == SystemTime()) { return { opentracing::convert_time_point<SystemClock>(start_steady_timestamp), start_steady_timestamp}; } if (start_steady_timestamp == SteadyTime()) { return { start_system_timestamp, opentracing::convert_time_point<SteadyClock>(start_system_timestamp)}; } return {start_system_timestamp, start_steady_timestamp}; } //------------------------------------------------------------------------------ // SetSpanReference //------------------------------------------------------------------------------ static bool SetSpanReference( spdlog::logger& logger, const std::pair<opentracing::SpanReferenceType, const opentracing::SpanContext*>& reference, std::unordered_map<std::string, std::string>& baggage, collector::Reference& collector_reference) { collector_reference.Clear(); switch (reference.first) { case opentracing::SpanReferenceType::ChildOfRef: collector_reference.set_relationship(collector::Reference::CHILD_OF); break; case opentracing::SpanReferenceType::FollowsFromRef: collector_reference.set_relationship(collector::Reference::FOLLOWS_FROM); break; } if (reference.second == nullptr) { logger.warn("Passed in null span reference."); return false; } auto referenced_context = dynamic_cast<const LightStepSpanContext*>(reference.second); if (referenced_context == nullptr) { logger.warn("Passed in span reference of unexpected type."); return false; } collector_reference.mutable_span_context()->set_trace_id( referenced_context->trace_id()); collector_reference.mutable_span_context()->set_span_id( referenced_context->span_id()); referenced_context->ForeachBaggageItem( [&baggage](const std::string& key, const std::string& value) { baggage[key] = value; return true; }); return true; } //------------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------------ LightStepSpan::LightStepSpan( std::shared_ptr<const opentracing::Tracer>&& tracer, spdlog::logger& logger, Recorder& recorder, opentracing::string_view operation_name, const opentracing::StartSpanOptions& options) : tracer_{std::move(tracer)}, logger_{logger}, recorder_{recorder}, operation_name_{operation_name} { // Set the start timestamps. std::tie(start_timestamp_, start_steady_) = ComputeStartTimestamps( options.start_system_timestamp, options.start_steady_timestamp); // Set any span references. std::unordered_map<std::string, std::string> baggage; references_.reserve(options.references.size()); collector::Reference collector_reference; for (auto& reference : options.references) { if (!SetSpanReference(logger_, reference, baggage, collector_reference)) { continue; } references_.push_back(collector_reference); } // Set tags. for (auto& tag : options.tags) { tags_[tag.first] = tag.second; } // Set opentracing::SpanContext. auto trace_id = references_.empty() ? GenerateId() : references_[0].span_context().trace_id(); auto span_id = GenerateId(); span_context_ = LightStepSpanContext{trace_id, span_id, std::move(baggage)}; } //------------------------------------------------------------------------------ // Destructor //------------------------------------------------------------------------------ LightStepSpan::~LightStepSpan() { if (!is_finished_) { Finish(); } } //------------------------------------------------------------------------------ // FinishWithOptions //------------------------------------------------------------------------------ void LightStepSpan::FinishWithOptions( const opentracing::FinishSpanOptions& options) noexcept try { // Ensure the span is only finished once. if (is_finished_.exchange(true)) { return; } auto finish_timestamp = options.finish_steady_timestamp; if (finish_timestamp == SteadyTime()) { finish_timestamp = SteadyClock::now(); } collector::Span span; // Set timing information. auto duration = finish_timestamp - start_steady_; span.set_duration_micros( std::chrono::duration_cast<std::chrono::microseconds>(duration).count()); *span.mutable_start_timestamp() = ToTimestamp(start_timestamp_); // Set references. auto references = span.mutable_references(); references->Reserve(static_cast<int>(references_.size())); for (const auto& reference : references_) { *references->Add() = reference; } // Set tags, logs, and operation name. { std::lock_guard<std::mutex> lock_guard{mutex_}; span.set_operation_name(std::move(operation_name_)); auto tags = span.mutable_tags(); tags->Reserve(static_cast<int>(tags_.size())); for (const auto& tag : tags_) { try { *tags->Add() = ToKeyValue(tag.first, tag.second); } catch (const std::exception& e) { logger_.error(R"(Dropping tag for key "{}": {})", tag.first, e.what()); } } auto logs = span.mutable_logs(); for (auto& log : logs_) { *logs->Add() = log; } } // Set the span context. auto span_context = span.mutable_span_context(); span_context->set_trace_id(span_context_.trace_id()); span_context->set_span_id(span_context_.span_id()); auto baggage = span_context->mutable_baggage(); span_context_.ForeachBaggageItem( [baggage](const std::string& key, const std::string& value) { using StringMap = google::protobuf::Map<std::string, std::string>; baggage->insert(StringMap::value_type(key, value)); return true; }); // Record the span recorder_.RecordSpan(std::move(span)); } catch (const std::bad_alloc&) { // Do nothing if memory allocation fails. logger_.error("Span::FinishWithOptions failed."); } //------------------------------------------------------------------------------ // SetOperationName //------------------------------------------------------------------------------ void LightStepSpan::SetOperationName( opentracing::string_view name) noexcept try { std::lock_guard<std::mutex> lock_guard{mutex_}; operation_name_ = name; } catch (const std::bad_alloc&) { // Don't change operation name if memory can't be allocated for it. logger_.error("Span::SetOperationName failed."); } //------------------------------------------------------------------------------ // SetTag //------------------------------------------------------------------------------ void LightStepSpan::SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept try { std::lock_guard<std::mutex> lock_guard{mutex_}; tags_[key] = value; } catch (const std::bad_alloc&) { // Don't add the tag if memory can't be allocated for it. logger_.error("Span::SetTag failed."); } //------------------------------------------------------------------------------ // SetBaggageItem //------------------------------------------------------------------------------ void LightStepSpan::SetBaggageItem(opentracing::string_view restricted_key, opentracing::string_view value) noexcept { span_context_.set_baggage_item(restricted_key, value); } //------------------------------------------------------------------------------ // BaggageItem //------------------------------------------------------------------------------ std::string LightStepSpan::BaggageItem( opentracing::string_view restricted_key) const noexcept try { return span_context_.baggage_item(restricted_key); } catch (const std::bad_alloc&) { logger_.error("Span::BaggageItem failed, returning empty string."); return {}; } //------------------------------------------------------------------------------ // Log //------------------------------------------------------------------------------ void LightStepSpan::Log(std::initializer_list< std::pair<opentracing::string_view, opentracing::Value>> fields) noexcept try { auto timestamp = SystemClock::now(); collector::Log log; *log.mutable_timestamp() = ToTimestamp(timestamp); auto key_values = log.mutable_keyvalues(); for (const auto& field : fields) { try { *key_values->Add() = ToKeyValue(field.first, field.second); } catch (const std::exception& e) { logger_.error(R"(Failed to log record for key "{}":)", std::string{field.first}, e.what()); } } logs_.emplace_back(std::move(log)); } catch (const std::bad_alloc&) { // Do nothing if memory can't be allocted for log records. logger_.error("Span::Log failed."); } } // namespace lightstep <commit_msg>Fix error log.<commit_after>#include "lightstep_span.h" #include "utility.h" using opentracing::SystemTime; using opentracing::SystemClock; using opentracing::SteadyClock; using opentracing::SteadyTime; namespace lightstep { //------------------------------------------------------------------------------ // ComputeStartTimestamps //------------------------------------------------------------------------------ static std::tuple<SystemTime, SteadyTime> ComputeStartTimestamps( const SystemTime& start_system_timestamp, const SteadyTime& start_steady_timestamp) { // If neither the system nor steady timestamps are set, get the tme from the // respective clocks; otherwise, use the set timestamp to initialize the // other. if (start_system_timestamp == SystemTime() && start_steady_timestamp == SteadyTime()) { return {SystemClock::now(), SteadyClock::now()}; } if (start_system_timestamp == SystemTime()) { return { opentracing::convert_time_point<SystemClock>(start_steady_timestamp), start_steady_timestamp}; } if (start_steady_timestamp == SteadyTime()) { return { start_system_timestamp, opentracing::convert_time_point<SteadyClock>(start_system_timestamp)}; } return {start_system_timestamp, start_steady_timestamp}; } //------------------------------------------------------------------------------ // SetSpanReference //------------------------------------------------------------------------------ static bool SetSpanReference( spdlog::logger& logger, const std::pair<opentracing::SpanReferenceType, const opentracing::SpanContext*>& reference, std::unordered_map<std::string, std::string>& baggage, collector::Reference& collector_reference) { collector_reference.Clear(); switch (reference.first) { case opentracing::SpanReferenceType::ChildOfRef: collector_reference.set_relationship(collector::Reference::CHILD_OF); break; case opentracing::SpanReferenceType::FollowsFromRef: collector_reference.set_relationship(collector::Reference::FOLLOWS_FROM); break; } if (reference.second == nullptr) { logger.warn("Passed in null span reference."); return false; } auto referenced_context = dynamic_cast<const LightStepSpanContext*>(reference.second); if (referenced_context == nullptr) { logger.warn("Passed in span reference of unexpected type."); return false; } collector_reference.mutable_span_context()->set_trace_id( referenced_context->trace_id()); collector_reference.mutable_span_context()->set_span_id( referenced_context->span_id()); referenced_context->ForeachBaggageItem( [&baggage](const std::string& key, const std::string& value) { baggage[key] = value; return true; }); return true; } //------------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------------ LightStepSpan::LightStepSpan( std::shared_ptr<const opentracing::Tracer>&& tracer, spdlog::logger& logger, Recorder& recorder, opentracing::string_view operation_name, const opentracing::StartSpanOptions& options) : tracer_{std::move(tracer)}, logger_{logger}, recorder_{recorder}, operation_name_{operation_name} { // Set the start timestamps. std::tie(start_timestamp_, start_steady_) = ComputeStartTimestamps( options.start_system_timestamp, options.start_steady_timestamp); // Set any span references. std::unordered_map<std::string, std::string> baggage; references_.reserve(options.references.size()); collector::Reference collector_reference; for (auto& reference : options.references) { if (!SetSpanReference(logger_, reference, baggage, collector_reference)) { continue; } references_.push_back(collector_reference); } // Set tags. for (auto& tag : options.tags) { tags_[tag.first] = tag.second; } // Set opentracing::SpanContext. auto trace_id = references_.empty() ? GenerateId() : references_[0].span_context().trace_id(); auto span_id = GenerateId(); span_context_ = LightStepSpanContext{trace_id, span_id, std::move(baggage)}; } //------------------------------------------------------------------------------ // Destructor //------------------------------------------------------------------------------ LightStepSpan::~LightStepSpan() { if (!is_finished_) { Finish(); } } //------------------------------------------------------------------------------ // FinishWithOptions //------------------------------------------------------------------------------ void LightStepSpan::FinishWithOptions( const opentracing::FinishSpanOptions& options) noexcept try { // Ensure the span is only finished once. if (is_finished_.exchange(true)) { return; } auto finish_timestamp = options.finish_steady_timestamp; if (finish_timestamp == SteadyTime()) { finish_timestamp = SteadyClock::now(); } collector::Span span; // Set timing information. auto duration = finish_timestamp - start_steady_; span.set_duration_micros( std::chrono::duration_cast<std::chrono::microseconds>(duration).count()); *span.mutable_start_timestamp() = ToTimestamp(start_timestamp_); // Set references. auto references = span.mutable_references(); references->Reserve(static_cast<int>(references_.size())); for (const auto& reference : references_) { *references->Add() = reference; } // Set tags, logs, and operation name. { std::lock_guard<std::mutex> lock_guard{mutex_}; span.set_operation_name(std::move(operation_name_)); auto tags = span.mutable_tags(); tags->Reserve(static_cast<int>(tags_.size())); for (const auto& tag : tags_) { try { *tags->Add() = ToKeyValue(tag.first, tag.second); } catch (const std::exception& e) { logger_.error(R"(Dropping tag for key "{}": {})", tag.first, e.what()); } } auto logs = span.mutable_logs(); for (auto& log : logs_) { *logs->Add() = log; } } // Set the span context. auto span_context = span.mutable_span_context(); span_context->set_trace_id(span_context_.trace_id()); span_context->set_span_id(span_context_.span_id()); auto baggage = span_context->mutable_baggage(); span_context_.ForeachBaggageItem( [baggage](const std::string& key, const std::string& value) { using StringMap = google::protobuf::Map<std::string, std::string>; baggage->insert(StringMap::value_type(key, value)); return true; }); // Record the span recorder_.RecordSpan(std::move(span)); } catch (const std::bad_alloc&) { // Do nothing if memory allocation fails. logger_.error("Span::FinishWithOptions failed."); } //------------------------------------------------------------------------------ // SetOperationName //------------------------------------------------------------------------------ void LightStepSpan::SetOperationName( opentracing::string_view name) noexcept try { std::lock_guard<std::mutex> lock_guard{mutex_}; operation_name_ = name; } catch (const std::bad_alloc&) { // Don't change operation name if memory can't be allocated for it. logger_.error("Span::SetOperationName failed."); } //------------------------------------------------------------------------------ // SetTag //------------------------------------------------------------------------------ void LightStepSpan::SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept try { std::lock_guard<std::mutex> lock_guard{mutex_}; tags_[key] = value; } catch (const std::bad_alloc&) { // Don't add the tag if memory can't be allocated for it. logger_.error("Span::SetTag failed."); } //------------------------------------------------------------------------------ // SetBaggageItem //------------------------------------------------------------------------------ void LightStepSpan::SetBaggageItem(opentracing::string_view restricted_key, opentracing::string_view value) noexcept { span_context_.set_baggage_item(restricted_key, value); } //------------------------------------------------------------------------------ // BaggageItem //------------------------------------------------------------------------------ std::string LightStepSpan::BaggageItem( opentracing::string_view restricted_key) const noexcept try { return span_context_.baggage_item(restricted_key); } catch (const std::bad_alloc&) { logger_.error("Span::BaggageItem failed, returning empty string."); return {}; } //------------------------------------------------------------------------------ // Log //------------------------------------------------------------------------------ void LightStepSpan::Log(std::initializer_list< std::pair<opentracing::string_view, opentracing::Value>> fields) noexcept try { auto timestamp = SystemClock::now(); collector::Log log; *log.mutable_timestamp() = ToTimestamp(timestamp); auto key_values = log.mutable_keyvalues(); for (const auto& field : fields) { try { *key_values->Add() = ToKeyValue(field.first, field.second); } catch (const std::exception& e) { logger_.error(R"(Failed to log record for key "{}": {})", std::string{field.first}, e.what()); } } logs_.emplace_back(std::move(log)); } catch (const std::bad_alloc&) { // Do nothing if memory can't be allocted for log records. logger_.error("Span::Log failed."); } } // namespace lightstep <|endoftext|>
<commit_before>// Copyright 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. #include "cc/heads_up_display_layer.h" #include "base/debug/trace_event.h" #include "cc/heads_up_display_layer_impl.h" #include "cc/layer_tree_host.h" namespace cc { scoped_refptr<HeadsUpDisplayLayer> HeadsUpDisplayLayer::create() { return make_scoped_refptr(new HeadsUpDisplayLayer()); } HeadsUpDisplayLayer::HeadsUpDisplayLayer() : Layer() { setBounds(gfx::Size(256, 256)); } HeadsUpDisplayLayer::~HeadsUpDisplayLayer() { } void HeadsUpDisplayLayer::update(ResourceUpdateQueue&, const OcclusionTracker*, RenderingStats*) { const LayerTreeDebugState& debugState = layerTreeHost()->debugState(); int maxTextureSize = layerTreeHost()->rendererCapabilities().maxTextureSize; gfx::Size bounds; gfx::Transform matrix; matrix.MakeIdentity(); if (debugState.showPlatformLayerTree || debugState.showHudRects()) { int width = std::min(maxTextureSize, layerTreeHost()->layoutViewportSize().width()); int height = std::min(maxTextureSize, layerTreeHost()->layoutViewportSize().height()); bounds = gfx::Size(width, height); } else { bounds = gfx::Size(256, 256); matrix.Translate(layerTreeHost()->layoutViewportSize().width() - 256, 0); } setBounds(bounds); setTransform(matrix); } bool HeadsUpDisplayLayer::drawsContent() const { return true; } scoped_ptr<LayerImpl> HeadsUpDisplayLayer::createLayerImpl(LayerTreeImpl* treeImpl) { return HeadsUpDisplayLayerImpl::create(treeImpl, m_layerId).PassAs<LayerImpl>(); } } // namespace cc <commit_msg>cc: fix HudLayer to be sized by device<commit_after>// Copyright 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. #include "cc/heads_up_display_layer.h" #include "base/debug/trace_event.h" #include "cc/heads_up_display_layer_impl.h" #include "cc/layer_tree_host.h" namespace cc { scoped_refptr<HeadsUpDisplayLayer> HeadsUpDisplayLayer::create() { return make_scoped_refptr(new HeadsUpDisplayLayer()); } HeadsUpDisplayLayer::HeadsUpDisplayLayer() : Layer() { setBounds(gfx::Size(256, 256)); } HeadsUpDisplayLayer::~HeadsUpDisplayLayer() { } void HeadsUpDisplayLayer::update(ResourceUpdateQueue&, const OcclusionTracker*, RenderingStats*) { const LayerTreeDebugState& debugState = layerTreeHost()->debugState(); int maxTextureSize = layerTreeHost()->rendererCapabilities().maxTextureSize; int deviceViewportInLayoutPixelsWidth = layerTreeHost()->deviceViewportSize().width() / layerTreeHost()->deviceScaleFactor(); int deviceViewportInLayoutPixelsHeight = layerTreeHost()->deviceViewportSize().height() / layerTreeHost()->deviceScaleFactor(); gfx::Size bounds; gfx::Transform matrix; matrix.MakeIdentity(); if (debugState.showPlatformLayerTree || debugState.showHudRects()) { int width = std::min(maxTextureSize, deviceViewportInLayoutPixelsWidth); int height = std::min(maxTextureSize, deviceViewportInLayoutPixelsHeight); bounds = gfx::Size(width, height); } else { bounds = gfx::Size(256, 256); matrix.Translate(deviceViewportInLayoutPixelsWidth - 256, 0); } setBounds(bounds); setTransform(matrix); } bool HeadsUpDisplayLayer::drawsContent() const { return true; } scoped_ptr<LayerImpl> HeadsUpDisplayLayer::createLayerImpl(LayerTreeImpl* treeImpl) { return HeadsUpDisplayLayerImpl::create(treeImpl, m_layerId).PassAs<LayerImpl>(); } } // namespace cc <|endoftext|>
<commit_before>/* This file is part of the clang-lazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected] Author: Sérgio Martins <[email protected]> Copyright (C) 2015 Sergio Martins <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "functionargsbyref.h" #include "Utils.h" #include "checkmanager.h" #include <clang/AST/AST.h> using namespace clang; using namespace std; static bool shouldIgnoreClass(const std::string &qualifiedClassName) { static const vector<string> ignoreList = {"QDebug", // Too many warnings "QGenericReturnArgument", "QColor", // TODO: Remove in Qt6 "QStringRef", // TODO: Remove in Qt6 "QList::const_iterator", // TODO: Remove in Qt6 "QJsonArray::const_iterator", // TODO: Remove in Qt6 "QList<QString>::const_iterator", // TODO: Remove in Qt6 "QtMetaTypePrivate::QSequentialIterableImpl", "QtMetaTypePrivate::QAssociativeIterableImpl" }; return std::find(ignoreList.cbegin(), ignoreList.cend(), qualifiedClassName) != ignoreList.cend(); } static bool shouldIgnoreFunction(const std::string &methodName) { // Too many warnings in operator<< static const vector<string> ignoreList = {"operator<<"}; return std::find(ignoreList.cbegin(), ignoreList.cend(), methodName) != ignoreList.cend(); } FunctionArgsByRef::FunctionArgsByRef(const std::string &name) : CheckBase(name) { } std::vector<string> FunctionArgsByRef::filesToIgnore() const { return {"/c++/", "qimage.cpp", // TODO: Uncomment in Qt6 "qimage.h", // TODO: Uncomment in Qt6 "qevent.h", // TODO: Uncomment in Qt6 "avxintrin.h", // Some clang internal "avx2intrin.h", // Some clang internal "qnoncontiguousbytedevice.cpp", "qlocale_unix.cpp", "/clang/" }; } static std::string warningMsgForSmallType(int sizeOf, const std::string &typeName) { std::string sizeStr = std::to_string(sizeOf); return "Missing reference on large type sizeof " + typeName + " is " + sizeStr + " bytes)"; } void FunctionArgsByRef::VisitDecl(Decl *decl) { FunctionDecl *functionDecl = dyn_cast<FunctionDecl>(decl); if (functionDecl == nullptr || !functionDecl->hasBody() || shouldIgnoreFunction(functionDecl->getNameAsString()) || !functionDecl->isThisDeclarationADefinition()) return; Stmt *body = functionDecl->getBody(); for (auto it = functionDecl->param_begin(), end = functionDecl->param_end(); it != end; ++it) { const ParmVarDecl *param = *it; QualType paramQt = param->getType(); const Type *paramType = paramQt.getTypePtrOrNull(); if (paramType == nullptr || paramType->isDependentType()) continue; const int size_of_T = m_ci.getASTContext().getTypeSize(paramQt) / 8; const bool isSmall = size_of_T <= 16; // TODO: What about arm ? CXXRecordDecl *recordDecl = paramType->getAsCXXRecordDecl(); const bool isNonTrivialCopyable = recordDecl && (recordDecl->hasNonTrivialCopyConstructor() || recordDecl->hasNonTrivialDestructor()); const bool isReference = paramType->isLValueReferenceType(); const bool isConst = paramQt.isConstQualified(); if (recordDecl && shouldIgnoreClass(recordDecl->getQualifiedNameAsString())) continue; std::string error; if (isConst && !isReference) { if (!isSmall) { error += warningMsgForSmallType(size_of_T, paramQt.getAsString()); } else if (isNonTrivialCopyable) { error += "Missing reference on non-trivial type " + recordDecl->getQualifiedNameAsString(); } } else if (isConst && isReference && !isNonTrivialCopyable && isSmall) { //error += "Don't use by-ref on small trivial type"; } else if (!isConst && !isReference && (!isSmall || isNonTrivialCopyable)) { if (Utils::containsNonConstMemberCall(body, param) || Utils::containsCallByRef(body, param)) continue; if (!isSmall) { error += warningMsgForSmallType(size_of_T, paramQt.getAsString()); } else if (isNonTrivialCopyable) { error += "Missing reference on non-trivial type " + recordDecl->getQualifiedNameAsString(); } } if (!error.empty()) { emitWarning(param->getLocStart(), error.c_str()); } } } REGISTER_CHECK_WITH_FLAGS("function-args-by-ref", FunctionArgsByRef, CheckLevel2) <commit_msg>coding style<commit_after>/* This file is part of the clang-lazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected] Author: Sérgio Martins <[email protected]> Copyright (C) 2015 Sergio Martins <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "functionargsbyref.h" #include "Utils.h" #include "checkmanager.h" #include <clang/AST/AST.h> using namespace clang; using namespace std; static bool shouldIgnoreClass(const std::string &qualifiedClassName) { static const vector<string> ignoreList = {"QDebug", // Too many warnings "QGenericReturnArgument", "QColor", // TODO: Remove in Qt6 "QStringRef", // TODO: Remove in Qt6 "QList::const_iterator", // TODO: Remove in Qt6 "QJsonArray::const_iterator", // TODO: Remove in Qt6 "QList<QString>::const_iterator", // TODO: Remove in Qt6 "QtMetaTypePrivate::QSequentialIterableImpl", "QtMetaTypePrivate::QAssociativeIterableImpl" }; return std::find(ignoreList.cbegin(), ignoreList.cend(), qualifiedClassName) != ignoreList.cend(); } static bool shouldIgnoreFunction(const std::string &methodName) { // Too many warnings in operator<< static const vector<string> ignoreList = {"operator<<"}; return std::find(ignoreList.cbegin(), ignoreList.cend(), methodName) != ignoreList.cend(); } FunctionArgsByRef::FunctionArgsByRef(const std::string &name) : CheckBase(name) { } std::vector<string> FunctionArgsByRef::filesToIgnore() const { return {"/c++/", "qimage.cpp", // TODO: Uncomment in Qt6 "qimage.h", // TODO: Uncomment in Qt6 "qevent.h", // TODO: Uncomment in Qt6 "avxintrin.h", "avx2intrin.h", "qnoncontiguousbytedevice.cpp", "qlocale_unix.cpp", "/clang/" }; } static std::string warningMsgForSmallType(int sizeOf, const std::string &typeName) { std::string sizeStr = std::to_string(sizeOf); return "Missing reference on large type sizeof " + typeName + " is " + sizeStr + " bytes)"; } void FunctionArgsByRef::VisitDecl(Decl *decl) { FunctionDecl *functionDecl = dyn_cast<FunctionDecl>(decl); if (!functionDecl || !functionDecl->hasBody() || shouldIgnoreFunction(functionDecl->getNameAsString()) || !functionDecl->isThisDeclarationADefinition()) return; Stmt *body = functionDecl->getBody(); for (auto it = functionDecl->param_begin(), end = functionDecl->param_end(); it != end; ++it) { const ParmVarDecl *param = *it; QualType paramQt = param->getType(); const Type *paramType = paramQt.getTypePtrOrNull(); if (!paramType || paramType->isDependentType()) continue; const int size_of_T = m_ci.getASTContext().getTypeSize(paramQt) / 8; const bool isSmall = size_of_T <= 16; // TODO: What about arm ? CXXRecordDecl *recordDecl = paramType->getAsCXXRecordDecl(); const bool isNonTrivialCopyable = recordDecl && (recordDecl->hasNonTrivialCopyConstructor() || recordDecl->hasNonTrivialDestructor()); const bool isReference = paramType->isLValueReferenceType(); const bool isConst = paramQt.isConstQualified(); if (recordDecl && shouldIgnoreClass(recordDecl->getQualifiedNameAsString())) continue; std::string error; if (isConst && !isReference) { if (!isSmall) { error += warningMsgForSmallType(size_of_T, paramQt.getAsString()); } else if (isNonTrivialCopyable) { error += "Missing reference on non-trivial type " + recordDecl->getQualifiedNameAsString(); } } else if (isConst && isReference && !isNonTrivialCopyable && isSmall) { //error += "Don't use by-ref on small trivial type"; } else if (!isConst && !isReference && (!isSmall || isNonTrivialCopyable)) { if (Utils::containsNonConstMemberCall(body, param) || Utils::containsCallByRef(body, param)) continue; if (!isSmall) { error += warningMsgForSmallType(size_of_T, paramQt.getAsString()); } else if (isNonTrivialCopyable) { error += "Missing reference on non-trivial type " + recordDecl->getQualifiedNameAsString(); } } if (!error.empty()) { emitWarning(param->getLocStart(), error.c_str()); } } } REGISTER_CHECK_WITH_FLAGS("function-args-by-ref", FunctionArgsByRef, CheckLevel2) <|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_frame/module_utils.h" #include <atlbase.h> #include "base/logging.h" const wchar_t kBeaconWindowClassName[] = L"ChromeFrameBeaconWindowClass826C5D01-E355-4b23-8AC2-40650E0B7843"; // static ATOM DllRedirector::atom_ = 0; bool DllRedirector::RegisterAsFirstCFModule() { // This would imply that this module had already registered a window class // which should never happen. if (atom_) { NOTREACHED(); return true; } WNDCLASSEX wnd_class = {0}; wnd_class.cbSize = sizeof(WNDCLASSEX); wnd_class.style = CS_GLOBALCLASS; wnd_class.lpfnWndProc = &DefWindowProc; wnd_class.cbClsExtra = sizeof(HMODULE); wnd_class.cbWndExtra = 0; wnd_class.hInstance = NULL; wnd_class.hIcon = NULL; wnd_class.hCursor = LoadCursor(NULL, IDC_ARROW); wnd_class.hbrBackground = NULL; wnd_class.lpszMenuName = NULL; wnd_class.lpszClassName = kBeaconWindowClassName; wnd_class.hIconSm = wnd_class.hIcon; ATOM atom = RegisterClassEx(&wnd_class); bool success = false; if (atom != 0) { HWND hwnd = CreateWindow(MAKEINTATOM(atom), L"temp_window", WS_POPUP, 0, 0, 0, 0, NULL, NULL, NULL, NULL); DCHECK(IsWindow(hwnd)); if (hwnd) { HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase); LONG_PTR lp = reinterpret_cast<LONG_PTR>(this_module); SetClassLongPtr(hwnd, 0, lp); // We need to check the GLE value since SetClassLongPtr returns 0 on // failure as well as on the first call. if (GetLastError() == ERROR_SUCCESS) { atom_ = atom; success = true; } DestroyWindow(hwnd); } } return success; } void DllRedirector::UnregisterAsFirstCFModule() { if (atom_) { UnregisterClass(MAKEINTATOM(atom_), NULL); } } HMODULE DllRedirector::GetFirstCFModule() { WNDCLASSEX wnd_class = {0}; HMODULE oldest_module = NULL; HWND hwnd = CreateWindow(kBeaconWindowClassName, L"temp_window", WS_POPUP, 0, 0, 0, 0, NULL, NULL, NULL, NULL); DCHECK(IsWindow(hwnd)); if (hwnd) { oldest_module = reinterpret_cast<HMODULE>(GetClassLongPtr(hwnd, 0)); DestroyWindow(hwnd); } return oldest_module; } LPFNGETCLASSOBJECT DllRedirector::GetDllGetClassObjectPtr(HMODULE module) { LPFNGETCLASSOBJECT proc_ptr = NULL; HMODULE temp_handle = 0; // Increment the module ref count while we have an pointer to its // DllGetClassObject function. if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCTSTR>(module), &temp_handle)) { proc_ptr = reinterpret_cast<LPFNGETCLASSOBJECT>( GetProcAddress(temp_handle, "DllGetClassObject")); if (!proc_ptr) { FreeLibrary(temp_handle); LOG(ERROR) << "Module Scan: Couldn't get address of " << "DllGetClassObject: " << GetLastError(); } } else { LOG(ERROR) << "Module Scan: Could not increment module count: " << GetLastError(); } return proc_ptr; } <commit_msg>Add a call to SetLastError before calling SetClassLongPtr. It turns out that SetClasSLongPtr doesn't reset the error code on success and yet said code must be used to check for failure.<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_frame/module_utils.h" #include <atlbase.h> #include "base/logging.h" const wchar_t kBeaconWindowClassName[] = L"ChromeFrameBeaconWindowClass826C5D01-E355-4b23-8AC2-40650E0B7843"; // static ATOM DllRedirector::atom_ = 0; bool DllRedirector::RegisterAsFirstCFModule() { // This would imply that this module had already registered a window class // which should never happen. if (atom_) { NOTREACHED(); return true; } WNDCLASSEX wnd_class = {0}; wnd_class.cbSize = sizeof(WNDCLASSEX); wnd_class.style = CS_GLOBALCLASS; wnd_class.lpfnWndProc = &DefWindowProc; wnd_class.cbClsExtra = sizeof(HMODULE); wnd_class.cbWndExtra = 0; wnd_class.hInstance = NULL; wnd_class.hIcon = NULL; wnd_class.hCursor = LoadCursor(NULL, IDC_ARROW); wnd_class.hbrBackground = NULL; wnd_class.lpszMenuName = NULL; wnd_class.lpszClassName = kBeaconWindowClassName; wnd_class.hIconSm = wnd_class.hIcon; ATOM atom = RegisterClassEx(&wnd_class); bool success = false; if (atom != 0) { HWND hwnd = CreateWindow(MAKEINTATOM(atom), L"temp_window", WS_POPUP, 0, 0, 0, 0, NULL, NULL, NULL, NULL); DCHECK(IsWindow(hwnd)); if (hwnd) { HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase); LONG_PTR lp = reinterpret_cast<LONG_PTR>(this_module); // SetClassLongPtr doesn't call this on success, so we do it here first. SetLastError(ERROR_SUCCESS); SetClassLongPtr(hwnd, 0, lp); // We need to check the GLE value since SetClassLongPtr returns 0 on // failure as well as on the first call. if (GetLastError() == ERROR_SUCCESS) { atom_ = atom; success = true; } DestroyWindow(hwnd); } } return success; } void DllRedirector::UnregisterAsFirstCFModule() { if (atom_) { UnregisterClass(MAKEINTATOM(atom_), NULL); } } HMODULE DllRedirector::GetFirstCFModule() { WNDCLASSEX wnd_class = {0}; HMODULE oldest_module = NULL; HWND hwnd = CreateWindow(kBeaconWindowClassName, L"temp_window", WS_POPUP, 0, 0, 0, 0, NULL, NULL, NULL, NULL); DCHECK(IsWindow(hwnd)); if (hwnd) { oldest_module = reinterpret_cast<HMODULE>(GetClassLongPtr(hwnd, 0)); DestroyWindow(hwnd); } return oldest_module; } LPFNGETCLASSOBJECT DllRedirector::GetDllGetClassObjectPtr(HMODULE module) { LPFNGETCLASSOBJECT proc_ptr = NULL; HMODULE temp_handle = 0; // Increment the module ref count while we have an pointer to its // DllGetClassObject function. if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCTSTR>(module), &temp_handle)) { proc_ptr = reinterpret_cast<LPFNGETCLASSOBJECT>( GetProcAddress(temp_handle, "DllGetClassObject")); if (!proc_ptr) { FreeLibrary(temp_handle); LOG(ERROR) << "Module Scan: Couldn't get address of " << "DllGetClassObject: " << GetLastError(); } } else { LOG(ERROR) << "Module Scan: Could not increment module count: " << GetLastError(); } return proc_ptr; } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2016 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* Authors: Hye-Jong KIM */ #ifndef OMKINEMATICS_HPP_ #define OMKINEMATICS_HPP_ #include "../../include/open_manipulator/OMAPI.hpp" #include "../../include/open_manipulator/OMDebug.hpp" #include <Eigen.h> // Calls main Eigen matrix class library #include <Eigen/LU> // Calls inverse, determinant, LU decomp., etc. #include <Eigen/Dense> #include <math.h> #include <vector> using namespace OPEN_MANIPULATOR; class OMKinematicsMethod { public: OMKinematicsMethod(){}; ~OMKinematicsMethod(){}; void solveKinematicsSinglePoint(Manipulator* manipulator, Name component_name, bool* error = false) { Pose parent_pose; Pose link_relative_pose; Eigen::Matrix3f rodrigues_rotation_matrix; Pose result_pose; parent_pose = MANAGER::getComponentPoseToWorld(manipulator, MANAGER::getComponentParentName(manipulator, component_name, error), error); link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, component_name, error); rodrigues_rotation_matrix = MATH::rodriguesRotationMatrix(getComponentJointAxis(manipulator, component_name, error), MANAGER::getComponentJointAngle(manipulator, component_name, error)); result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position; result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation * rodrigues_rotation_matrix; MANAGER::setComponentPoseToWorld(manipulator, component_name, result_pose, error); for(int i = 0; i > MANAGER::getComponentChildName(manipulator, component_name, error).size(); i++) { solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, component_name, error).at(i), error); } } void forward(Manipulator* manipulator, bool* error = false) { Pose pose_to_wolrd; Pose link_relative_pose; Eigen::Matrix3f rodrigues_rotation_matrix; Pose result_pose; //Base Pose Set (from world) parent_pose = MANAGER::getWorldPose(manipulator, error); link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, MANAGER::getWorldChildName(manipulator, error), error); result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position; result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation; MANAGER::setComponentPoseToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), result_pose, error); //Next Component Pose Set for(int i = 0; i > MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).size(); i++) { solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).at(i), error); } } }; class OMChainKinematics { private: public: OMChainKinematics(){}; ~OMChainKinematics(){}; Eigen::MatrixXf jacobian(Manipulator* manipulator, int8_t tool_component_name, bool *error = false) { Eigen::MatrixXf jacobian(6,MANAGER::getDOF(manipulator, error)); Eigen::Vector3f position_changed = Eigen::Vector3f::Zero(); Eigen::Vector3f orientation_changed = Eigen::Vector3f::Zero(); Eigen::VectorXf pose_changed(6); map<Name, Component> temp_component = MANAGER::getAllComponent(manipulator, error); map<Name, Component>::iterator it_component_; int8_t j = 0; for(it_component_ = temp_component.begin(); it_component_ != temp_component.end(); it_component_++) { if(MANAGER::getComponentJointId(it_component_->first, error) >= 0) { position_changed = MATH::skewSymmetricMatrix(getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error)) * (MANAGER::getComponentPositionToWorld(manipulator, tool_component_name, error) - MANAGER::getComponentPositionToWorld(manipulator, it_component_->first, error)); orientation_changed = MANAGER::getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error); pose_changed << position_changed(0), position_changed(1), position_changed(2), orientation_changed(0), orientation_changed(1), orientation_changed(2); jacobian.col(j) = pose_changed; j++; } } return jacobian } }; class OMScaraKinematics { private: public: OMScaraKinematics(){}; ~OMScaraKinematics(){}; }; class OMLinkKinematics { private: public: OMLinkKinematics(){}; ~OMLinkKinematics(){}; void forward(Manipulator* manipulator, bool *error = false) { KINEMATICS::getPassiveJointAngle(manipulator, error) OMKinematicsMethod::forward(manipulator, error); } Eigen::VectorXf numericalInverse(Manipulator* manipulator, int8_t tool_number, Pose target_pose, float gain) { // Eigen::VectorXf target_angle(omlink.getDOF()); // Eigen::MatrixXf jacobian(6,omlink.getDOF()); // Eigen::VectorXf differential_pose(6); // Eigen::VectorXf previous_differential_pose(6); // while(differential_pose.norm() < 1E-6) // { // forward(omlink); // jacobian = method_.jacobian(omlink, tool_number); // differential_pose = math_.differentialPose(target_pose.position, omlink.tool[tool_number].getPosition(), target_pose.orientation, omlink.tool[tool_number].getOrientation()); // Eigen::ColPivHouseholderQR<Eigen::MatrixXf> qrmethod(jacobian); // target_angle = gain * qrmethod.solve(differential_pose); // int8_t k = 0; // for(int8_t j = 0; j < omlink.getJointSize(); j++) // { // if(omlink.joint_[j].getId() >= 0) // { // omlink.joint_[j].setAngle(target_angle(k)); // k++; // } // } // if(differential_pose.norm()>previous_differential_pose.norm()) // { // //ERROR // break; // } // previous_differential_pose = differential_pose; // } // return target_angle; } Eigen::VectorXf geometricInverse(Manipulator* manipulator, Name tool_number, Pose target_pose, float gain) //for basic model { Eigen::VectorXf target_angle_vector(3); Eigen::Vector3f control_position; //joint6-joint1 Eigen::Vector3f tool_relative_position = MANAGER::getComponentRelativePositionToParent(manipulator, tool_number, error); Eigen::Vector3f base_position = MANAGER::getComponentPositionToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), error); Eigen::Vector3f temp_vector; float target_angle[3]; float link[3]; float temp_x; float temp_y; temp_y = target_pose.position(0)-base_position(0); temp_x = target_pose.position(1)-base_position(1); target_angle[0] = atan2(temp_y, temp_x); control_position(0) = target_pose.position(0) - tool_relative_position(0)*cos(target_angle[0]); control_position(1) = target_pose.position(1) - tool_relative_position(0)*sin(target_angle[0]); control_position(2) = target_pose.position(2) - tool_relative_position(2); // temp_vector = omlink.link_[0].getRelativeJointPosition(1,0); temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error), error); link[0] = temp_vector(2); // temp_vector = omlink.link_[1].getRelativeJointPosition(5,1); temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error); link[1] = temp_vector(0); // temp_vector = omlink.link_[4].getRelativeJointPosition(6,5); temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error); link[2] = -temp_vector(0); temp_y = control_position(2)-base_position(2); temp_x = (control_position(0)-base_position(0))*cos(target_angle[0]); target_angle[1] = acos(((temp_x*temp_x+temp_y*temp_y+link[1]*link[1]-link[2]*link[2]))/(2*link[1]*sqrt(temp_x*temp_x+temp_y*temp_y))) + atan2(temp_y, temp_x); target_angle[2] = acos((link[1]*link[1]+link[2]*link[2]-(temp_x*temp_x+temp_y*temp_y))/(2*link[1]*link[2])) + target_angle[1]; target_angle_vector << target_angle[0], target_angle[1], target_angle[2]; return target_angle_vector; } }; class OMDeltaKinematics { private: public: OMDeltaKinematics(){}; ~OMDeltaKinematics(){}; }; class MYKinematics { private: public: MYKinematics(){}; ~MYKinematics(){}; }; #endif // OMKINEMATICS_HPP_ <commit_msg>update geometricInverse for OMLINK<commit_after>/******************************************************************************* * Copyright 2016 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* Authors: Hye-Jong KIM */ #ifndef OMKINEMATICS_HPP_ #define OMKINEMATICS_HPP_ #include "../../include/open_manipulator/OMAPI.hpp" #include "../../include/open_manipulator/OMDebug.hpp" #include <Eigen.h> // Calls main Eigen matrix class library #include <Eigen/LU> // Calls inverse, determinant, LU decomp., etc. #include <Eigen/Dense> #include <math.h> #include <vector> using namespace OPEN_MANIPULATOR; class OMKinematicsMethod { public: OMKinematicsMethod(){}; ~OMKinematicsMethod(){}; void solveKinematicsSinglePoint(Manipulator* manipulator, Name component_name, bool* error = false) { Pose parent_pose; Pose link_relative_pose; Eigen::Matrix3f rodrigues_rotation_matrix; Pose result_pose; parent_pose = MANAGER::getComponentPoseToWorld(manipulator, MANAGER::getComponentParentName(manipulator, component_name, error), error); link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, component_name, error); rodrigues_rotation_matrix = MATH::rodriguesRotationMatrix(getComponentJointAxis(manipulator, component_name, error), MANAGER::getComponentJointAngle(manipulator, component_name, error)); result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position; result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation * rodrigues_rotation_matrix; MANAGER::setComponentPoseToWorld(manipulator, component_name, result_pose, error); for(int i = 0; i > MANAGER::getComponentChildName(manipulator, component_name, error).size(); i++) { solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, component_name, error).at(i), error); } } void forward(Manipulator* manipulator, bool* error = false) { Pose pose_to_wolrd; Pose link_relative_pose; Eigen::Matrix3f rodrigues_rotation_matrix; Pose result_pose; //Base Pose Set (from world) parent_pose = MANAGER::getWorldPose(manipulator, error); link_relative_pose = MANAGER::getComponentRelativePoseToParent(manipulator, MANAGER::getWorldChildName(manipulator, error), error); result_pose.poosition = parent_pose.position + parent_pose.orientation * link_relative_pose.relative_position; result_pose.orientation = parent_pose.orientation * link_relative_pose.relative_orientation; MANAGER::setComponentPoseToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), result_pose, error); //Next Component Pose Set for(int i = 0; i > MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).size(); i++) { solveKinematicsSinglePoint(manipulator, MANAGER::getComponentChildName(manipulator, MANAGER::getWorldChildName(manipulator, error), error).at(i), error); } } }; class OMChainKinematics { private: public: OMChainKinematics(){}; ~OMChainKinematics(){}; Eigen::MatrixXf jacobian(Manipulator* manipulator, int8_t tool_component_name, bool *error = false) { Eigen::MatrixXf jacobian(6,MANAGER::getDOF(manipulator, error)); Eigen::Vector3f position_changed = Eigen::Vector3f::Zero(); Eigen::Vector3f orientation_changed = Eigen::Vector3f::Zero(); Eigen::VectorXf pose_changed(6); map<Name, Component> temp_component = MANAGER::getAllComponent(manipulator, error); map<Name, Component>::iterator it_component_; int8_t j = 0; for(it_component_ = temp_component.begin(); it_component_ != temp_component.end(); it_component_++) { if(MANAGER::getComponentJointId(it_component_->first, error) >= 0) { position_changed = MATH::skewSymmetricMatrix(getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error)) * (MANAGER::getComponentPositionToWorld(manipulator, tool_component_name, error) - MANAGER::getComponentPositionToWorld(manipulator, it_component_->first, error)); orientation_changed = MANAGER::getComponentOrientationToWorld(manipulator, it_component_->first, error)*MANAGER::getComponentJointAxis(manipulator, it_component_->first, error); pose_changed << position_changed(0), position_changed(1), position_changed(2), orientation_changed(0), orientation_changed(1), orientation_changed(2); jacobian.col(j) = pose_changed; j++; } } return jacobian } }; class OMScaraKinematics { private: public: OMScaraKinematics(){}; ~OMScaraKinematics(){}; }; class OMLinkKinematics { private: public: OMLinkKinematics(){}; ~OMLinkKinematics(){}; void forward(Manipulator* manipulator, bool *error = false) { KINEMATICS::getPassiveJointAngle(manipulator, error) OMKinematicsMethod::forward(manipulator, error); } Eigen::VectorXf numericalInverse(Manipulator* manipulator, int8_t tool_number, Pose target_pose, float gain) { // Eigen::VectorXf target_angle(omlink.getDOF()); // Eigen::MatrixXf jacobian(6,omlink.getDOF()); // Eigen::VectorXf differential_pose(6); // Eigen::VectorXf previous_differential_pose(6); // while(differential_pose.norm() < 1E-6) // { // forward(omlink); // jacobian = method_.jacobian(omlink, tool_number); // differential_pose = math_.differentialPose(target_pose.position, omlink.tool[tool_number].getPosition(), target_pose.orientation, omlink.tool[tool_number].getOrientation()); // Eigen::ColPivHouseholderQR<Eigen::MatrixXf> qrmethod(jacobian); // target_angle = gain * qrmethod.solve(differential_pose); // int8_t k = 0; // for(int8_t j = 0; j < omlink.getJointSize(); j++) // { // if(omlink.joint_[j].getId() >= 0) // { // omlink.joint_[j].setAngle(target_angle(k)); // k++; // } // } // if(differential_pose.norm()>previous_differential_pose.norm()) // { // //ERROR // break; // } // previous_differential_pose = differential_pose; // } // return target_angle; } Eigen::VectorXf geometricInverse(Manipulator* manipulator, Name tool_number, Pose target_pose, float gain) //for basic model { Eigen::VectorXf target_angle_vector(3); Eigen::Vector3f control_position; //joint6-joint1 Eigen::Vector3f tool_relative_position = MANAGER::getComponentRelativePositionToParent(manipulator, tool_number, error); Eigen::Vector3f base_position = MANAGER::getComponentPositionToWorld(manipulator, MANAGER::getWorldChildName(manipulator, error), error); Eigen::Vector3f temp_vector; float target_angle[3]; float link[3]; float temp_x; float temp_y; temp_y = target_pose.position(0)-base_position(0); temp_x = target_pose.position(1)-base_position(1); target_angle[0] = atan2(temp_y, temp_x); control_position(0) = target_pose.position(0) - tool_relative_position(0)*cos(target_angle[0]); control_position(1) = target_pose.position(1) - tool_relative_position(0)*sin(target_angle[0]); control_position(2) = target_pose.position(2) - tool_relative_position(2); // temp_vector = omlink.link_[0].getRelativeJointPosition(1,0); temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error), error); link[0] = temp_vector(2); // temp_vector = omlink.link_[1].getRelativeJointPosition(5,1); temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error), error); link[1] = temp_vector(0); // temp_vector = omlink.link_[4].getRelativeJointPosition(6,5); temp_vector = MANAGER::getComponentRelativePositionToParent(manipulator, MANAGER::getComponentParentName(manipulator, tool_number, error), error); link[2] = -temp_vector(0); temp_y = control_position(2)-base_position(2); temp_x = (control_position(0)-base_position(0))*cos(target_angle[0]); target_angle[1] = acos(((temp_x*temp_x+temp_y*temp_y+link[1]*link[1]-link[2]*link[2]))/(2*link[1]*sqrt(temp_x*temp_x+temp_y*temp_y))) + atan2(temp_y, temp_x); target_angle[2] = acos((link[1]*link[1]+link[2]*link[2]-(temp_x*temp_x+temp_y*temp_y))/(2*link[1]*link[2])) + target_angle[1]; target_angle_vector << target_angle[0], target_angle[1], target_angle[2]; return target_angle_vector; } }; class OMDeltaKinematics { private: public: OMDeltaKinematics(){}; ~OMDeltaKinematics(){}; }; class MYKinematics { private: public: MYKinematics(){}; ~MYKinematics(){}; }; #endif // OMKINEMATICS_HPP_ <|endoftext|>
<commit_before>#include "NotifyingTextView.h" /* * Copyright 2003-2009, IM Kit Team. * Distributed under the terms of the MIT License. * * Authors: * Michael Davidson <[email protected]> */ #include <app/Messenger.h> //#pragma mark Constructor NotifyingTextView::NotifyingTextView(BRect frame, const char *name, BRect textRect, uint32 resizingMode, uint32 flags) : BTextView(frame, name, textRect, resizingMode, flags), fMessenger(NULL) { }; NotifyingTextView::~NotifyingTextView(void) { if (fMessenger != NULL) delete fMessenger; }; //#pragma mark Public void NotifyingTextView::SetHandler(BHandler *handler) { if (fMessenger != NULL) delete fMessenger; fMessenger = new BMessenger(handler); }; BMessage NotifyingTextView::NotificationMessage(void) const { return fMessage; }; void NotifyingTextView::SetNotificationMessage(BMessage msg) { fMessage = msg; } //#pragma mark BTextView Hooks void NotifyingTextView::InsertText(const char *text, int32 length, int32 offset, const text_run_array *runs = NULL) { if ((fMessenger != NULL) && (fMessenger->IsValid() == true)) { BMessage msg(fMessage); msg.AddPointer("source", this); fMessenger->SendMessage(&msg); }; }; void NotifyingTextView::DeleteText(int32 start, int32 finish) { if ((fMessenger != NULL) && (fMessenger->IsValid() == true)) { BMessage msg(fMessage); msg.AddPointer("source", this); fMessenger->SendMessage(&msg); }; }; <commit_msg>Common: Fixed the NotifyingTextView - I was not calling the base methods for InsertText and DeleteText. This will not fix the issue on Haiku though<commit_after>#include "NotifyingTextView.h" /* * Copyright 2003-2009, IM Kit Team. * Distributed under the terms of the MIT License. * * Authors: * Michael Davidson <[email protected]> */ #include <app/Messenger.h> //#pragma mark Constructor NotifyingTextView::NotifyingTextView(BRect frame, const char *name, BRect textRect, uint32 resizingMode, uint32 flags) : BTextView(frame, name, textRect, resizingMode, flags), fMessenger(NULL) { }; NotifyingTextView::~NotifyingTextView(void) { if (fMessenger != NULL) delete fMessenger; }; //#pragma mark Public void NotifyingTextView::SetHandler(BHandler *handler) { if (fMessenger != NULL) delete fMessenger; fMessenger = new BMessenger(handler); }; BMessage NotifyingTextView::NotificationMessage(void) const { return fMessage; }; void NotifyingTextView::SetNotificationMessage(BMessage msg) { fMessage = msg; } //#pragma mark BTextView Hooks void NotifyingTextView::InsertText(const char *text, int32 length, int32 offset, const text_run_array *runs = NULL) { if ((fMessenger != NULL) && (fMessenger->IsValid() == true)) { BMessage msg(fMessage); msg.AddPointer("source", this); fMessenger->SendMessage(&msg); }; BTextView::InsertText(text, length, offset, runs); }; void NotifyingTextView::DeleteText(int32 start, int32 finish) { if ((fMessenger != NULL) && (fMessenger->IsValid() == true)) { BMessage msg(fMessage); msg.AddPointer("source", this); fMessenger->SendMessage(&msg); }; BTextView::DeleteText(start, finish); }; <|endoftext|>
<commit_before>/*=========================================================================*/ /* */ /* @file Optimizer.cpp */ /* @author Chirantan Ekbote ([email protected]) */ /* @date 2012/11/14 */ /* @version 0.2 */ /* @brief Optimizer for generating bright and dark images */ /* */ /*=========================================================================*/ #include "../inc/Optimizer.h" #define ROW(n) 1*n, 2*n, 3*n, 4*n, 3*n, 2*n, 1*n namespace pvrtex { // Optimization window information const int Optimizer::window_width_ = 11; const int Optimizer::window_height_ = 11; const int Optimizer::matrix_rows_ = 121; const int Optimizer::matrix_cols_ = 8; const int Optimizer::offset_x_ = 4; const int Optimizer::offset_y_ = 4; // Weight matrices const float Optimizer::kTopLeft[] = { ROW(0.0625f), 0, 0, 0, 0, // 1/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.25f), 0, 0, 0, 0, // 4/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.0625f), 0, 0, 0, 0, // 1/16 ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0 }; const float Optimizer::kTopRight[] = { 0, 0, 0, 0, ROW(0.0625f), // 1/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.25f), // 4/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.0625f), // 1/16 ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0 }; const float Optimizer::kBottomLeft[] = { ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0.0625f), 0, 0, 0, 0, // 1/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.25f), 0, 0, 0, 0, // 4/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.0625f), 0, 0, 0, 0, // 1/16 }; const float Optimizer::kBottomRight[] = { ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, 0, 0, 0, 0, ROW(0.0625f), // 1/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.25f), // 4/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.0625f) // 1/16 }; Optimizer::Optimizer(const Eigen::MatrixXi &o, Eigen::MatrixXi &d, Eigen::MatrixXi &b) : dark_(d), bright_(b), orig_(o), solv_(SVD) { red_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); green_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); blue_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); } Optimizer::Optimizer(const Eigen::MatrixXi &o, Eigen::MatrixXi &d, Eigen::MatrixXi &b, SOLVER s): dark_(d), bright_(b), orig_(o), solv_(s) { red_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); green_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); blue_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); } Optimizer::~Optimizer() { } void Optimizer::ComputeUpdateVector() { Eigen::Vector3i diff; Eigen::MatrixXi comp = util::ModulateImage(util::Upscale4x4(dark_), util::Upscale4x4(bright_), mod_); #pragma omp parallel for for (int y = 0; y < orig_.rows(); ++y) { for (int x = 0; x < orig_.cols(); ++x) { diff = (util::MakeColorVector(orig_(y,x)) - util::MakeColorVector(comp(y,x))); // red(y,x) = util::MakeRed(orig(y,x)); // green(y,x) = util::MakeGreen(orig(y,x)); // blue(y,x) = util::MakeBlue(orig(y,x)); red_(y,x) = diff(0); green_(y,x) = diff(1); blue_(y,x) = diff(2); } } } void Optimizer::OptimizeWindow(int j, int i) { Eigen::MatrixXf a(matrix_rows_, matrix_cols_); Eigen::VectorXf red(matrix_rows_); Eigen::VectorXf green(matrix_rows_); Eigen::VectorXf blue(matrix_rows_); int idx, pixel_x, pixel_y; float m, distance; float r, g, b; /* Construct the optimization window */ for (int y = 0; y < window_height_; ++y) { for (int x = 0; x < window_width_; ++x) { /* Get the position of the pixel we want to fetch */ idx = y*window_width_ + x; pixel_x = util::Clamp(offset_x_*i-1 + x, 0, mod_.cols()-1); pixel_y = util::Clamp(offset_y_*j-1 + y, 0, mod_.rows()-1); /* Fetch the modulation value and the original color*/ m = mod_(pixel_y, pixel_x); r = static_cast<float>(red_(pixel_y, pixel_x)); g = static_cast<float>(green_(pixel_y, pixel_x)); b = static_cast<float>(blue_(pixel_y, pixel_x)); /* Fetch the distance weights and construct the matrix */ distance = kTopLeft[idx]; a(idx, 0) = distance * (1.0f - m); a(idx, 1) = distance * m; red(idx) = distance * r; green(idx) = distance * g; blue(idx) = distance * b; /* Top right pxel */ distance = kTopRight[idx]; a(idx, 2) = distance * (1.0f - m); a(idx, 3) = distance * m; red(idx) += distance * r; green(idx) += distance * g; blue(idx) += distance * b; /* Bottom left pixel */ distance = kBottomLeft[idx]; a(idx, 4) = distance * (1.0f - m); a(idx, 5) = distance * m; red(idx) += distance * r; green(idx) += distance * g; blue(idx) += distance * b; /* Bottom right pixel */ distance = kBottomRight[idx]; a(idx, 6) = distance * (1.0f - m); a(idx, 7) = distance * m; red(idx) += distance * r; green(idx) += distance * g; blue(idx) += distance * b; } } /* Solve for the best colors */ Eigen::JacobiSVD<Eigen::MatrixXf> svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV); Eigen::VectorXi optimal_red = svd.solve(red).cast<int>(); Eigen::VectorXi optimal_green = svd.solve(green).cast<int>(); Eigen::VectorXi optimal_blue = svd.solve(blue).cast<int>(); /* Update the dark and bright images */ for (int x = 0; x < 2; ++x) { for (int y = 0; y < 2; ++y) { idx = 4*y + 2*x; dark_(j+y, i+x) = util::Make565RGB( util::Make565ColorVector(dark_(j+y, i+x)) + Eigen::Vector3i( util::Clamp(optimal_red(idx), -32, 32), util::Clamp(optimal_green(idx), -32, 32), util::Clamp(optimal_blue(idx), -32, 32))); bright_(j+y, i+x) = util::Make565RGB( util::Make565ColorVector(bright_(j+y, i+x)) + Eigen::Vector3i( util::Clamp(optimal_red(idx+1), -32, 32), util::Clamp(optimal_green(idx+1), -32, 32), util::Clamp(optimal_blue(idx+1), -32, 32))); } } } void Optimizer::Optimize(const Eigen::MatrixXf &m) { mod_ = m; ComputeUpdateVector(); //#pragma omp parallel for for (int j = 0; j < dark_.rows(); j+=2) { for (int i = 0; i < dark_.cols(); i+=2) { OptimizeWindow(j, i); } } } }<commit_msg>Added code to compare basic vs error-fixing optimization<commit_after>/*=========================================================================*/ /* */ /* @file Optimizer.cpp */ /* @author Chirantan Ekbote ([email protected]) */ /* @date 2012/11/14 */ /* @version 0.2 */ /* @brief Optimizer for generating bright and dark images */ /* */ /*=========================================================================*/ #include "../inc/Optimizer.h" #define ROW(n) 1*n, 2*n, 3*n, 4*n, 3*n, 2*n, 1*n namespace pvrtex { // Optimization window information const int Optimizer::window_width_ = 11; const int Optimizer::window_height_ = 11; const int Optimizer::matrix_rows_ = 121; const int Optimizer::matrix_cols_ = 8; const int Optimizer::offset_x_ = 4; const int Optimizer::offset_y_ = 4; // Weight matrices const float Optimizer::kTopLeft[] = { ROW(0.0625f), 0, 0, 0, 0, // 1/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.25f), 0, 0, 0, 0, // 4/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.0625f), 0, 0, 0, 0, // 1/16 ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0 }; const float Optimizer::kTopRight[] = { 0, 0, 0, 0, ROW(0.0625f), // 1/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.25f), // 4/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.0625f), // 1/16 ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0 }; const float Optimizer::kBottomLeft[] = { ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0.0625f), 0, 0, 0, 0, // 1/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.25f), 0, 0, 0, 0, // 4/16 ROW(0.1875f), 0, 0, 0, 0, // 3/16 ROW(0.125f), 0, 0, 0, 0, // 2/16 ROW(0.0625f), 0, 0, 0, 0, // 1/16 }; const float Optimizer::kBottomRight[] = { ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, ROW(0), 0, 0, 0, 0, 0, 0, 0, 0, ROW(0.0625f), // 1/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.25f), // 4/16 0, 0, 0, 0, ROW(0.1875f), // 3/16 0, 0, 0, 0, ROW(0.125f), // 2/16 0, 0, 0, 0, ROW(0.0625f) // 1/16 }; Optimizer::Optimizer(const Eigen::MatrixXi &o, Eigen::MatrixXi &d, Eigen::MatrixXi &b) : dark_(d), bright_(b), orig_(o), solv_(SVD) { red_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); green_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); blue_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); } Optimizer::Optimizer(const Eigen::MatrixXi &o, Eigen::MatrixXi &d, Eigen::MatrixXi &b, SOLVER s): dark_(d), bright_(b), orig_(o), solv_(s) { red_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); green_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); blue_ = Eigen::MatrixXi(orig_.rows(), orig_.cols()); } Optimizer::~Optimizer() { } void Optimizer::ComputeUpdateVector() { Eigen::Vector3i diff; Eigen::MatrixXi comp = util::ModulateImage(util::Upscale4x4(dark_), util::Upscale4x4(bright_), mod_); #pragma omp parallel for for (int y = 0; y < orig_.rows(); ++y) { for (int x = 0; x < orig_.cols(); ++x) { diff = (util::MakeColorVector(orig_(y,x)) - util::MakeColorVector(comp(y,x))); // red_(y,x) = util::MakeRed(orig_(y,x)); // green_(y,x) = util::MakeGreen(orig_(y,x)); // blue_(y,x) = util::MakeBlue(orig_(y,x)); red_(y,x) = diff(0); green_(y,x) = diff(1); blue_(y,x) = diff(2); } } } void Optimizer::OptimizeWindow(int j, int i) { Eigen::MatrixXf a(matrix_rows_, matrix_cols_); Eigen::VectorXf red(matrix_rows_); Eigen::VectorXf green(matrix_rows_); Eigen::VectorXf blue(matrix_rows_); int idx, pixel_x, pixel_y; float m, distance; float r, g, b; /* Construct the optimization window */ for (int y = 0; y < window_height_; ++y) { for (int x = 0; x < window_width_; ++x) { /* Get the position of the pixel we want to fetch */ idx = y*window_width_ + x; pixel_x = util::Clamp(offset_x_*i-1 + x, 0, mod_.cols()-1); pixel_y = util::Clamp(offset_y_*j-1 + y, 0, mod_.rows()-1); /* Fetch the modulation value and the original color*/ m = mod_(pixel_y, pixel_x); r = static_cast<float>(red_(pixel_y, pixel_x)); g = static_cast<float>(green_(pixel_y, pixel_x)); b = static_cast<float>(blue_(pixel_y, pixel_x)); /* Fetch the distance weights and construct the matrix */ distance = kTopLeft[idx]; a(idx, 0) = distance * (1.0f - m); a(idx, 1) = distance * m; red(idx) = distance * r; green(idx) = distance * g; blue(idx) = distance * b; /* Top right pxel */ distance = kTopRight[idx]; a(idx, 2) = distance * (1.0f - m); a(idx, 3) = distance * m; red(idx) += distance * r; green(idx) += distance * g; blue(idx) += distance * b; /* Bottom left pixel */ distance = kBottomLeft[idx]; a(idx, 4) = distance * (1.0f - m); a(idx, 5) = distance * m; red(idx) += distance * r; green(idx) += distance * g; blue(idx) += distance * b; /* Bottom right pixel */ distance = kBottomRight[idx]; a(idx, 6) = distance * (1.0f - m); a(idx, 7) = distance * m; red(idx) += distance * r; green(idx) += distance * g; blue(idx) += distance * b; } } /* Solve for the best colors */ Eigen::JacobiSVD<Eigen::MatrixXf> svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV); Eigen::VectorXi optimal_red = svd.solve(red).cast<int>(); Eigen::VectorXi optimal_green = svd.solve(green).cast<int>(); Eigen::VectorXi optimal_blue = svd.solve(blue).cast<int>(); /* Update the dark and bright images */ for (int x = 0; x < 2; ++x) { for (int y = 0; y < 2; ++y) { idx = 4*y + 2*x; dark_(j+y, i+x) = util::Make565RGB( util::Make565ColorVector(dark_(j+y, i+x)) + Eigen::Vector3i( util::Clamp(optimal_red(idx), -32, 32), util::Clamp(optimal_green(idx), -32, 32), util::Clamp(optimal_blue(idx), -32, 32))); bright_(j+y, i+x) = util::Make565RGB( util::Make565ColorVector(bright_(j+y, i+x)) + Eigen::Vector3i( util::Clamp(optimal_red(idx+1), -32, 32), util::Clamp(optimal_green(idx+1), -32, 32), util::Clamp(optimal_blue(idx+1), -32, 32))); // dark_(j+y, i+x) = util::Make565RGB(Eigen::Vector3i(optimal_red(idx), // optimal_green(idx), // optimal_blue(idx))); // bright_(j+y, i+x) = util::Make565RGB(Eigen::Vector3i(optimal_red(idx+1), // optimal_green(idx+1), // optimal_blue(idx+1))); } } } void Optimizer::Optimize(const Eigen::MatrixXf &m) { mod_ = m; ComputeUpdateVector(); #pragma omp parallel for for (int j = 0; j < dark_.rows(); j+=2) { for (int i = 0; i < dark_.cols(); i+=2) { OptimizeWindow(j, i); } } } }<|endoftext|>
<commit_before>#include "settingswindow.h" SettingsWindow::SettingsWindow(QWidget *parent) : QDialog(parent) { this->setWindowFlags(Qt::Dialog | Qt::WindowSystemMenuHint); this->setWindowTitle(QString::fromUtf8("Параметры")); tabbedWidget = new QTabWidget; tabbedWidget->setUsesScrollButtons(false); mainLayout = new QVBoxLayout(this); mainLayout->addWidget(tabbedWidget); buttonsLayout = new QHBoxLayout; mainLayout->addLayout(buttonsLayout); mainLayout->setStretch(0,1); mainLayout->setStretch(1,0); okButton = new QPushButton(QString::fromUtf8("ОК")); cancelButton = new QPushButton(QString::fromUtf8("Отмена")); buttonsLayout->addStretch(1); buttonsLayout->addWidget(okButton); buttonsLayout->addWidget(cancelButton); forumsScreen = new QWidget; loginScreen = new QWidget; proxyScreen = new QWidget; tabbedWidget->addTab(forumsScreen, QString::fromUtf8("Разделы")); tabbedWidget->addTab(loginScreen, QString::fromUtf8("Аккаунт")); tabbedWidget->addTab(proxyScreen, QString::fromUtf8("Прокси")); forumsLayout = new QHBoxLayout(forumsScreen); moviesGroup = new QGroupBox(QString::fromUtf8("Художественные")); cartoonsGroup = new QGroupBox(QString::fromUtf8("Мультфильмы")); documentaryGroup = new QGroupBox(QString::fromUtf8("Документальные")); moviesLayout = new QVBoxLayout(moviesGroup); cartoonsLayout = new QVBoxLayout(cartoonsGroup); documentaryLayout = new QVBoxLayout(documentaryGroup); latestMoviesCheck = new QCheckBox(QString::fromUtf8("Новейшие фильмы (2011 - 2015)")); newMoviesCheck = new QCheckBox(QString::fromUtf8("Зарубежные фильмы (до 2010)")); oldMoviesCheck = new QCheckBox(QString::fromUtf8("Классика зарубежного кино")); artHouseCheck = new QCheckBox(QString::fromUtf8("Арт-хаус и авторское кино")); asianCheck = new QCheckBox(QString::fromUtf8("Азиатские фильмы")); grindhouseCheck = new QCheckBox(QString::fromUtf8("Грайндхаус")); russianCheck = new QCheckBox(QString::fromUtf8("Наше кино")); ussrCheck = new QCheckBox(QString::fromUtf8("Кино СССР")); tvSeriesCheck = new QCheckBox(QString::fromUtf8("Зарубежные сериалы")); tvSeriesRussianCheck = new QCheckBox(QString::fromUtf8("Русские сериалы")); moviesLayout->addWidget(latestMoviesCheck); moviesLayout->addWidget(newMoviesCheck); moviesLayout->addWidget(oldMoviesCheck); moviesLayout->addWidget(artHouseCheck); moviesLayout->addWidget(asianCheck); moviesLayout->addWidget(grindhouseCheck); moviesLayout->addWidget(russianCheck); moviesLayout->addWidget(ussrCheck); moviesLayout->addWidget(tvSeriesCheck); moviesLayout->addWidget(tvSeriesRussianCheck); moviesLayout->addStretch(1); animeCheck = new QCheckBox(QString::fromUtf8("Аниме (основной и HD разделы)")); cartoonsCheck = new QCheckBox(QString::fromUtf8("Иностранные мультфильмы")); cartoonSeriesCheck = new QCheckBox(QString::fromUtf8("Мультсериалы")); russianCartoonsCheck = new QCheckBox(QString::fromUtf8("Отечественные мультфильмы")); cartoonsLayout->addWidget(animeCheck); cartoonsLayout->addWidget(cartoonsCheck); cartoonsLayout->addWidget(cartoonSeriesCheck); cartoonsLayout->addWidget(russianCartoonsCheck); cartoonsLayout->addStretch(1); criminalCheck = new QCheckBox(QString::fromUtf8("Криминальная документалистика")); bbcCheck = new QCheckBox(QString::fromUtf8("BBC")); discoveryCheck = new QCheckBox(QString::fromUtf8("Discovery")); ngCheck = new QCheckBox(QString::fromUtf8("National Geographic")); documentaryLayout->addWidget(criminalCheck); documentaryLayout->addWidget(bbcCheck); documentaryLayout->addWidget(discoveryCheck); documentaryLayout->addWidget(ngCheck); documentaryLayout->addStretch(1); forumsLayout->addWidget(moviesGroup); forumsLayout->addWidget(cartoonsGroup); forumsLayout->addWidget(documentaryGroup); moviesGroup->setMinimumWidth(300); cartoonsGroup->setMinimumWidth(300); documentaryGroup->setMinimumWidth(300); loginLayout = new QFormLayout(loginScreen); loginEdit = new QLineEdit; passwordEdit = new QLineEdit; passwordEdit->setEchoMode(QLineEdit::PasswordEchoOnEdit); loginLayout->addRow(QString::fromUtf8("Пользователь"), loginEdit); loginLayout->addRow(QString::fromUtf8("Пароль"), passwordEdit); proxyLayout = new QFormLayout(proxyScreen); proxyCheck = new QCheckBox; proxyUrlEdit = new QLineEdit; proxyPortBox = new QSpinBox; proxyPortBox->setMaximum(65535); proxyTypeBox = new QComboBox; proxyTypeBox->addItem("SOCKS 5"); proxyTypeBox->addItem("HTTP"); proxyLoginEdit = new QLineEdit; proxyPasswordEdit = new QLineEdit; proxyPasswordEdit->setEchoMode(QLineEdit::PasswordEchoOnEdit); proxyLayout->addRow(QString::fromUtf8("Прокси для обхода блокировки:"), proxyCheck); proxyLayout->addRow(QString::fromUtf8("Адрес"), proxyUrlEdit); proxyLayout->addRow(QString::fromUtf8("Порт"), proxyPortBox); proxyLayout->addRow(QString::fromUtf8("Тип"), proxyTypeBox); proxyLayout->addRow(QString::fromUtf8("Логин"), proxyLoginEdit); proxyLayout->addRow(QString::fromUtf8("Пароль"), proxyPasswordEdit); connect(proxyCheck, SIGNAL(stateChanged(int)), this, SLOT(toggleProxy(int))); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(okButton, SIGNAL(clicked()), this, SLOT(saveSettings())); settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "MIB", "rutracker-news"); } void SettingsWindow::toggleProxy(int state) { if (state) { proxyUrlEdit->setEnabled(true); proxyPortBox->setEnabled(true); proxyTypeBox->setEnabled(true); proxyLoginEdit->setEnabled(true); proxyPasswordEdit->setEnabled(true); } else { proxyUrlEdit->setEnabled(false); proxyPortBox->setEnabled(false); proxyTypeBox->setEnabled(false); proxyLoginEdit->setEnabled(false); proxyPasswordEdit->setEnabled(false); } } void SettingsWindow::showEvent(QShowEvent *event) { /* read settings */ loginEdit->setText(settings->value("login").toString()); passwordEdit->setText(settings->value("password").toString()); proxyCheck->setChecked(settings->value("use-proxy").toBool()); proxyUrlEdit->setText(settings->value("proxy-url").toString()); proxyPortBox->setValue(settings->value("proxy-port").toInt()); proxyTypeBox->setCurrentIndex(proxyTypeBox->findText(settings->value("proxy-type").toString())); proxyLoginEdit->setText(settings->value("proxy-login").toString()); proxyPasswordEdit->setText(settings->value("proxy-password").toString()); toggleProxy(proxyCheck->checkState()); latestMoviesCheck->setChecked(settings->value("latest-movies").toBool()); newMoviesCheck->setChecked(settings->value("new-movies").toBool()); oldMoviesCheck->setChecked(settings->value("old-movies").toBool()); artHouseCheck->setChecked(settings->value("art-house").toBool()); asianCheck->setChecked(settings->value("asian").toBool()); grindhouseCheck->setChecked(settings->value("grindhouse").toBool()); russianCheck->setChecked(settings->value("russian").toBool()); ussrCheck->setChecked(settings->value("ussr").toBool()); tvSeriesCheck->setChecked(settings->value("tv-series").toBool()); tvSeriesRussianCheck->setChecked(settings->value("tv-series-russian").toBool()); animeCheck->setChecked(settings->value("anime").toBool()); cartoonsCheck->setChecked(settings->value("cartoons").toBool()); cartoonSeriesCheck->setChecked(settings->value("cartoon-series").toBool()); russianCartoonsCheck->setChecked(settings->value("russian-cartoons").toBool()); criminalCheck->setChecked(settings->value("criminal").toBool()); bbcCheck->setChecked(settings->value("bbc").toBool()); discoveryCheck->setChecked(settings->value("discovery").toBool()); ngCheck->setChecked(settings->value("ng").toBool()); } void SettingsWindow::saveSettings() { settings->setValue("login", loginEdit->text()); settings->setValue("password", passwordEdit->text()); settings->setValue("use-proxy", proxyCheck->isChecked()); settings->setValue("proxy-url", proxyUrlEdit->text()); settings->setValue("proxy-port", proxyPortBox->value()); settings->setValue("proxy-type", proxyTypeBox->currentText()); settings->setValue("proxy-login", proxyLoginEdit->text()); settings->setValue("proxy-password", proxyPasswordEdit->text()); settings->setValue("latest-movies", latestMoviesCheck->isChecked()); settings->setValue("new-movies", newMoviesCheck->isChecked()); settings->setValue("old-movies", oldMoviesCheck->isChecked()); settings->setValue("art-house", artHouseCheck->isChecked()); settings->setValue("asian", asianCheck->isChecked()); settings->setValue("grindhouse", grindhouseCheck->isChecked()); settings->setValue("russian", russianCheck->isChecked()); settings->setValue("ussr", ussrCheck->isChecked()); settings->setValue("tv-series", tvSeriesCheck->isChecked()); settings->setValue("tv-series-russian", tvSeriesRussianCheck->isChecked()); settings->setValue("anime", animeCheck->isChecked()); settings->setValue("cartoons", cartoonsCheck->isChecked()); settings->setValue("cartoon-series", cartoonSeriesCheck->isChecked()); settings->setValue("russian-cartoons", russianCartoonsCheck->isChecked()); settings->setValue("criminal", criminalCheck->isChecked()); settings->setValue("bbc", bbcCheck->isChecked()); settings->setValue("discovery", discoveryCheck->isChecked()); settings->setValue("ng", ngCheck->isChecked()); settings->sync(); accept(); } SettingsWindow::~SettingsWindow() { delete settings; } <commit_msg>Set latest movies year to 2016<commit_after>#include "settingswindow.h" SettingsWindow::SettingsWindow(QWidget *parent) : QDialog(parent) { this->setWindowFlags(Qt::Dialog | Qt::WindowSystemMenuHint); this->setWindowTitle(QString::fromUtf8("Параметры")); tabbedWidget = new QTabWidget; tabbedWidget->setUsesScrollButtons(false); mainLayout = new QVBoxLayout(this); mainLayout->addWidget(tabbedWidget); buttonsLayout = new QHBoxLayout; mainLayout->addLayout(buttonsLayout); mainLayout->setStretch(0,1); mainLayout->setStretch(1,0); okButton = new QPushButton(QString::fromUtf8("ОК")); cancelButton = new QPushButton(QString::fromUtf8("Отмена")); buttonsLayout->addStretch(1); buttonsLayout->addWidget(okButton); buttonsLayout->addWidget(cancelButton); forumsScreen = new QWidget; loginScreen = new QWidget; proxyScreen = new QWidget; tabbedWidget->addTab(forumsScreen, QString::fromUtf8("Разделы")); tabbedWidget->addTab(loginScreen, QString::fromUtf8("Аккаунт")); tabbedWidget->addTab(proxyScreen, QString::fromUtf8("Прокси")); forumsLayout = new QHBoxLayout(forumsScreen); moviesGroup = new QGroupBox(QString::fromUtf8("Художественные")); cartoonsGroup = new QGroupBox(QString::fromUtf8("Мультфильмы")); documentaryGroup = new QGroupBox(QString::fromUtf8("Документальные")); moviesLayout = new QVBoxLayout(moviesGroup); cartoonsLayout = new QVBoxLayout(cartoonsGroup); documentaryLayout = new QVBoxLayout(documentaryGroup); latestMoviesCheck = new QCheckBox(QString::fromUtf8("Новейшие фильмы (2011 - 2016)")); newMoviesCheck = new QCheckBox(QString::fromUtf8("Зарубежные фильмы (до 2010)")); oldMoviesCheck = new QCheckBox(QString::fromUtf8("Классика зарубежного кино")); artHouseCheck = new QCheckBox(QString::fromUtf8("Арт-хаус и авторское кино")); asianCheck = new QCheckBox(QString::fromUtf8("Азиатские фильмы")); grindhouseCheck = new QCheckBox(QString::fromUtf8("Грайндхаус")); russianCheck = new QCheckBox(QString::fromUtf8("Наше кино")); ussrCheck = new QCheckBox(QString::fromUtf8("Кино СССР")); tvSeriesCheck = new QCheckBox(QString::fromUtf8("Зарубежные сериалы")); tvSeriesRussianCheck = new QCheckBox(QString::fromUtf8("Русские сериалы")); moviesLayout->addWidget(latestMoviesCheck); moviesLayout->addWidget(newMoviesCheck); moviesLayout->addWidget(oldMoviesCheck); moviesLayout->addWidget(artHouseCheck); moviesLayout->addWidget(asianCheck); moviesLayout->addWidget(grindhouseCheck); moviesLayout->addWidget(russianCheck); moviesLayout->addWidget(ussrCheck); moviesLayout->addWidget(tvSeriesCheck); moviesLayout->addWidget(tvSeriesRussianCheck); moviesLayout->addStretch(1); animeCheck = new QCheckBox(QString::fromUtf8("Аниме (основной и HD разделы)")); cartoonsCheck = new QCheckBox(QString::fromUtf8("Иностранные мультфильмы")); cartoonSeriesCheck = new QCheckBox(QString::fromUtf8("Мультсериалы")); russianCartoonsCheck = new QCheckBox(QString::fromUtf8("Отечественные мультфильмы")); cartoonsLayout->addWidget(animeCheck); cartoonsLayout->addWidget(cartoonsCheck); cartoonsLayout->addWidget(cartoonSeriesCheck); cartoonsLayout->addWidget(russianCartoonsCheck); cartoonsLayout->addStretch(1); criminalCheck = new QCheckBox(QString::fromUtf8("Криминальная документалистика")); bbcCheck = new QCheckBox(QString::fromUtf8("BBC")); discoveryCheck = new QCheckBox(QString::fromUtf8("Discovery")); ngCheck = new QCheckBox(QString::fromUtf8("National Geographic")); documentaryLayout->addWidget(criminalCheck); documentaryLayout->addWidget(bbcCheck); documentaryLayout->addWidget(discoveryCheck); documentaryLayout->addWidget(ngCheck); documentaryLayout->addStretch(1); forumsLayout->addWidget(moviesGroup); forumsLayout->addWidget(cartoonsGroup); forumsLayout->addWidget(documentaryGroup); moviesGroup->setMinimumWidth(300); cartoonsGroup->setMinimumWidth(300); documentaryGroup->setMinimumWidth(300); loginLayout = new QFormLayout(loginScreen); loginEdit = new QLineEdit; passwordEdit = new QLineEdit; passwordEdit->setEchoMode(QLineEdit::PasswordEchoOnEdit); loginLayout->addRow(QString::fromUtf8("Пользователь"), loginEdit); loginLayout->addRow(QString::fromUtf8("Пароль"), passwordEdit); proxyLayout = new QFormLayout(proxyScreen); proxyCheck = new QCheckBox; proxyUrlEdit = new QLineEdit; proxyPortBox = new QSpinBox; proxyPortBox->setMaximum(65535); proxyTypeBox = new QComboBox; proxyTypeBox->addItem("SOCKS 5"); proxyTypeBox->addItem("HTTP"); proxyLoginEdit = new QLineEdit; proxyPasswordEdit = new QLineEdit; proxyPasswordEdit->setEchoMode(QLineEdit::PasswordEchoOnEdit); proxyLayout->addRow(QString::fromUtf8("Прокси для обхода блокировки:"), proxyCheck); proxyLayout->addRow(QString::fromUtf8("Адрес"), proxyUrlEdit); proxyLayout->addRow(QString::fromUtf8("Порт"), proxyPortBox); proxyLayout->addRow(QString::fromUtf8("Тип"), proxyTypeBox); proxyLayout->addRow(QString::fromUtf8("Логин"), proxyLoginEdit); proxyLayout->addRow(QString::fromUtf8("Пароль"), proxyPasswordEdit); connect(proxyCheck, SIGNAL(stateChanged(int)), this, SLOT(toggleProxy(int))); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(okButton, SIGNAL(clicked()), this, SLOT(saveSettings())); settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "MIB", "rutracker-news"); } void SettingsWindow::toggleProxy(int state) { if (state) { proxyUrlEdit->setEnabled(true); proxyPortBox->setEnabled(true); proxyTypeBox->setEnabled(true); proxyLoginEdit->setEnabled(true); proxyPasswordEdit->setEnabled(true); } else { proxyUrlEdit->setEnabled(false); proxyPortBox->setEnabled(false); proxyTypeBox->setEnabled(false); proxyLoginEdit->setEnabled(false); proxyPasswordEdit->setEnabled(false); } } void SettingsWindow::showEvent(QShowEvent *event) { /* read settings */ loginEdit->setText(settings->value("login").toString()); passwordEdit->setText(settings->value("password").toString()); proxyCheck->setChecked(settings->value("use-proxy").toBool()); proxyUrlEdit->setText(settings->value("proxy-url").toString()); proxyPortBox->setValue(settings->value("proxy-port").toInt()); proxyTypeBox->setCurrentIndex(proxyTypeBox->findText(settings->value("proxy-type").toString())); proxyLoginEdit->setText(settings->value("proxy-login").toString()); proxyPasswordEdit->setText(settings->value("proxy-password").toString()); toggleProxy(proxyCheck->checkState()); latestMoviesCheck->setChecked(settings->value("latest-movies").toBool()); newMoviesCheck->setChecked(settings->value("new-movies").toBool()); oldMoviesCheck->setChecked(settings->value("old-movies").toBool()); artHouseCheck->setChecked(settings->value("art-house").toBool()); asianCheck->setChecked(settings->value("asian").toBool()); grindhouseCheck->setChecked(settings->value("grindhouse").toBool()); russianCheck->setChecked(settings->value("russian").toBool()); ussrCheck->setChecked(settings->value("ussr").toBool()); tvSeriesCheck->setChecked(settings->value("tv-series").toBool()); tvSeriesRussianCheck->setChecked(settings->value("tv-series-russian").toBool()); animeCheck->setChecked(settings->value("anime").toBool()); cartoonsCheck->setChecked(settings->value("cartoons").toBool()); cartoonSeriesCheck->setChecked(settings->value("cartoon-series").toBool()); russianCartoonsCheck->setChecked(settings->value("russian-cartoons").toBool()); criminalCheck->setChecked(settings->value("criminal").toBool()); bbcCheck->setChecked(settings->value("bbc").toBool()); discoveryCheck->setChecked(settings->value("discovery").toBool()); ngCheck->setChecked(settings->value("ng").toBool()); } void SettingsWindow::saveSettings() { settings->setValue("login", loginEdit->text()); settings->setValue("password", passwordEdit->text()); settings->setValue("use-proxy", proxyCheck->isChecked()); settings->setValue("proxy-url", proxyUrlEdit->text()); settings->setValue("proxy-port", proxyPortBox->value()); settings->setValue("proxy-type", proxyTypeBox->currentText()); settings->setValue("proxy-login", proxyLoginEdit->text()); settings->setValue("proxy-password", proxyPasswordEdit->text()); settings->setValue("latest-movies", latestMoviesCheck->isChecked()); settings->setValue("new-movies", newMoviesCheck->isChecked()); settings->setValue("old-movies", oldMoviesCheck->isChecked()); settings->setValue("art-house", artHouseCheck->isChecked()); settings->setValue("asian", asianCheck->isChecked()); settings->setValue("grindhouse", grindhouseCheck->isChecked()); settings->setValue("russian", russianCheck->isChecked()); settings->setValue("ussr", ussrCheck->isChecked()); settings->setValue("tv-series", tvSeriesCheck->isChecked()); settings->setValue("tv-series-russian", tvSeriesRussianCheck->isChecked()); settings->setValue("anime", animeCheck->isChecked()); settings->setValue("cartoons", cartoonsCheck->isChecked()); settings->setValue("cartoon-series", cartoonSeriesCheck->isChecked()); settings->setValue("russian-cartoons", russianCartoonsCheck->isChecked()); settings->setValue("criminal", criminalCheck->isChecked()); settings->setValue("bbc", bbcCheck->isChecked()); settings->setValue("discovery", discoveryCheck->isChecked()); settings->setValue("ng", ngCheck->isChecked()); settings->sync(); accept(); } SettingsWindow::~SettingsWindow() { delete settings; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_PROPERTY_HPP #define REALM_PROPERTY_HPP #include <string> namespace realm { enum PropertyType { /** Integer type: NSInteger, int, long, Int (Swift) */ PropertyTypeInt = 0, /** Boolean type: BOOL, bool, Bool (Swift) */ PropertyTypeBool = 1, /** Float type: float, Float (Swift) */ PropertyTypeFloat = 9, /** Double type: double, Double (Swift) */ PropertyTypeDouble = 10, /** String type: NSString, String (Swift) */ PropertyTypeString = 2, /** Data type: NSData */ PropertyTypeData = 4, /** Any type: id, **not supported in Swift** */ PropertyTypeAny = 6, /** Date type: NSDate */ PropertyTypeDate = 7, /** Object type. See [Realm Models](http://realm.io/docs/cocoa/latest/#models) */ PropertyTypeObject = 12, /** Array type. See [Realm Models](http://realm.io/docs/cocoa/latest/#models) */ PropertyTypeArray = 13, }; struct Property { std::string name; PropertyType type; std::string object_type; bool is_primary = false; bool is_indexed = false; bool is_nullable = false; size_t table_column; bool requires_index() const { return is_primary || is_indexed; } }; static inline const char *string_for_property_type(PropertyType type) { switch (type) { case PropertyTypeString: return "string"; case PropertyTypeInt: return "int"; case PropertyTypeBool: return "bool"; case PropertyTypeDate: return "date"; case PropertyTypeData: return "data"; case PropertyTypeDouble: return "double"; case PropertyTypeFloat: return "float"; case PropertyTypeAny: return "any"; case PropertyTypeObject: return "object"; case PropertyTypeArray: return "array"; } } } #endif /* REALM_PROPERTY_HPP */ <commit_msg>fix old links in ObjectStore/property.hpp<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #ifndef REALM_PROPERTY_HPP #define REALM_PROPERTY_HPP #include <string> namespace realm { enum PropertyType { /** Integer type: NSInteger, int, long, Int (Swift) */ PropertyTypeInt = 0, /** Boolean type: BOOL, bool, Bool (Swift) */ PropertyTypeBool = 1, /** Float type: float, Float (Swift) */ PropertyTypeFloat = 9, /** Double type: double, Double (Swift) */ PropertyTypeDouble = 10, /** String type: NSString, String (Swift) */ PropertyTypeString = 2, /** Data type: NSData */ PropertyTypeData = 4, /** Any type: id, **not supported in Swift** */ PropertyTypeAny = 6, /** Date type: NSDate */ PropertyTypeDate = 7, /** Object type. See [Realm Models](http://realm.io/docs/objc/latest/#models) */ PropertyTypeObject = 12, /** Array type. See [Realm Models](http://realm.io/docs/objc/latest/#models) */ PropertyTypeArray = 13, }; struct Property { std::string name; PropertyType type; std::string object_type; bool is_primary = false; bool is_indexed = false; bool is_nullable = false; size_t table_column; bool requires_index() const { return is_primary || is_indexed; } }; static inline const char *string_for_property_type(PropertyType type) { switch (type) { case PropertyTypeString: return "string"; case PropertyTypeInt: return "int"; case PropertyTypeBool: return "bool"; case PropertyTypeDate: return "date"; case PropertyTypeData: return "data"; case PropertyTypeDouble: return "double"; case PropertyTypeFloat: return "float"; case PropertyTypeAny: return "any"; case PropertyTypeObject: return "object"; case PropertyTypeArray: return "array"; } } } #endif /* REALM_PROPERTY_HPP */ <|endoftext|>
<commit_before>/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://opensource.org/licenses/BSD-3-Clause for details. */ #include <functional> #include "helpers.h" #include "transform.h" using namespace std::placeholders; static void delete_span(std::vector<Command> &commands, std::vector<Span> &spans, size_t span_index) { spans.erase(spans.begin() + span_index); for (auto &c : commands) { if (c.identifier > span_index) { c.identifier--; } } } static void insert_span(std::vector<Command> &commands, std::vector<Span> &spans, size_t span_index, const Span &new_span) { spans.insert(spans.begin() + span_index, new_span); for (auto &c : commands) { if (c.identifier > span_index) { c.identifier++; } } } static void run(std::vector<Command> &commands, std::vector<Span> &spans, size_t column_width, const std::string &argument_indent_string) { (void)column_width; (void)argument_indent_string; for (auto c : commands) { const std::string ident = lowerstring(spans[c.identifier].data); std::string command_indentation; if (spans[c.identifier - 1].type == SpanType::Newline) { command_indentation = ""; } else if (spans[c.identifier - 1].type == SpanType::Space) { command_indentation = spans[c.identifier - 1].data; } else { throw std::runtime_error("command '" + ident + "' not preceded by space or newline: '" + spans[c.identifier - 1].data + "'"); } size_t line_width = command_indentation.size() + ident.size(); size_t next_token = c.identifier + 1; if (spans[next_token].type == SpanType::Space) { line_width += spans[next_token].data.size(); next_token++; } if (spans[next_token].type != SpanType::Lparen) { throw std::runtime_error("expected lparen, got '" + spans[next_token].data + "'"); } line_width += spans[next_token].data.size(); next_token++; bool first_argument = true; while (spans[next_token].type != SpanType::Rparen) { if (spans[next_token].type == SpanType::Space) { delete_span(commands, spans, next_token); } else if (spans[next_token].type == SpanType::Newline) { delete_span(commands, spans, next_token); } else if (spans[next_token].type == SpanType::Comment) { insert_span(commands, spans, next_token, {SpanType::Newline, "\n"}); insert_span(commands, spans, next_token + 1, {SpanType::Space, command_indentation + argument_indent_string}); next_token += 3; insert_span(commands, spans, next_token, {SpanType::Newline, "\n"}); insert_span(commands, spans, next_token + 1, {SpanType::Space, command_indentation + argument_indent_string}); first_argument = false; line_width = command_indentation.size() + argument_indent_string.size(); } else if (spans[next_token].type == SpanType::Quoted || spans[next_token].type == SpanType::Unquoted) { bool attached_comment = false; size_t argument_spans_count = 1; if (spans[next_token + 1].type == SpanType::Comment) { argument_spans_count = 2; attached_comment = true; } else if (spans[next_token + 1].type == SpanType::Space && spans[next_token + 2].type == SpanType::Comment) { argument_spans_count = 3; attached_comment = true; } size_t argument_size = 0; for (size_t i = 0; i < argument_spans_count; i++) { argument_size += spans[next_token + i].data.size(); } if (!first_argument) { argument_size += 1; } if (line_width + argument_size <= column_width) { if (!first_argument) { insert_span(commands, spans, next_token, {SpanType::Space, " "}); next_token++; } line_width += argument_size; if (first_argument) { first_argument = false; } } else { insert_span(commands, spans, next_token, {SpanType::Newline, "\n"}); insert_span(commands, spans, next_token + 1, {SpanType::Space, command_indentation + argument_indent_string}); next_token += 2; line_width = command_indentation.size() + argument_indent_string.size() + argument_size - 1; } if (attached_comment) { line_width = column_width; } next_token += argument_spans_count; } else { throw std::runtime_error("unexpected '" + spans[next_token].data + "'"); } } } } static bool handleCommandLine(const std::string &arg, std::vector<TransformFunction> &transform_functions) { if (arg.find("-argument-bin-pack=") != 0) { return false; } const size_t width = std::stoi(arg.substr(std::string{"-argument-bin-pack="}.size())); // TODO: allow specifying indent as well as column width transform_functions.emplace_back(std::bind(run, _1, _2, width, " ")); return true; }; static const on_program_load transform_argument_per_line{[]() { getCommandLineDescriptions().emplace_back( "-argument-bin-pack=WIDTH", "\"Bin pack\" arguments, with a maximum column width of WIDTH."); getCommandLineHandlers().emplace_back(&handleCommandLine); }}; TEST_CASE("Bin packs arguments", "[transform.argument_bin_pack]") { REQUIRE_TRANSFORMS_TO(std::bind(run, _1, _2, 30, " "), R"( command(ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7) command( ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) command( ARG1# comment # entire line comment ARG2 # comment preceded by space ARG3 #a ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) )", R"( command(ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7) command(ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) command(ARG1# comment # entire line comment ARG2 # comment preceded by space ARG3 #a ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) )"); } <commit_msg>transform_argument_bin_pack: extracted function insert_before<commit_after>/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://opensource.org/licenses/BSD-3-Clause for details. */ #include <functional> #include "helpers.h" #include "transform.h" using namespace std::placeholders; static void delete_span(std::vector<Command> &commands, std::vector<Span> &spans, size_t span_index) { spans.erase(spans.begin() + span_index); for (auto &c : commands) { if (c.identifier > span_index) { c.identifier--; } } } static void insert_before(size_t &span_index, std::vector<Command> &commands, std::vector<Span> &spans, const std::vector<Span> &new_spans) { spans.insert(spans.begin() + span_index, new_spans.begin(), new_spans.end()); for (auto &c : commands) { if (c.identifier > span_index) { c.identifier += new_spans.size(); } } span_index += new_spans.size(); } static void insert_before(size_t &span_index, std::vector<Command> &commands, std::vector<Span> &spans, const Span &new_span) { return insert_before(span_index, commands, spans, std::vector<Span>{new_span}); } static void run(std::vector<Command> &commands, std::vector<Span> &spans, size_t column_width, const std::string &argument_indent_string) { (void)column_width; (void)argument_indent_string; for (auto c : commands) { const std::string ident = lowerstring(spans[c.identifier].data); std::string command_indentation; if (spans[c.identifier - 1].type == SpanType::Newline) { command_indentation = ""; } else if (spans[c.identifier - 1].type == SpanType::Space) { command_indentation = spans[c.identifier - 1].data; } else { throw std::runtime_error("command '" + ident + "' not preceded by space or newline: '" + spans[c.identifier - 1].data + "'"); } size_t line_width = command_indentation.size() + ident.size(); size_t next_token = c.identifier + 1; if (spans[next_token].type == SpanType::Space) { line_width += spans[next_token].data.size(); next_token++; } if (spans[next_token].type != SpanType::Lparen) { throw std::runtime_error("expected lparen, got '" + spans[next_token].data + "'"); } line_width += spans[next_token].data.size(); next_token++; bool first_argument = true; while (spans[next_token].type != SpanType::Rparen) { if (spans[next_token].type == SpanType::Space) { delete_span(commands, spans, next_token); } else if (spans[next_token].type == SpanType::Newline) { delete_span(commands, spans, next_token); } else if (spans[next_token].type == SpanType::Comment) { insert_before(next_token, commands, spans, { {SpanType::Newline, "\n"}, {SpanType::Space, command_indentation + argument_indent_string}, }); next_token++; line_width = column_width; } else if (spans[next_token].type == SpanType::Quoted || spans[next_token].type == SpanType::Unquoted) { bool add_line_break = false; size_t argument_spans_count = 1; if (spans[next_token + 1].type == SpanType::Comment) { argument_spans_count = 2; add_line_break = true; } else if (spans[next_token + 1].type == SpanType::Space && spans[next_token + 2].type == SpanType::Comment) { argument_spans_count = 3; add_line_break = true; } size_t argument_size = 0; for (size_t i = 0; i < argument_spans_count; i++) { argument_size += spans[next_token + i].data.size(); } if (!first_argument) { argument_size += 1; } if (line_width + argument_size <= column_width) { if (!first_argument) { insert_before(next_token, commands, spans, {SpanType::Space, " "}); } line_width += argument_size; first_argument = false; } else { insert_before( next_token, commands, spans, {{SpanType::Newline, "\n"}, {SpanType::Space, command_indentation + argument_indent_string}}); line_width = command_indentation.size() + argument_indent_string.size() + argument_size - 1; } if (add_line_break) { line_width = column_width; } next_token += argument_spans_count; } else { throw std::runtime_error("unexpected '" + spans[next_token].data + "'"); } } } } static bool handleCommandLine(const std::string &arg, std::vector<TransformFunction> &transform_functions) { if (arg.find("-argument-bin-pack=") != 0) { return false; } const size_t width = std::stoi(arg.substr(std::string{"-argument-bin-pack="}.size())); // TODO: allow specifying indent as well as column width transform_functions.emplace_back(std::bind(run, _1, _2, width, " ")); return true; }; static const on_program_load transform_argument_per_line{[]() { getCommandLineDescriptions().emplace_back( "-argument-bin-pack=WIDTH", "\"Bin pack\" arguments, with a maximum column width of WIDTH."); getCommandLineHandlers().emplace_back(&handleCommandLine); }}; TEST_CASE("Bin packs arguments", "[transform.argument_bin_pack]") { REQUIRE_TRANSFORMS_TO(std::bind(run, _1, _2, 30, " "), R"( command(ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7) command( ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) command( ARG1# comment # entire line comment ARG2 # comment preceded by space ARG3 #a ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) )", R"( command(ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7) command(ARG1 ARG2 ARG3 ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) command(ARG1# comment # entire line comment ARG2 # comment preceded by space ARG3 #a ARG4 ARG5 ARG6 ARG7 ARG8 ARG9 ARG10) )"); } <|endoftext|>
<commit_before>#ifndef ATL_GC_HH #define ATL_GC_HH // @file /home/ryan/programming/atl/gc.hpp // @author Ryan Domigan <ryan_domigan@[email protected]> // Created on Jan 08, 2014 // // A garbage collected environment. #include <limits> #include <algorithm> #include <functional> #include <list> #include <memory> #include <iterator> #include <boost/mpl/map.hpp> #include "./debug.hpp" namespace atl { using namespace std; // Immediate (wrapped as an Any). This doesn't require the GC per se, but is related to // initialization and allocation. // // ++add assert (that I am wrapping an immediate). // @tparam T: // @return: template<class T> Any aimm() { return Any(tag<T>::value, nullptr); } Any aimm(Any *ptr) { return Any(tag<Pointer>::value, (void*)ptr); } Any aimm(long num) { return Any(tag<Fixnum>::value, (void*)num); } /*****************/ /* ____ ____ */ /* / ___|/ ___| */ /* | | _| | */ /* | |_| | |___ */ /* \____|\____| */ /*****************/ namespace memory_pool { template<class T> class Pool { private: static const size_t _size = 512; static const size_t num_mark_feilds = (_size / (sizeof(size_t) << 1)); static const size_t _mask = numeric_limits<off_t>::digits >> 1; typedef size_t mark_t; // used to hold a mark/unmarked bit and a allocated/free bit mark_t _mark[num_mark_feilds]; T *_begin, *_itr, *_end, *_free; public: static_assert( sizeof(T) >= sizeof(void*), "Can't build a pool _free list of types sized < void*"); Pool() : _free(nullptr){ _itr = _begin = (T*) new char[sizeof(T) * _size]; _end = _itr + _size; for(unsigned int i = 0; i < num_mark_feilds; ++i) _mark[i] = 0; } ~Pool() { delete[] (char*)_begin; } T *begin() { return _begin; } T *end() { return _end; } // @param p: pointer to the object that needs marking // @return: true if the mark was needed, false if the object was already marked. bool mark(T *p) { off_t offset = reinterpret_cast<off_t>( p - _begin) , mark_bit = static_cast<off_t>(1) << ((offset & _mask) << 1); if( _mark[offset >> 5] & mark_bit ) return false; _mark[offset >> 5] |= mark_bit; return true; } // allocates a T from the array, checking _free list first T* alloc() { T *tmp ; if(_free != nullptr) { tmp = _free; _free = *reinterpret_cast<T**>(_free); } else if(_itr != _end) tmp = _itr++; else return nullptr; /* mark that this as allocated for the sweep cycle */ off_t offset = reinterpret_cast<off_t>( tmp - _begin); _mark[offset >> 5] |= static_cast<off_t>(2) << ((offset & _mask) << 1); return tmp; } /* delete all un-marked objects (and re-set mark flags) */ virtual unsigned int sweep() { unsigned int item = 0 , swept = 0; for(unsigned int i = 0; i < num_mark_feilds; ++i) { for(unsigned int mask = 2 /* allocated */ ; mask /* while the bits havn't shifted off */ ; mask <<= 2 , ++item ) { if( _mark[i] & mask ) { /* is the element allocated */ if( _mark[i] & (mask >> 1) ) /* yes; and it's marked. Just clear the bit */ _mark[i] ^= (mask >> 1); else { /* allocated but not marked; collect */ _mark[i] ^= mask; _begin[item].~T(); /* call the destructor*/ ++swept; if((_begin + item + 1) == _itr) --_itr; else { *reinterpret_cast<T**>(_begin + item) = _free; _free = _begin + item; }}} }} cout << "GC: Sweep reclaimed " << swept << endl; return swept; } void print() { for(unsigned int i = 1; i <= num_mark_feilds; ++i) { cout << "["; print_binary( _mark[num_mark_feilds - i] ); cout << "]" << endl; } } /* test weather ptr is in this particular array */ int cmp(T *ptr) { if(ptr < _begin) return -1; if(ptr >= _end) return 1; return 0; } }; } class GC { private: typedef std::list< Any > MarkType; MarkType _mark; private: vector< function<void (GC&)> > _mark_callbacks; void unregister(MarkType::iterator itr) { _mark.erase(itr); } memory_pool::Pool< Undefined > _undefined_heap; memory_pool::Pool< Procedure > _procedure_heap; memory_pool::Pool< String > _string_heap; memory_pool::Pool< CxxFunctor > _primitive_recursive_heap; memory_pool::Pool< Symbol > _symbol_heap; memory_pool::Pool< Parameter > _Parameter_heap; memory_pool::Pool< Slice > _slice_heap; template< class T, memory_pool::Pool<T> GC::*member > struct MemberPtr { typedef memory_pool::Pool<T> GC::* PoolType; /* man this would be easier with inline definitions. */ const static PoolType value; }; typedef mpl::map< mpl::pair< Undefined , MemberPtr<Undefined, &GC::_undefined_heap > > , mpl::pair< Procedure , MemberPtr<Procedure, &GC::_procedure_heap > > , mpl::pair< String , MemberPtr<String, &GC::_string_heap > > , mpl::pair< CxxFunctor, MemberPtr<CxxFunctor, &GC::_primitive_recursive_heap > > , mpl::pair< Symbol, MemberPtr<Symbol, &GC::_symbol_heap > > , mpl::pair< Parameter, MemberPtr<Parameter, &GC::_Parameter_heap > > , mpl::pair< Slice, MemberPtr<Slice, &GC::_slice_heap > > > PoolMap; template<class T> T* alloc_from(memory_pool::Pool<T> &pool) { T* result = pool.alloc(); if(result == nullptr) { mark_and_sweep(); result = pool.alloc(); if(result == nullptr) throw string("out of memory"); } return result; } public: typedef PCode::value_type* PCodeAccumulator; std::vector<PCodeAccumulator> code_blocks; void mark_and_sweep() { for(auto i : _mark_callbacks) i(*this); _undefined_heap.sweep(); _procedure_heap.sweep(); _string_heap.sweep(); } void mark(Any a) {} /** * Adds callbacks which will be invoked during the mark phase of the GC. * * @param fn: the callback */ void mark_callback(function<void (GC&)> fn) { _mark_callbacks.push_back(fn); } /*****************************/ /** __ __ _ **/ /** | \/ | __ _| | _____ **/ /** | |\/| |/ _` | |/ / _ \ **/ /** | | | | (_| | < __/ **/ /** |_| |_|\__,_|_|\_\___| **/ /*****************************/ template<class T> T* alloc() { static_assert( mpl::has_key<PoolMap, T>::value, "GC::Type does not have corrosponding pool." ); return alloc_from( (this->*mpl::at<PoolMap,T>::type::value) ); } PCodeAccumulator& alloc_pcode() { code_blocks.push_back(new PCode::value_type[100]); return code_blocks.back(); } template<class Type, class ... Types> Type* make(Types ... args) { return new ( alloc<Type>() ) Type (args...); } template<class Type, class ... Types> Any amake(Types ... args) { return Any( tag<Type>::value , make<Type>(args...)); } // Mixed metaphore struct. // This is a container that behaves a bit like an iterator. struct DynamicVector { typedef Any* iterator; typedef const Any* const_iterator; typedef Any value_type; Any *_buffer, *_end, *_buffer_end; DynamicVector(size_t initial_size) { _buffer = new Any[initial_size + 1]; _buffer++; // reserve for the array end pointer _end = _buffer; _buffer_end = _buffer + initial_size; } DynamicVector(const DynamicVector&) = default; iterator begin() { return _buffer; } iterator end() { return _end; } const_iterator begin() const { return _buffer; } const_iterator end() const { return _end; } Any& back() { return *(_end - 1); } template<class T> T* push_seq() { T *result = new (_end)T(_end + 1, _end + 1); _end += 2; return result; } void push_back(const Any& input) { *_end = input; ++_end; } Any pop_back() { --_end; return _end[1]; } void pop_back(size_t nn) { _end -= nn; } void resize(size_t n) { } // TODO DynamicVector& operator++() { ++_end; return *this; } DynamicVector operator++(int) { DynamicVector vec = *this; ++_end; return vec; } Any& operator*() { return *_end; } DynamicVector& operator+=(size_t n) { _end += n; return *this; } Any& operator[](size_t n) { return _end[n]; } std::back_insert_iterator<GC::DynamicVector> back_insert_iterator() { return std::back_insert_iterator<GC::DynamicVector>(*this); } }; std::unique_ptr<DynamicVector> dynamic_vector(size_t initial_size = 100) { return std::move(std::unique_ptr<DynamicVector>(new DynamicVector(initial_size))); } }; template< class T, memory_pool::Pool<T> GC::*member > const typename GC::MemberPtr<T,member>::PoolType GC::MemberPtr<T,member>::value = member; /** * Uses GC to mark each argument of this function. * * @tparam Types: types of the args * @param args: args to be marked */ void mark_args(GC &gc) {} template<class T, class ... Types> void mark_args(GC &gc, T a, Types ... as) { gc.mark( a ); mark_args(gc, as...); } } namespace std { template<> struct iterator_traits<atl::GC::DynamicVector> { typedef size_t difference_type; typedef atl::Any value_type; typedef atl::Any* pointer; typedef atl::Any& reference; typedef output_iterator_tag iterator_category; }; } #endif <commit_msg>Reformat gc.hpp<commit_after>#ifndef ATL_GC_HH #define ATL_GC_HH // @file /home/ryan/programming/atl/gc.hpp // @author Ryan Domigan <ryan_domigan@[email protected]> // Created on Jan 08, 2014 // // A garbage collected environment. #include <limits> #include <algorithm> #include <functional> #include <list> #include <memory> #include <iterator> #include <boost/mpl/map.hpp> #include "./debug.hpp" namespace atl { using namespace std; // Immediate (wrapped as an Any). This doesn't require the GC per se, but is related to // initialization and allocation. // // ++add assert (that I am wrapping an immediate). // @tparam T: // @return: template<class T> Any aimm() { return Any(tag<T>::value, nullptr); } Any aimm(Any *ptr) { return Any(tag<Pointer>::value, (void*)ptr); } Any aimm(long num) { return Any(tag<Fixnum>::value, (void*)num); } /*****************/ /* ____ ____ */ /* / ___|/ ___| */ /* | | _| | */ /* | |_| | |___ */ /* \____|\____| */ /*****************/ namespace memory_pool { template<class T> class Pool { private: static const size_t _size = 512; static const size_t num_mark_feilds = (_size / (sizeof(size_t) << 1)); static const size_t _mask = numeric_limits<off_t>::digits >> 1; typedef size_t mark_t; // used to hold a mark/unmarked bit and a allocated/free bit mark_t _mark[num_mark_feilds]; T *_begin, *_itr, *_end, *_free; public: static_assert( sizeof(T) >= sizeof(void*), "Can't build a pool _free list of types sized < void*"); Pool() : _free(nullptr) { _itr = _begin = (T*) new char[sizeof(T) * _size]; _end = _itr + _size; for(unsigned int i = 0; i < num_mark_feilds; ++i) _mark[i] = 0; } ~Pool() { delete[] (char*)_begin; } T *begin() { return _begin; } T *end() { return _end; } // @param p: pointer to the object that needs marking // @return: true if the mark was needed, false if the object was already marked. bool mark(T *p) { off_t offset = reinterpret_cast<off_t>( p - _begin) , mark_bit = static_cast<off_t>(1) << ((offset & _mask) << 1); if( _mark[offset >> 5] & mark_bit ) return false; _mark[offset >> 5] |= mark_bit; return true; } // allocates a T from the array, checking _free list first T* alloc() { T *tmp ; if(_free != nullptr) { tmp = _free; _free = *reinterpret_cast<T**>(_free); } else if(_itr != _end) tmp = _itr++; else return nullptr; // mark that this as allocated for the sweep cycle off_t offset = reinterpret_cast<off_t>( tmp - _begin); _mark[offset >> 5] |= static_cast<off_t>(2) << ((offset & _mask) << 1); return tmp; } // delete all un-marked objects (and re-set mark flags) virtual unsigned int sweep() { unsigned int item = 0 , swept = 0; for(unsigned int i = 0; i < num_mark_feilds; ++i) { for(unsigned int mask = 2 // allocated ; mask // while the bits havn't shifted off ; mask <<= 2 , ++item ) { if( _mark[i] & mask ) { // is the element allocated if( _mark[i] & (mask >> 1) ) // yes; and it's marked. Just clear the bit _mark[i] ^= (mask >> 1); else { // allocated but not marked; collect _mark[i] ^= mask; _begin[item].~T(); // call the destructor ++swept; if((_begin + item + 1) == _itr) --_itr; else { *reinterpret_cast<T**>(_begin + item) = _free; _free = _begin + item; }}} }} cout << "GC: Sweep reclaimed " << swept << endl; return swept; } void print() { for(unsigned int i = 1; i <= num_mark_feilds; ++i) { cout << "["; print_binary( _mark[num_mark_feilds - i] ); cout << "]" << endl; } } // test whether ptr is in this particular array int cmp(T *ptr) { if(ptr < _begin) return -1; if(ptr >= _end) return 1; return 0; } }; } class GC { private: typedef std::list< Any > MarkType; MarkType _mark; private: vector< function<void (GC&)> > _mark_callbacks; void unregister(MarkType::iterator itr) { _mark.erase(itr); } memory_pool::Pool< Undefined > _undefined_heap; memory_pool::Pool< Procedure > _procedure_heap; memory_pool::Pool< String > _string_heap; memory_pool::Pool< CxxFunctor > _primitive_recursive_heap; memory_pool::Pool< Symbol > _symbol_heap; memory_pool::Pool< Parameter > _Parameter_heap; memory_pool::Pool< Slice > _slice_heap; memory_pool::Pool< abstract_type::Type > _abstract_type_heap; template< class T, memory_pool::Pool<T> GC::*member > struct MemberPtr { typedef memory_pool::Pool<T> GC::* PoolType; /* man this would be easier with inline definitions. */ const static PoolType value; }; typedef mpl::map< mpl::pair< Undefined , MemberPtr<Undefined, &GC::_undefined_heap > > , mpl::pair< Procedure , MemberPtr<Procedure, &GC::_procedure_heap > > , mpl::pair< String , MemberPtr<String, &GC::_string_heap > > , mpl::pair< CxxFunctor, MemberPtr<CxxFunctor, &GC::_primitive_recursive_heap > > , mpl::pair< Symbol, MemberPtr<Symbol, &GC::_symbol_heap > > , mpl::pair< Parameter, MemberPtr<Parameter, &GC::_Parameter_heap > > , mpl::pair< Slice, MemberPtr<Slice, &GC::_slice_heap > > , mpl::pair< abstract_type::Type, MemberPtr<abstract_type::Type, &GC::_abstract_type_heap> > > PoolMap; template<class T> T* alloc_from(memory_pool::Pool<T> &pool) { T* result = pool.alloc(); if(result == nullptr) { mark_and_sweep(); result = pool.alloc(); if(result == nullptr) throw string("out of memory"); } return result; } public: typedef PCode::value_type* PCodeAccumulator; std::vector<PCodeAccumulator> code_blocks; void mark_and_sweep() { for(auto i : _mark_callbacks) i(*this); _undefined_heap.sweep(); _procedure_heap.sweep(); _string_heap.sweep(); } void mark(Any a) {} // Adds callbacks which will be invoked during the mark phase of the GC. // @param fn: the callback void mark_callback(function<void (GC&)> fn) { _mark_callbacks.push_back(fn); } /*****************************/ /** __ __ _ **/ /** | \/ | __ _| | _____ **/ /** | |\/| |/ _` | |/ / _ \ **/ /** | | | | (_| | < __/ **/ /** |_| |_|\__,_|_|\_\___| **/ /*****************************/ template<class T> T* alloc() { static_assert( mpl::has_key<PoolMap, T>::value, "GC::Type does not have corrosponding pool." ); return alloc_from( (this->*mpl::at<PoolMap,T>::type::value) ); } PCodeAccumulator& alloc_pcode() { code_blocks.push_back(new PCode::value_type[100]); return code_blocks.back(); } template<class Type, class ... Types> Type* make(Types ... args) { return new ( alloc<Type>() ) Type (args...); } template<class Type, class ... Types> Any amake(Types ... args) { return Any( tag<Type>::value , make<Type>(args...)); } // Mixed metaphore struct. // This is a container that behaves a bit like an iterator. struct DynamicVector { typedef Any* iterator; typedef const Any* const_iterator; typedef Any value_type; Any *_buffer, *_end, *_buffer_end; DynamicVector(size_t initial_size) { _buffer = new Any[initial_size + 1]; _buffer++; // reserve for the array end pointer _end = _buffer; _buffer_end = _buffer + initial_size; } DynamicVector(const DynamicVector&) = default; iterator begin() { return _buffer; } iterator end() { return _end; } const_iterator begin() const { return _buffer; } const_iterator end() const { return _end; } Any& back() { return *(_end - 1); } template<class T> T* push_seq() { T *result = new (_end)T(_end + 1, _end + 1); _end += 2; return result; } void push_back(const Any& input) { *_end = input; ++_end; } Any pop_back() { --_end; return _end[1]; } void pop_back(size_t nn) { _end -= nn; } void resize(size_t n) { } // TODO DynamicVector& operator++() { ++_end; return *this; } DynamicVector operator++(int) { DynamicVector vec = *this; ++_end; return vec; } Any& operator*() { return *_end; } DynamicVector& operator+=(size_t n) { _end += n; return *this; } Any& operator[](size_t n) { return _end[n]; } std::back_insert_iterator<GC::DynamicVector> back_insert_iterator() { return std::back_insert_iterator<GC::DynamicVector>(*this); } }; std::unique_ptr<DynamicVector> dynamic_seq(size_t initial_size = 100) { return std::move(std::unique_ptr<DynamicVector>(new DynamicVector(initial_size))); } }; template< class T, memory_pool::Pool<T> GC::*member > const typename GC::MemberPtr<T,member>::PoolType GC::MemberPtr<T,member>::value = member; // Uses GC to mark each argument of this function. // // @tparam Types: types of the args // @param args: args to be marked void mark_args(GC &gc) {} template<class T, class ... Types> void mark_args(GC &gc, T a, Types ... as) { gc.mark( a ); mark_args(gc, as...); } } namespace std { template<> struct iterator_traits<atl::GC::DynamicVector> { typedef size_t difference_type; typedef atl::Any value_type; typedef atl::Any* pointer; typedef atl::Any& reference; typedef output_iterator_tag iterator_category; }; } #endif <|endoftext|>
<commit_before>/******************************************************************************\ * File: lexers.cpp * Purpose: Implementation of wxExLexers classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stdpaths.h> #include <wx/tokenzr.h> #include <wx/stc/stc.h> #include <wx/textfile.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> // for wxExMatchesOneOf wxExLexers::wxExLexers(const wxFileName& filename) : m_FileName(filename) { } const wxString wxExLexers::BuildComboBox() const { wxString combobox; for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (!it->GetAssociations().empty()) { if (!combobox.empty()) { combobox += ","; } combobox += it->GetAssociations(); } } return combobox; } const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const { const wxString allfiles_wildcard = _("All Files") + wxString::Format(" (%s)|%s", wxFileSelectorDefaultWildcardStr, wxFileSelectorDefaultWildcardStr); wxString wildcards = allfiles_wildcard; // Build the wildcard string using all available lexers. for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (!it->GetAssociations().empty()) { const wxString wildcard = it->GetScintillaLexer() + " (" + it->GetAssociations() + ") |" + it->GetAssociations(); if (wxExMatchesOneOf(filename, it->GetAssociations())) { wildcards = wildcard + "|" + wildcards; } else { wildcards = wildcards + "|" + wildcard; } } } return wildcards; } const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const { if (!filename.IsOk()) { return wxExLexer(); } for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (wxExMatchesOneOf(filename, it->GetAssociations())) { return *it; } } return wxExLexer(); } const wxExLexer wxExLexers::FindByName( const wxString& name, bool show_error_if_not_found) const { for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (name == it->GetScintillaLexer()) { return *it; } } if (!m_Lexers.empty() && show_error_if_not_found) { // We did not find a lexer, so give an error. // The same error is shown in wxExSTC::SetLexer as well. wxLogError("Lexer is not known: " + name); } return wxExLexer(); } const wxExLexer wxExLexers::FindByText(const wxString& text) const { // Add automatic lexers if text starts with some special tokens. const wxString text_lowercase = text.Lower(); if (text_lowercase.StartsWith("#") || // .po files that do not have comment headers, start with msgid, so set them text_lowercase.StartsWith("msgid")) { return FindByName("bash", false); // don't show error } else if (text_lowercase.StartsWith("<html>") || text_lowercase.StartsWith("<?php") || text_lowercase.StartsWith("<?xml")) { return FindByName("hypertext", false); // don't show error } // cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map) // so add here. else if (text_lowercase.StartsWith("//")) { return FindByName("cpp", false); // don't show error } return wxExLexer(); } const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const { wxString text; wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "colouring") { text += child->GetAttribute("no", "0") + "=" + child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL(); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError("Undefined colourings tag: %s on: %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } void wxExLexers::ParseTagGlobal(const wxXmlNode* node) { wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "comment") { // Ignore comments. } else if (child->GetName() == "hex") { m_StylesHex.push_back( child->GetAttribute("no", "0") + "=" + child->GetNodeContent().Strip(wxString::both)); } else if (child->GetName() == "indicator") { m_Indicators.insert(std::make_pair( atoi(child->GetAttribute("no", "0").c_str()), atoi(child->GetNodeContent().Strip(wxString::both).c_str()))); } else if (child->GetName() == "marker") { const wxExMarker marker(ParseTagMarker( child->GetAttribute("no", "0"), child->GetNodeContent().Strip(wxString::both))); if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX && marker.GetMarkerSymbol() < wxSTC_STYLE_MAX) { m_Markers.push_back(marker); } else { wxLogError("Illegal marker number: %d or symbol: %d on: %d", marker.GetMarkerNumber(), marker.GetMarkerSymbol(), child->GetLineNumber()); } } else if (child->GetName() == "style") { m_Styles.push_back( child->GetAttribute("no", "0") + "=" + child->GetNodeContent().Strip(wxString::both)); } else { wxLogError("Undefined global tag: %s on: %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } } const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const { wxExLexer lexer; lexer.m_ScintillaLexer = node->GetAttribute("name", ""); lexer.m_Associations = node->GetAttribute("extensions", ""); wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "colourings") { lexer.m_Colourings = ParseTagColourings(child); } else if (child->GetName() == "keywords") { if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both))) { wxLogError("Keywords could not be set on: %d", child->GetLineNumber()); } } else if (child->GetName() == "properties") { lexer.m_Properties = ParseTagProperties(child); } else if (child->GetName() == "comments") { lexer.m_CommentBegin = child->GetAttribute("begin1", ""); lexer.m_CommentEnd = child->GetAttribute("end1", ""); lexer.m_CommentBegin2 = child->GetAttribute("begin2", ""); lexer.m_CommentEnd2 = child->GetAttribute("end2", ""); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError("Undefined lexer tag: %s on: %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return lexer; } const wxExMarker wxExLexers::ParseTagMarker( const wxString& number, const wxString& props) const { wxStringTokenizer prop_fields(props, ","); const wxString symbol = prop_fields.GetNextToken(); wxColour foreground; wxColour background; if (prop_fields.HasMoreTokens()) { foreground = prop_fields.GetNextToken(); if (prop_fields.HasMoreTokens()) { background = prop_fields.GetNextToken(); } } const int no = atoi(number.c_str()); const int symbol_no = atoi(symbol.c_str()); if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX) { return wxExMarker(no, symbol_no, foreground, background); } else { wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no); return wxExMarker(0, 0, foreground, background); } } const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const { wxString text; wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "property") { text += child->GetAttribute("name", "0") + "=" + child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL(); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError("Undefined properties tag: %s on %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } bool wxExLexers::Read() { if (!m_FileName.FileExists()) { return false; } wxXmlDocument doc; if (!doc.Load(m_FileName.GetFullPath())) { return false; } // Initialize members. m_Indicators.clear(); m_Lexers.clear(); m_Markers.clear(); m_Styles.clear(); m_StylesHex.clear(); wxXmlNode* child = doc.GetRoot()->GetChildren(); while (child) { if (child->GetName() == "global") { ParseTagGlobal(child); } else if (child->GetName() == "lexer") { const wxExLexer& lexer = ParseTagLexer(child); if (!lexer.GetScintillaLexer().empty()) { m_Lexers.push_back(lexer); } } child = child->GetNext(); } return true; } bool wxExLexers::ShowDialog( wxWindow* parent, wxExLexer& lexer, const wxString& caption) const { wxArrayString aChoices; int choice = -1; int index = 0; for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { aChoices.Add(it->GetScintillaLexer()); if (lexer.GetScintillaLexer() == it->GetScintillaLexer()) { choice = index; } index++; } aChoices.Add("<none>"); if (lexer.GetScintillaLexer().empty()) { choice = index; } index++; wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices); if (choice != -1) { dlg.SetSelection(choice); } if (dlg.ShowModal() == wxID_CANCEL) { return false; } const wxString sel = dlg.GetStringSelection(); if (sel == "<none>") { lexer = wxExLexer(); } else { lexer = FindByName(sel); } return true; } <commit_msg>improved the none lexer<commit_after>/******************************************************************************\ * File: lexers.cpp * Purpose: Implementation of wxExLexers classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stdpaths.h> #include <wx/tokenzr.h> #include <wx/stc/stc.h> #include <wx/textfile.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> // for wxExMatchesOneOf wxExLexers::wxExLexers(const wxFileName& filename) : m_FileName(filename) { } const wxString wxExLexers::BuildComboBox() const { wxString combobox; for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (!it->GetAssociations().empty()) { if (!combobox.empty()) { combobox += ","; } combobox += it->GetAssociations(); } } return combobox; } const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const { const wxString allfiles_wildcard = _("All Files") + wxString::Format(" (%s)|%s", wxFileSelectorDefaultWildcardStr, wxFileSelectorDefaultWildcardStr); wxString wildcards = allfiles_wildcard; // Build the wildcard string using all available lexers. for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (!it->GetAssociations().empty()) { const wxString wildcard = it->GetScintillaLexer() + " (" + it->GetAssociations() + ") |" + it->GetAssociations(); if (wxExMatchesOneOf(filename, it->GetAssociations())) { wildcards = wildcard + "|" + wildcards; } else { wildcards = wildcards + "|" + wildcard; } } } return wildcards; } const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const { if (!filename.IsOk()) { return wxExLexer(); } for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (wxExMatchesOneOf(filename, it->GetAssociations())) { return *it; } } return wxExLexer(); } const wxExLexer wxExLexers::FindByName( const wxString& name, bool show_error_if_not_found) const { for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { if (name == it->GetScintillaLexer()) { return *it; } } if (!m_Lexers.empty() && show_error_if_not_found) { // We did not find a lexer, so give an error. // The same error is shown in wxExSTC::SetLexer as well. wxLogError("Lexer is not known: " + name); } return wxExLexer(); } const wxExLexer wxExLexers::FindByText(const wxString& text) const { // Add automatic lexers if text starts with some special tokens. const wxString text_lowercase = text.Lower(); if (text_lowercase.StartsWith("#") || // .po files that do not have comment headers, start with msgid, so set them text_lowercase.StartsWith("msgid")) { return FindByName("bash", false); // don't show error } else if (text_lowercase.StartsWith("<html>") || text_lowercase.StartsWith("<?php") || text_lowercase.StartsWith("<?xml")) { return FindByName("hypertext", false); // don't show error } // cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map) // so add here. else if (text_lowercase.StartsWith("//")) { return FindByName("cpp", false); // don't show error } return wxExLexer(); } const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const { wxString text; wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "colouring") { text += child->GetAttribute("no", "0") + "=" + child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL(); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError("Undefined colourings tag: %s on: %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } void wxExLexers::ParseTagGlobal(const wxXmlNode* node) { wxXmlNode* child = node->GetChildren(); while (child) { if (child->GetName() == "comment") { // Ignore comments. } else if (child->GetName() == "hex") { m_StylesHex.push_back( child->GetAttribute("no", "0") + "=" + child->GetNodeContent().Strip(wxString::both)); } else if (child->GetName() == "indicator") { m_Indicators.insert(std::make_pair( atoi(child->GetAttribute("no", "0").c_str()), atoi(child->GetNodeContent().Strip(wxString::both).c_str()))); } else if (child->GetName() == "marker") { const wxExMarker marker(ParseTagMarker( child->GetAttribute("no", "0"), child->GetNodeContent().Strip(wxString::both))); if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX && marker.GetMarkerSymbol() < wxSTC_STYLE_MAX) { m_Markers.push_back(marker); } else { wxLogError("Illegal marker number: %d or symbol: %d on: %d", marker.GetMarkerNumber(), marker.GetMarkerSymbol(), child->GetLineNumber()); } } else if (child->GetName() == "style") { m_Styles.push_back( child->GetAttribute("no", "0") + "=" + child->GetNodeContent().Strip(wxString::both)); } else { wxLogError("Undefined global tag: %s on: %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } } const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const { wxExLexer lexer; lexer.m_ScintillaLexer = node->GetAttribute("name", ""); lexer.m_Associations = node->GetAttribute("extensions", ""); wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "colourings") { lexer.m_Colourings = ParseTagColourings(child); } else if (child->GetName() == "keywords") { if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both))) { wxLogError("Keywords could not be set on: %d", child->GetLineNumber()); } } else if (child->GetName() == "properties") { lexer.m_Properties = ParseTagProperties(child); } else if (child->GetName() == "comments") { lexer.m_CommentBegin = child->GetAttribute("begin1", ""); lexer.m_CommentEnd = child->GetAttribute("end1", ""); lexer.m_CommentBegin2 = child->GetAttribute("begin2", ""); lexer.m_CommentEnd2 = child->GetAttribute("end2", ""); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError("Undefined lexer tag: %s on: %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return lexer; } const wxExMarker wxExLexers::ParseTagMarker( const wxString& number, const wxString& props) const { wxStringTokenizer prop_fields(props, ","); const wxString symbol = prop_fields.GetNextToken(); wxColour foreground; wxColour background; if (prop_fields.HasMoreTokens()) { foreground = prop_fields.GetNextToken(); if (prop_fields.HasMoreTokens()) { background = prop_fields.GetNextToken(); } } const int no = atoi(number.c_str()); const int symbol_no = atoi(symbol.c_str()); if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX) { return wxExMarker(no, symbol_no, foreground, background); } else { wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no); return wxExMarker(0, 0, foreground, background); } } const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const { wxString text; wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "property") { text += child->GetAttribute("name", "0") + "=" + child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL(); } else if (child->GetName() == "comment") { // Ignore comments. } else { wxLogError("Undefined properties tag: %s on %d", child->GetName().c_str(), child->GetLineNumber()); } child = child->GetNext(); } return text; } bool wxExLexers::Read() { if (!m_FileName.FileExists()) { return false; } wxXmlDocument doc; if (!doc.Load(m_FileName.GetFullPath())) { return false; } // Initialize members. m_Indicators.clear(); m_Lexers.clear(); m_Markers.clear(); m_Styles.clear(); m_StylesHex.clear(); wxXmlNode* child = doc.GetRoot()->GetChildren(); while (child) { if (child->GetName() == "global") { ParseTagGlobal(child); } else if (child->GetName() == "lexer") { const wxExLexer& lexer = ParseTagLexer(child); if (!lexer.GetScintillaLexer().empty()) { m_Lexers.push_back(lexer); } } child = child->GetNext(); } return true; } bool wxExLexers::ShowDialog( wxWindow* parent, wxExLexer& lexer, const wxString& caption) const { wxArrayString aChoices; int choice = -1; int index = 0; for ( std::vector<wxExLexer>::const_iterator it = m_Lexers.begin(); it != m_Lexers.end(); ++it) { aChoices.Add(it->GetScintillaLexer()); if (lexer.GetScintillaLexer() == it->GetScintillaLexer()) { choice = index; } index++; } const wxString no_lexer = "<none>"; aChoices.Add(no_lexer); if (lexer.GetScintillaLexer().empty()) { choice = index; } index++; wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices); if (choice != -1) { dlg.SetSelection(choice); } if (dlg.ShowModal() == wxID_CANCEL) { return false; } const wxString sel = dlg.GetStringSelection(); if (sel == no_lexer) { lexer = wxExLexer(); } else { lexer = FindByName(sel); } return true; } <|endoftext|>
<commit_before> // $Id: patch.C,v 1.4 2007-02-13 17:10:48 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <algorithm> // for std::fill #include <cmath> // for std::sqrt std::pow std::abs // Local Includes #include "libmesh_common.h" #include "libmesh_logging.h" #include "patch.h" #include "elem.h" //----------------------------------------------------------------- // Patch implementations void Patch::find_face_neighbors(std::set<const Elem *> &new_neighbors) { // Loop over all the elements in the patch std::set<const Elem*>::const_iterator it = this->begin(); const std::set<const Elem*>::const_iterator end = this->end(); for (; it != end; ++it) { const Elem* elem = *it; for (unsigned int s=0; s<elem->n_sides(); s++) if (elem->neighbor(s) != NULL) // we have a neighbor on this side { const Elem* neighbor = elem->neighbor(s); if (neighbor->active()) new_neighbors.insert (neighbor); // add active neighbors else // the neighbor is *not* active, { // so add *all* neighboring // active children to the patch std::vector<const Elem*> active_neighbor_children; neighbor->active_family_tree_by_neighbor (active_neighbor_children, elem); std::vector<const Elem*>::const_iterator child_it = active_neighbor_children.begin(); const std::vector<const Elem*>::const_iterator child_end = active_neighbor_children.end(); for (; child_it != child_end; ++child_it) new_neighbors.insert(*child_it); } } } } void Patch::add_face_neighbors() { START_LOG("add_face_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_face_neighbors(new_neighbors); this->insert(new_neighbors.begin(), new_neighbors.end()); STOP_LOG("add_face_neighbors()", "Patch"); } void Patch::add_local_face_neighbors() { START_LOG("add_local_face_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_face_neighbors(new_neighbors); std::set<const Elem*>::const_iterator it = new_neighbors.begin(); const std::set<const Elem*>::const_iterator end = new_neighbors.end(); for (; it != end; ++it) { const Elem* neighbor = *it; if (neighbor->processor_id() == libMesh::processor_id()) // ... if the neighbor belongs to this processor this->insert (neighbor); // ... then add it to the patch } this->insert(new_neighbors.begin(), new_neighbors.end()); STOP_LOG("add_local_face_neighbors()", "Patch"); } void Patch::find_point_neighbors(std::set<const Elem *> &new_neighbors) { // Loop over all the elements in the patch std::set<const Elem*>::const_iterator it = this->begin(); const std::set<const Elem*>::const_iterator end = this->end(); for (; it != end; ++it) { std::set<const Elem*> elem_point_neighbors; const Elem* elem = *it; elem->find_point_neighbors(elem_point_neighbors); new_neighbors.insert(elem_point_neighbors.begin(), elem_point_neighbors.end()); } } void Patch::add_point_neighbors() { START_LOG("add_point_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_point_neighbors(new_neighbors); this->insert(new_neighbors.begin(), new_neighbors.end()); STOP_LOG("add_point_neighbors()", "Patch"); } void Patch::add_local_point_neighbors() { START_LOG("add_local_point_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_point_neighbors(new_neighbors); std::set<const Elem*>::const_iterator it = new_neighbors.begin(); const std::set<const Elem*>::const_iterator end = new_neighbors.end(); for (; it != end; ++it) { const Elem* neighbor = *it; if (neighbor->processor_id() == libMesh::processor_id()) // ... if the neighbor belongs to this processor this->insert (neighbor); // ... then add it to the patch } STOP_LOG("add_local_point_neighbors()", "Patch"); } void Patch::build_around_element (const Elem* e0, const unsigned int target_patch_size, PMF patchtype) { START_LOG("build_around_element()", "Patch"); // Make sure we are building a patch for an active element. assert (e0 != NULL); assert (e0->active()); // Make sure we are either starting with a local element or // requesting a nonlocal patch assert ((patchtype != &Patch::add_local_face_neighbors && patchtype != &Patch::add_local_point_neighbors) || e0->processor_id() == libMesh::processor_id()); // First clear the current set, then add the element of interest. this->clear(); this->insert (e0); // Repeatedly add the neighbors of the elements in the patch until // the target patch size is met while (this->size() < target_patch_size) { // It is possible that the target patch size is larger than the number // of elements that can be added to the patch. Since we don't // have access to the Mesh object here, the only way we can // detect this case is by detecting a "stagnant patch," i.e. a // patch whose size does not increase after adding face neighbors const unsigned int old_patch_size = this->size(); // We profile the patch-extending functions separately PAUSE_LOG("build_around_element()", "Patch"); (this->*patchtype)(); RESTART_LOG("build_around_element()", "Patch"); // Check for a "stagnant" patch if (this->size() == old_patch_size) { std::cerr << "WARNING: stagnant patch of " << this->size() << " elements." << std::endl << "Does your target patch size exceed the number of elements in the mesh?" << std::endl; here(); break; } } // end while loop // make sure all the elements in the patch are active and local // if we are in debug mode #ifdef DEBUG { std::set<const Elem*>::const_iterator it = this->begin(); const std::set<const Elem*>::const_iterator end = this->end(); for (; it != end; ++it) { // Convenience. Keep the syntax simple. const Elem* elem = *it; assert (elem->active()); if ((patchtype == &Patch::add_local_face_neighbors || patchtype == &Patch::add_local_point_neighbors)) assert (elem->processor_id() == libMesh::processor_id()); } } #endif STOP_LOG("build_around_element()", "Patch"); } <commit_msg>Get rid of annoying warning<commit_after> // $Id: patch.C,v 1.5 2007-02-13 21:16:41 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <algorithm> // for std::fill #include <cmath> // for std::sqrt std::pow std::abs // Local Includes #include "libmesh_common.h" #include "libmesh_logging.h" #include "patch.h" #include "elem.h" //----------------------------------------------------------------- // Patch implementations void Patch::find_face_neighbors(std::set<const Elem *> &new_neighbors) { // Loop over all the elements in the patch std::set<const Elem*>::const_iterator it = this->begin(); const std::set<const Elem*>::const_iterator end = this->end(); for (; it != end; ++it) { const Elem* elem = *it; for (unsigned int s=0; s<elem->n_sides(); s++) if (elem->neighbor(s) != NULL) // we have a neighbor on this side { const Elem* neighbor = elem->neighbor(s); if (neighbor->active()) new_neighbors.insert (neighbor); // add active neighbors else // the neighbor is *not* active, { // so add *all* neighboring // active children to the patch std::vector<const Elem*> active_neighbor_children; neighbor->active_family_tree_by_neighbor (active_neighbor_children, elem); std::vector<const Elem*>::const_iterator child_it = active_neighbor_children.begin(); const std::vector<const Elem*>::const_iterator child_end = active_neighbor_children.end(); for (; child_it != child_end; ++child_it) new_neighbors.insert(*child_it); } } } } void Patch::add_face_neighbors() { START_LOG("add_face_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_face_neighbors(new_neighbors); this->insert(new_neighbors.begin(), new_neighbors.end()); STOP_LOG("add_face_neighbors()", "Patch"); } void Patch::add_local_face_neighbors() { START_LOG("add_local_face_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_face_neighbors(new_neighbors); std::set<const Elem*>::const_iterator it = new_neighbors.begin(); const std::set<const Elem*>::const_iterator end = new_neighbors.end(); for (; it != end; ++it) { const Elem* neighbor = *it; if (neighbor->processor_id() == libMesh::processor_id()) // ... if the neighbor belongs to this processor this->insert (neighbor); // ... then add it to the patch } this->insert(new_neighbors.begin(), new_neighbors.end()); STOP_LOG("add_local_face_neighbors()", "Patch"); } void Patch::find_point_neighbors(std::set<const Elem *> &new_neighbors) { // Loop over all the elements in the patch std::set<const Elem*>::const_iterator it = this->begin(); const std::set<const Elem*>::const_iterator end = this->end(); for (; it != end; ++it) { std::set<const Elem*> elem_point_neighbors; const Elem* elem = *it; elem->find_point_neighbors(elem_point_neighbors); new_neighbors.insert(elem_point_neighbors.begin(), elem_point_neighbors.end()); } } void Patch::add_point_neighbors() { START_LOG("add_point_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_point_neighbors(new_neighbors); this->insert(new_neighbors.begin(), new_neighbors.end()); STOP_LOG("add_point_neighbors()", "Patch"); } void Patch::add_local_point_neighbors() { START_LOG("add_local_point_neighbors()", "Patch"); std::set<const Elem *> new_neighbors; this->find_point_neighbors(new_neighbors); std::set<const Elem*>::const_iterator it = new_neighbors.begin(); const std::set<const Elem*>::const_iterator end = new_neighbors.end(); for (; it != end; ++it) { const Elem* neighbor = *it; if (neighbor->processor_id() == libMesh::processor_id()) // ... if the neighbor belongs to this processor this->insert (neighbor); // ... then add it to the patch } STOP_LOG("add_local_point_neighbors()", "Patch"); } void Patch::build_around_element (const Elem* e0, const unsigned int target_patch_size, PMF patchtype) { START_LOG("build_around_element()", "Patch"); // Make sure we are building a patch for an active element. assert (e0 != NULL); assert (e0->active()); // Make sure we are either starting with a local element or // requesting a nonlocal patch assert ((patchtype != &Patch::add_local_face_neighbors && patchtype != &Patch::add_local_point_neighbors) || e0->processor_id() == libMesh::processor_id()); // First clear the current set, then add the element of interest. this->clear(); this->insert (e0); // Repeatedly add the neighbors of the elements in the patch until // the target patch size is met while (this->size() < target_patch_size) { // It is possible that the target patch size is larger than the number // of elements that can be added to the patch. Since we don't // have access to the Mesh object here, the only way we can // detect this case is by detecting a "stagnant patch," i.e. a // patch whose size does not increase after adding face neighbors const unsigned int old_patch_size = this->size(); // We profile the patch-extending functions separately PAUSE_LOG("build_around_element()", "Patch"); (this->*patchtype)(); RESTART_LOG("build_around_element()", "Patch"); // Check for a "stagnant" patch if (this->size() == old_patch_size) { // std::cerr << "WARNING: stagnant patch of " // << this->size() << " elements." // << std::endl // << "Does your target patch size exceed the number of elements in the mesh?" // << std::endl; // here(); break; } } // end while loop // make sure all the elements in the patch are active and local // if we are in debug mode #ifdef DEBUG { std::set<const Elem*>::const_iterator it = this->begin(); const std::set<const Elem*>::const_iterator end = this->end(); for (; it != end; ++it) { // Convenience. Keep the syntax simple. const Elem* elem = *it; assert (elem->active()); if ((patchtype == &Patch::add_local_face_neighbors || patchtype == &Patch::add_local_point_neighbors)) assert (elem->processor_id() == libMesh::processor_id()); } } #endif STOP_LOG("build_around_element()", "Patch"); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); wizard = new Wizard(this); wizard->exec(); ui->room_view->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); ui->room_view->setFixedSize(wizard->getSize()); this->adjustSize(); world = new World(wizard->getName(), wizard->getSize()); world->addRoom("Example Room"); ui->room_view->setWorld(world); ui->rooms_list->setModel(world->rooms()); } MainWindow::~MainWindow() { delete ui; delete wizard; } <commit_msg>model is roomsModel()<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); wizard = new Wizard(this); wizard->exec(); ui->room_view->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); ui->room_view->setFixedSize(wizard->getSize()); this->adjustSize(); world = new World(wizard->getName(), wizard->getSize()); world->addRoom("Example Room"); ui->room_view->setWorld(world); ui->rooms_list->setModel(world->roomsModel()); } MainWindow::~MainWindow() { delete ui; delete wizard; } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/stat.h> #include <string.h> #include <atomic> #include "mailbox.h" using namespace std; Mailbox::Mailbox (){ //Attempt to create a new memory segment. controlID = shmget(controlKey, controlSize, S_IRUSR | S_IWUSR | IPC_CREAT); if (controlID == -1) { //Fatal error. Unknown error with shmget. exit(-1); } //Attach to the memory segment. controlPointer = (char*)shmat(controlID, NULL, 0); } Mailbox::~Mailbox (){ shmdt(controlPointer); shmctl(controlID, IPC_RMID, NULL); } void Mailbox::OpenUserBox(int Box){ OpenBoxes.push_back(Box); } void Mailbox::CloseUserBox(int Box){ for (int i = 0; i < OpenBoxes.size(); i++){ if (OpenBoxes[i] == Box){ OpenBoxes.erase(OpenBoxes.begin() + i); for (int j = 0; j < slotCount; j++){ ClearSlot(Box, j); } } } } bool Mailbox::SetupSuccessful(){ return (controlPointer != NULL); } void Mailbox::CheckMessages(){ if (LockInbox()){ for (int i = 1; i < inboxCount;i++){ if (CheckSlot(0,i)){ Inbox.push_back(GetMessage(0,i)); ClearSlot(0,i); } else { break; } } UnlockInbox(); } } bool Mailbox::LockInbox(){ //Attempt to lock Inbox. Success = Inbox was not locked. bool* LockLocation = controlPointer + InboxLock; return (!std::atomic_fetch_or(LockLocation, true)); } void Mailbox::UnlockInbox(){ bool* LockLocation = controlPointer + InboxLock; *LockLocation = 0x0; } string Mailbox::GetNextMessage(){ string RetVal = ""; CheckMessages(); if (Inbox.size() > 0){ RetVal = Inbox[0]; Inbox.erase(Inbox.begin()); } return RetVal; } void Mailbox::BroadcastMessage(string Message){ for (int i = 0; i < OpenBoxes.size(); i++){ SendMessageToBox(Message, i); } } void Mailbox::SendMessageToBox(std::string Message, int Box){ //Note: a full box results in a dropped message. for (int i = 1; i < slotCount; i++){ if (CheckSlot(Box, i)){ SetMessage(Box, i, Message); break; } } } bool Mailbox::CheckSlot(int Box, int Slot){ // For future reference - this is not server-side thread-safe, modify if expanding use to other programs. //To be thread safe, atomically reserve while checking (as we do with locking the Inbox.) char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } return (MemLoc[MessageSetFlag] == 0x0); } string Mailbox::GetMessage(int Box, int Slot){ char Buffer[slotSize]; char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } memcpy (&Buffer, MemLoc + FlagSetSize, slotSize - FlagSetSize); return (string(Buffer)); } void Mailbox::SetMessage(int Box, int Slot, string Message){ char Buffer[slotSize]; char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } *(MemLoc + MessageSetFlag) = 0x1; int MemSize = Message.size(); if (MemSize > slotSize - FlagSetSize) { MemSize = slotSize - FlagSetSize;} memcpy ( MemLoc + FlagSetSize, Message.c_str(), MemSize); } void Mailbox::ClearSlot (int Box, int Slot){ void* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } memset (MemLoc,'\0',slotSize); } int Mailbox::FindSlot(int Box){ for (int i = 1; i < boxSize; i++){ char* MemLoc = controlPointer + inboxSize + (Box * boxSize) + (i * slotSize); if (*(MemLoc + MessageSetFlag) == 0x0){ *(MemLoc + MessageSetFlag) = 0x1; return i; } } return 0; } <commit_msg>Update mailbox.cpp<commit_after>#include <string> #include <vector> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/stat.h> #include <string.h> #include <semaphore.h> #include <fcntl.h> #include "mailbox.h" using namespace std; Mailbox::Mailbox (){ bool Success = true; //Attempt to create a new memory segment. controlID = shmget(controlKey, controlSize, S_IRUSR | S_IWUSR | IPC_CREAT); if (controlID == -1) { //Fatal error. Unknown error with shmget. Success = false; } //Attach to the memory segment. controlPointer = (char*)shmat(controlID, NULL, 0); //Create the Inbox semaphore semID = sem_open (semName.c_str(), O_CREAT | O_EXCL, 0644, 1); if (semID == SEM_FAILED) { Success = false; } SetupOK = Success; } Mailbox::~Mailbox (){ shmdt(controlPointer); shmctl(controlID, IPC_RMID, NULL); sem_destroy (semID); } void Mailbox::OpenUserBox(int Box){ OpenBoxes.push_back(Box); } void Mailbox::CloseUserBox(int Box){ for (int i = 0; i < OpenBoxes.size(); i++){ if (OpenBoxes[i] == Box){ OpenBoxes.erase(OpenBoxes.begin() + i); for (int j = 0; j < slotCount; j++){ ClearSlot(Box, j); } } } } bool Mailbox::SetupSuccessful(){ return (SetupOK); } void Mailbox::CheckMessages(){ LockInbox(); for (int i = 1; i < inboxCount;i++){ if (CheckSlot(0,i)){ Inbox.push_back(GetMessage(0,i)); ClearSlot(0,i); } else { break; } } UnlockInbox(); } void Mailbox::LockInbox(){ // //Attempt to lock Inbox. Success = Inbox was not locked. // char* LockLocation = controlPointer + InboxLock; // bool Success = false; // // sem_wait(semID); // if (*LockLocation == 0x0){ // *LockLocation = 0x1; // Success = true; // } // sem_post(semID); // return (Success); sem_wait(semID); } void Mailbox::UnlockInbox(){ // char* LockLocation = controlPointer + InboxLock; // *LockLocation = 0x0; sem_post(semID); } string Mailbox::GetNextMessage(){ string RetVal = ""; CheckMessages(); if (Inbox.size() > 0){ RetVal = Inbox[0]; Inbox.erase(Inbox.begin()); } return RetVal; } void Mailbox::BroadcastMessage(string Message){ for (int i = 0; i < OpenBoxes.size(); i++){ SendMessageToBox(Message, i); } } void Mailbox::SendMessageToBox(std::string Message, int Box){ //Note: a full box results in a dropped message. for (int i = 1; i < slotCount; i++){ if (CheckSlot(Box, i)){ ClearSlot(Box, i); SetMessage(Box, i, Message); break; } } } bool Mailbox::CheckSlot(int Box, int Slot){ // For future reference - this is not server-side thread-safe, modify if expanding use to other programs. //To be thread safe, atomically reserve while checking (as we do with locking the Inbox.) char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } return (MemLoc[MessageSetFlag] == 0x0 || MemLoc[MessageReceivedFlag] == 0x1); } string Mailbox::GetMessage(int Box, int Slot){ char Buffer[slotSize]; char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } memcpy (&Buffer, MemLoc + FlagSetSize, slotSize - FlagSetSize); return (string(Buffer)); } void Mailbox::SetMessage(int Box, int Slot, string Message){ char Buffer[slotSize]; char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } *(MemLoc + MessageSetFlag) = 0x1; int MemSize = Message.size(); if (MemSize > slotSize - FlagSetSize) { MemSize = slotSize - FlagSetSize;} memcpy ( MemLoc + FlagSetSize, Message.c_str(), MemSize); } void Mailbox::ClearSlot (int Box, int Slot){ void* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } memset (MemLoc,'\0',slotSize); } int Mailbox::FindSlot(int Box){ for (int i = 1; i < boxSize; i++){ char* MemLoc = controlPointer + inboxSize + (Box * boxSize) + (i * slotSize); if (*(MemLoc + MessageSetFlag) == 0x0){ *(MemLoc + MessageSetFlag) = 0x1; return i; } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014, webvariants GmbH, http://www.webvariants.de * * This file is released under the terms of the MIT license. You can find the * complete text in the attached LICENSE file or online at: * * http://www.opensource.org/licenses/mit-license.php * * @author: Thomas Krause ([email protected]) */ #include "gtest/gtest.h" #include "events/global.h" #include <condition_variable> #include <chrono> #include "states/StateEventInterface.h" #include "iocontroller/IOController.h" class StateEventsTest : public ::testing::Test { protected: std::shared_ptr<Susi::States::StateController> controller{nullptr}; std::mutex mutex; bool callbackCalledOne = false; std::condition_variable condOne; bool callbackCalledTwo = false; std::condition_variable condTwo; virtual void SetUp() override { world.setupEventManager(); //world.setupHeartBeat(); world.setupIOController(); world.setupStateController(); controller = std::shared_ptr<Susi::States::StateController>(world.stateController); } virtual void TearDown() override { world.ioController->deletePath("./states.json"); } }; using namespace Susi::Events; TEST_F(StateEventsTest,setState){ auto event = createEvent("state::setState"); event->payload = Susi::Util::Any::Object{ {"stateID","foo"}, {"value","bar"} }; publish(std::move(event),[this](SharedEventPtr event){ EXPECT_NO_THROW ({ bool success = event->payload["success"]; EXPECT_TRUE(success); }); callbackCalledOne = true; condOne.notify_all(); }); { std::unique_lock<std::mutex> lk(mutex); condOne.wait_for(lk,std::chrono::milliseconds{100},[this](){return callbackCalledOne;}); EXPECT_TRUE(callbackCalledOne); } } TEST_F(StateEventsTest,setPersistentState){ auto event = createEvent("state::setPersistentState"); event->payload = Susi::Util::Any::Object{ {"stateID","foo"}, {"value","bar"} }; publish(std::move(event),[this](SharedEventPtr event){ EXPECT_NO_THROW ({ bool success = event->payload["success"]; EXPECT_TRUE(success); }); callbackCalledOne = true; condOne.notify_all(); }); { std::unique_lock<std::mutex> lk(mutex); condOne.wait_for(lk,std::chrono::milliseconds{100},[this](){return callbackCalledOne;}); EXPECT_TRUE(callbackCalledOne); } } TEST_F(StateEventsTest,getState){ controller->setState("foo","bar"); auto event = createEvent("state::getState"); event->payload = Susi::Util::Any::Object{ {"stateID","foo"}, }; publish(std::move(event),[this](SharedEventPtr event){ EXPECT_NO_THROW ({ Susi::Util::Any value = event->payload["value"]; std::string val = value; EXPECT_EQ("bar", val); }); callbackCalledOne = true; condOne.notify_all(); }); { std::unique_lock<std::mutex> lk(mutex); condOne.wait_for(lk,std::chrono::milliseconds{100},[this](){return callbackCalledOne;}); EXPECT_TRUE(callbackCalledOne); } } TEST_F(StateEventsTest,getPersistentState){ controller->setPersistentState("foo","bar"); auto event = createEvent("state::getPersistentState"); event->payload = Susi::Util::Any::Object{ {"stateID","foo"}, }; publish(std::move(event),[this](SharedEventPtr event){ EXPECT_NO_THROW ({ Susi::Util::Any value = event->payload["value"]; std::string val = value; EXPECT_EQ("bar", val); }); callbackCalledOne = true; condOne.notify_all(); }); { std::unique_lock<std::mutex> lk(mutex); condOne.wait_for(lk,std::chrono::milliseconds{100},[this](){return callbackCalledOne;}); EXPECT_TRUE(callbackCalledOne); } }<commit_msg>[StateController] removed old event test;<commit_after><|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MaterialData.h" #include "Material.h" MaterialData::MaterialData(MaterialPropertyStorage & storage) : _storage(storage), _n_qpoints(0), _swapped(false) { } MaterialData::~MaterialData() { release(); } void MaterialData::release() { _props.destroy(); _props_old.destroy(); _props_older.destroy(); } void MaterialData::resize(unsigned int n_qpoints) { if (n_qpoints == _n_qpoints) return; _props.resizeItems(n_qpoints); // if there are stateful material properties in the system, also resize // storage for old and older material properties if (_storage.hasStatefulProperties()) _props_old.resizeItems(n_qpoints); if (_storage.hasOlderProperties()) _props_older.resizeItems(n_qpoints); _n_qpoints = n_qpoints; } unsigned int MaterialData::nQPoints() { return _n_qpoints; } void MaterialData::copy(const Elem & elem_to, const Elem & elem_from, unsigned int side) { _storage.copy(*this, elem_to, elem_from, side, _n_qpoints); } void MaterialData::swap(const Elem & elem, unsigned int side/* = 0*/) { if (_storage.hasStatefulProperties()) { _storage.swap(*this, elem, side); _swapped = true; } } void MaterialData::reinit(const std::vector<std::shared_ptr<Material>> & mats) { for (const auto & mat : mats) mat->computeProperties(); } void MaterialData::reset(const std::vector<std::shared_ptr<Material>> & mats) { for (const auto & mat : mats) mat->resetProperties(); } void MaterialData::swapBack(const Elem & elem, unsigned int side/* = 0*/) { if (_swapped && _storage.hasStatefulProperties()) { _storage.swapBack(*this, elem, side); _swapped = false; } } bool MaterialData::isSwapped() { return _swapped; } <commit_msg>make materialdata safe when swap is called multiple times (e.g. via successive reinitMaterials calls without interleaving swapBackMaterials calls)<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "MaterialData.h" #include "Material.h" MaterialData::MaterialData(MaterialPropertyStorage & storage) : _storage(storage), _n_qpoints(0), _swapped(false) { } MaterialData::~MaterialData() { release(); } void MaterialData::release() { _props.destroy(); _props_old.destroy(); _props_older.destroy(); } void MaterialData::resize(unsigned int n_qpoints) { if (n_qpoints == _n_qpoints) return; _props.resizeItems(n_qpoints); // if there are stateful material properties in the system, also resize // storage for old and older material properties if (_storage.hasStatefulProperties()) _props_old.resizeItems(n_qpoints); if (_storage.hasOlderProperties()) _props_older.resizeItems(n_qpoints); _n_qpoints = n_qpoints; } unsigned int MaterialData::nQPoints() { return _n_qpoints; } void MaterialData::copy(const Elem & elem_to, const Elem & elem_from, unsigned int side) { _storage.copy(*this, elem_to, elem_from, side, _n_qpoints); } void MaterialData::swap(const Elem & elem, unsigned int side/* = 0*/) { if (!_storage.hasStatefulProperties() || _swapped) return; _storage.swap(*this, elem, side); _swapped = true; } void MaterialData::reinit(const std::vector<std::shared_ptr<Material>> & mats) { for (const auto & mat : mats) mat->computeProperties(); } void MaterialData::reset(const std::vector<std::shared_ptr<Material>> & mats) { for (const auto & mat : mats) mat->resetProperties(); } void MaterialData::swapBack(const Elem & elem, unsigned int side/* = 0*/) { if (_swapped && _storage.hasStatefulProperties()) { _storage.swapBack(*this, elem, side); _swapped = false; } } bool MaterialData::isSwapped() { return _swapped; } <|endoftext|>
<commit_before>/** * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <CsoundVST.hpp> #include <CsoundVstFltk.hpp> #include <cstdio> #include <cstdlib> int main(int argc, char **argv) { std::fprintf(stderr, "Starting CsoundVST...\n" ); #if defined(WIN32) HINSTANCE lib = LoadLibrary("CsoundVST.dll"); if(!lib) { DWORD lastError = GetLastError(); std::fprintf(stderr, "DLL load error: %d.\n", lastError); } std::fprintf(stderr, "lib = 0x%x\n", lib); AEffect* (*VSTPluginMain_)(audioMasterCallback audioMaster) = (AEffect* (*)(audioMasterCallback audioMaster)) GetProcAddress(lib, "VSTPluginMain"); std::fprintf(stderr, "VSTPluginMain = 0x%x\n", VSTPluginMain_); CsoundVST *(*CreateCsoundVST_)() = (CsoundVST *(*)()) GetProcAddress(lib, "CreateCsoundVST"); std::fprintf(stderr, "CreateCsoundVST_ = 0x%x\n", CreateCsoundVST_); #endif CsoundVST *csoundVST = CreateCsoundVST_(); std::fprintf(stderr, "csoundVST = 0x%x\n", (void*) csoundVST); AEffEditor *editor = csoundVST->getEditor(); editor->open(0); if(argc == 2) { csoundVST->openFile(argv[1]); } int status = csoundVST->fltkrun(); std::fprintf(stderr, "Quitting...\n"); } <commit_msg>New helper function to run CsoundVST in CsoundVSTShell -- MSVC 2008 doesn't seem to export vtbl properly.<commit_after>/** * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <CsoundVST.hpp> #include <CsoundVstFltk.hpp> #include <cstdio> #include <cstdlib> int main(int argc, char **argv) { #if defined(WIN32) HINSTANCE lib = LoadLibrary("CsoundVST.dll"); if(!lib) { DWORD lastError = GetLastError(); } void (*RunCsoundVST_)(const char *) = (void (*)(const char *)) GetProcAddress(lib, "RunCsoundVST"); #endif const char *filename = 0; if (argc > 1) { filename = argv[1]; } RunCsoundVST_(filename); } <|endoftext|>
<commit_before>#include "Connection.hpp" namespace et { Connection::Connection(std::shared_ptr<SocketHandler> _socketHandler, const string& _key) : socketHandler(_socketHandler), key(_key), shuttingDown(false) {} Connection::~Connection() { if (!shuttingDown) { LOG(ERROR) << "Call shutdown before destructing a Connection."; } closeSocket(); } inline bool isSkippableError() { return (errno == ECONNRESET || errno == ETIMEDOUT || errno == EAGAIN || errno == EWOULDBLOCK || errno == EHOSTUNREACH); } ssize_t Connection::read(void* buf, size_t count) { ssize_t bytesRead = reader->read(buf, count); if (bytesRead == -1) { if (isSkippableError()) { // The connection has reset, close the socket and invalidate, then // return 0 bytes LOG(INFO) << "Closing socket because " << errno << " " << strerror(errno); closeSocket(); bytesRead = 0; } } return bytesRead; } ssize_t Connection::readAll(void* buf, size_t count) { size_t pos = 0; while (pos < count && !shuttingDown) { ssize_t bytesRead = read(((char*)buf) + pos, count - pos); if (bytesRead < 0) { VLOG(1) << "Failed a call to readAll: %s\n" << strerror(errno); throw std::runtime_error("Failed a call to readAll"); } pos += bytesRead; if (pos < count) { // Yield the processor usleep(1000); } } return count; } ssize_t Connection::write(const void* buf, size_t count) { if (socketFd == -1) { return 0; } BackedWriterWriteState bwws = writer->write(buf, count); if (bwws == BackedWriterWriteState::SKIPPED) { return 0; } if (bwws == BackedWriterWriteState::WROTE_WITH_FAILURE) { // Error writing. if (!errno) { // The socket was already closed VLOG(1) << "Socket closed"; } else if (isSkippableError()) { VLOG(1) << " Connection is severed"; // The connection has been severed, handle and hide from the caller closeSocket(); } else { LOG(FATAL) << "Unexpected socket error: " << errno << " " << strerror(errno); } } return count; } void Connection::writeAll(const void* buf, size_t count) { while (!shuttingDown) { ssize_t bytesWritten = write(buf, count); if (bytesWritten > 0 && bytesWritten != (ssize_t)count) { LOG(FATAL) << "Somehow wrote a partial stream. This shouldn't happen"; } if (bytesWritten) { return; } usleep(1000); } } void Connection::closeSocket() { if (socketFd == -1) { LOG(ERROR) << "Tried to close a dead socket"; return; } reader->invalidateSocket(); writer->invalidateSocket(); socketHandler->close(socketFd); socketFd = -1; VLOG(1) << "Closed socket\n"; } bool Connection::recover(int newSocketFd) { LOG(INFO) << "Recovering..."; try { { // Write the current sequence number et::SequenceHeader sh; sh.set_sequencenumber(reader->getSequenceNumber()); socketHandler->writeProto(newSocketFd, sh, true); } // Read the remote sequence number et::SequenceHeader remoteHeader = socketHandler->readProto<et::SequenceHeader>(newSocketFd, true); { // Fetch the catchup bytes and send et::CatchupBuffer catchupBuffer; catchupBuffer.set_buffer(writer->recover(remoteHeader.sequencenumber())); socketHandler->writeProto(newSocketFd, catchupBuffer, true); } et::CatchupBuffer catchupBuffer = socketHandler->readProto<et::CatchupBuffer>(newSocketFd, true); socketFd = newSocketFd; reader->revive(socketFd, catchupBuffer.buffer()); writer->revive(socketFd); writer->unlock(); LOG(INFO) << "Finished recovering"; return true; } catch (const runtime_error& err) { LOG(ERROR) << "Error recovering: " << err.what(); socketHandler->close(newSocketFd); writer->unlock(); return false; } } void Connection::shutdown() { LOG(INFO) << "Shutting down connection"; shuttingDown = true; closeSocket(); } } <commit_msg>Fix race condition when closing a socket.<commit_after>#include "Connection.hpp" namespace et { Connection::Connection(std::shared_ptr<SocketHandler> _socketHandler, const string& _key) : socketHandler(_socketHandler), key(_key), shuttingDown(false) {} Connection::~Connection() { if (!shuttingDown) { LOG(ERROR) << "Call shutdown before destructing a Connection."; } closeSocket(); } inline bool isSkippableError() { return (errno == ECONNRESET || errno == ETIMEDOUT || errno == EAGAIN || errno == EWOULDBLOCK || errno == EHOSTUNREACH || errno == EBADF // Bad file descriptor can happen when // there's a race condition between ta thread // closing a connection and one // reading/writing. ); } ssize_t Connection::read(void* buf, size_t count) { ssize_t bytesRead = reader->read(buf, count); if (bytesRead == -1) { if (isSkippableError()) { // The connection has reset, close the socket and invalidate, then // return 0 bytes LOG(INFO) << "Closing socket because " << errno << " " << strerror(errno); closeSocket(); bytesRead = 0; } } return bytesRead; } ssize_t Connection::readAll(void* buf, size_t count) { size_t pos = 0; while (pos < count && !shuttingDown) { ssize_t bytesRead = read(((char*)buf) + pos, count - pos); if (bytesRead < 0) { VLOG(1) << "Failed a call to readAll: %s\n" << strerror(errno); throw std::runtime_error("Failed a call to readAll"); } pos += bytesRead; if (pos < count) { // Yield the processor usleep(1000); } } return count; } ssize_t Connection::write(const void* buf, size_t count) { if (socketFd == -1) { return 0; } BackedWriterWriteState bwws = writer->write(buf, count); if (bwws == BackedWriterWriteState::SKIPPED) { return 0; } if (bwws == BackedWriterWriteState::WROTE_WITH_FAILURE) { // Error writing. if (!errno) { // The socket was already closed VLOG(1) << "Socket closed"; } else if (isSkippableError()) { VLOG(1) << " Connection is severed"; // The connection has been severed, handle and hide from the caller closeSocket(); } else { LOG(FATAL) << "Unexpected socket error: " << errno << " " << strerror(errno); } } return count; } void Connection::writeAll(const void* buf, size_t count) { while (!shuttingDown) { ssize_t bytesWritten = write(buf, count); if (bytesWritten > 0 && bytesWritten != (ssize_t)count) { LOG(FATAL) << "Somehow wrote a partial stream. This shouldn't happen"; } if (bytesWritten) { return; } usleep(1000); } } void Connection::closeSocket() { if (socketFd == -1) { LOG(ERROR) << "Tried to close a dead socket"; return; } //TODO: There is a race condition where we invalidate and another //thread can try to read/write to the socket. For now we handle the //error but it would be better to avoid it. reader->invalidateSocket(); writer->invalidateSocket(); socketHandler->close(socketFd); socketFd = -1; VLOG(1) << "Closed socket\n"; } bool Connection::recover(int newSocketFd) { LOG(INFO) << "Recovering..."; try { { // Write the current sequence number et::SequenceHeader sh; sh.set_sequencenumber(reader->getSequenceNumber()); socketHandler->writeProto(newSocketFd, sh, true); } // Read the remote sequence number et::SequenceHeader remoteHeader = socketHandler->readProto<et::SequenceHeader>(newSocketFd, true); { // Fetch the catchup bytes and send et::CatchupBuffer catchupBuffer; catchupBuffer.set_buffer(writer->recover(remoteHeader.sequencenumber())); socketHandler->writeProto(newSocketFd, catchupBuffer, true); } et::CatchupBuffer catchupBuffer = socketHandler->readProto<et::CatchupBuffer>(newSocketFd, true); socketFd = newSocketFd; reader->revive(socketFd, catchupBuffer.buffer()); writer->revive(socketFd); writer->unlock(); LOG(INFO) << "Finished recovering"; return true; } catch (const runtime_error& err) { LOG(ERROR) << "Error recovering: " << err.what(); socketHandler->close(newSocketFd); writer->unlock(); return false; } } void Connection::shutdown() { LOG(INFO) << "Shutting down connection"; shuttingDown = true; closeSocket(); } } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #include "AliEveVZEROModuleEditor.h" #include <EveDet/AliEveVZEROModule.h> #include <AliVZERORawStream.h> #include <TEveGValuators.h> #include <TGSlider.h> //______________________________________________________________________________ // // Editor for AliEveVZEROModule. ClassImp(AliEveVZEROModuleEditor) AliEveVZEROModuleEditor::AliEveVZEROModuleEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options | kVerticalFrame, back), fM(0), fSampleIndex(NULL) { // Constructor. MakeTitle("AliEveVZEROModule"); fSampleIndex = new TEveGValuator(this,"Sample", 200, 0); fSampleIndex->SetNELength(4); fSampleIndex->SetLabelWidth(60); fSampleIndex->Build(); fSampleIndex->GetSlider()->SetWidth(120); fSampleIndex->SetLimits(0, AliVZERORawStream::kNEvOfInt-1, AliVZERORawStream::kNEvOfInt, TGNumberFormat::kNESInteger); fSampleIndex->Connect("ValueSet(Double_t)", "AliEveVZEROModuleEditor", this, "DoSampleIndex()"); AddFrame(fSampleIndex, new TGLayoutHints(kLHintsTop, 1, 1, 2, 1)); /* fSampleIndex = new TGNumberEntry(this, AliVZERORawStream::kNEvOfInt/2, 3, -1, TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative, TGNumberFormat::kNELLimitMinMax, 0,AliVZERORawStream::kNEvOfInt); AddFrame(fSampleIndex, new TGLayoutHints(kLHintsNormal, 10, 2, 0, 0)); fSampleIndex->Connect("ValueSet(Double_t)", "AliEveVZEROModuleEditor", this, "DoSampleIndex()"); fSampleIndex->SetText("ADC sample index (between 0 and 21)"); */ } /******************************************************************************/ void AliEveVZEROModuleEditor::SetModel(TObject* obj) { // Set model object. fM = dynamic_cast<AliEveVZEROModule*>(obj); fSampleIndex->SetValue(fM->GetSampleIndex()); } /******************************************************************************/ void AliEveVZEROModuleEditor::DoSampleIndex() { // Slot for SampleIndex. fM->SetSampleIndex((Int_t)fSampleIndex->GetValue()); Update(); } <commit_msg>Coverity<commit_after>/************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #include "AliEveVZEROModuleEditor.h" #include <EveDet/AliEveVZEROModule.h> #include <AliVZERORawStream.h> #include <TEveGValuators.h> #include <TGSlider.h> //______________________________________________________________________________ // // Editor for AliEveVZEROModule. ClassImp(AliEveVZEROModuleEditor) AliEveVZEROModuleEditor::AliEveVZEROModuleEditor(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options | kVerticalFrame, back), fM(0), fSampleIndex(NULL) { // Constructor. MakeTitle("AliEveVZEROModule"); fSampleIndex = new TEveGValuator(this,"Sample", 200, 0); fSampleIndex->SetNELength(4); fSampleIndex->SetLabelWidth(60); fSampleIndex->Build(); fSampleIndex->GetSlider()->SetWidth(120); fSampleIndex->SetLimits(0, AliVZERORawStream::kNEvOfInt-1, AliVZERORawStream::kNEvOfInt, TGNumberFormat::kNESInteger); fSampleIndex->Connect("ValueSet(Double_t)", "AliEveVZEROModuleEditor", this, "DoSampleIndex()"); AddFrame(fSampleIndex, new TGLayoutHints(kLHintsTop, 1, 1, 2, 1)); /* fSampleIndex = new TGNumberEntry(this, AliVZERORawStream::kNEvOfInt/2, 3, -1, TGNumberFormat::kNESInteger, TGNumberFormat::kNEANonNegative, TGNumberFormat::kNELLimitMinMax, 0,AliVZERORawStream::kNEvOfInt); AddFrame(fSampleIndex, new TGLayoutHints(kLHintsNormal, 10, 2, 0, 0)); fSampleIndex->Connect("ValueSet(Double_t)", "AliEveVZEROModuleEditor", this, "DoSampleIndex()"); fSampleIndex->SetText("ADC sample index (between 0 and 21)"); */ } /******************************************************************************/ void AliEveVZEROModuleEditor::SetModel(TObject* obj) { // Set model object. fM = static_cast<AliEveVZEROModule*>(obj); fSampleIndex->SetValue(fM->GetSampleIndex()); } /******************************************************************************/ void AliEveVZEROModuleEditor::DoSampleIndex() { // Slot for SampleIndex. fM->SetSampleIndex((Int_t)fSampleIndex->GetValue()); Update(); } <|endoftext|>
<commit_before>/** @file SuccessScene.cpp */ #include "LevelInfo.h" #include "SaveData.h" #include "Scene.h" #include "../Menu.h" #include "../../OpenGLESApp2/OpenGLESApp2.Android.NativeActivity/Renderer.h" #include <vector> #include <random> namespace SunnySideUp { using namespace Mai; /** Show the success event. */ class SuccessScene : public Scene { public: SuccessScene(); virtual ~SuccessScene() {} virtual int Update(Engine&, float); virtual bool Load(Engine&); virtual bool Unload(Engine&); virtual void Draw(Engine&); virtual void ProcessWindowEvent(Engine&, const Event&); private: static const int eventTime = 60; static const int enableInputTime = eventTime - 5; int DoUpdate(Engine&, float); int DoFadeOut(Engine&, float); int(SuccessScene::*updateFunc)(Engine&, float); std::vector<ObjectPtr> objList; bool loaded; bool hasFinishRequest; bool hasNewRecord; float timer; float cameraRotation; Menu::Menu rootMenu; }; SuccessScene::SuccessScene() : updateFunc(&SuccessScene::DoUpdate) , objList() , loaded(false) , hasFinishRequest(false) , hasNewRecord(false) , timer(static_cast<float>(eventTime)) , cameraRotation(0) {} bool SuccessScene::Load(Engine& engine) { if (loaded) { status = STATUSCODE_RUNNABLE; return true; } const CommonData* pCommonData = engine.GetCommonData<CommonData>(); hasNewRecord = SaveData::SetNewRecord(engine.GetWindow(), pCommonData->level, pCommonData->courseNo, pCommonData->currentTime); objList.reserve(8); Renderer& r = engine.GetRenderer(); const Vector3F shadowDir = GetSunRayDirection(r.GetTimeOfScene()); r.SetShadowLight(Position3F(0, 0, 0) - shadowDir * 200.0f, shadowDir, 150, 250, Vector2F(3, 3 * 4)); r.DoesDrawSkybox(false); { auto obj = r.CreateObject("FlyingPan", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); obj->SetScale(Vector3F(10, 10, 10)); obj->SetTranslation(Vector3F(0, 1.25f, 0)); objList.push_back(obj); } { static const char* const cookingNameList[] = { "SunnySideUp", "SunnySideUp01", "OverMedium", }; boost::random::mt19937 random(static_cast<uint32_t>(time(nullptr))); const int n = std::uniform_int_distribution<>(0, sizeof(cookingNameList) / sizeof(cookingNameList[0]) - 1)(random); auto obj = r.CreateObject(cookingNameList[n], Material(Color4B(255, 255, 255, 255), 0, 0), "defaultWithAlpha"); obj->SetScale(Vector3F(7, 7, 7)); obj->SetTranslation(Vector3F(0, 2.5f, 0)); objList.push_back(obj); } { auto obj = r.CreateObject("landscape", Material(Color4B(255, 255, 255, 255), 0, 0), "solidmodel" , ShadowCapability::Disable); obj->SetScale(Vector3F(12, 1, 12)); obj->SetTranslation(Vector3F(0, -4, 0)); objList.push_back(obj); } { // for shadow. auto obj = r.CreateObject("ground", Material(Color4B(255, 255, 255, 255), 0, 0), "default", ShadowCapability::ShadowOnly); obj->SetTranslation(Vector3F(0, -3, 0)); obj->SetScale(Vector3F(0.01f, 0.01f, 0.01f)); obj->SetRotation(degreeToRadian(-90.0f), 0, 0); objList.push_back(obj); } float scale = 1.0f; rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("THAT'S YUMMY!", Vector2F(0.5f, 0.25f), scale, Color4B(250, 250, 250, 255)))); if (hasNewRecord) { rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("NEW RECORD!", Vector2F(0.5f, 0.675f), scale, Color4B(250, 100, 50, 255), Menu::TextMenuItem::FLAG_ALPHA_ANIMATION))); } rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("YOUR TIME IS:", Vector2F(0.5f, 0.75f), scale, Color4B(250, 250, 250, 255)))); { const float time = static_cast<float>(engine.GetCommonData<CommonData>()->currentTime) / 1000.0f; char buf[32]; sprintf(buf, "%03.3fSec", time); rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem(buf, Vector2F(0.5f, 0.825f), scale, Color4B(250, 250, 250, 255)))); } if (pCommonData->courseNo >= GetMaximumCourseNo(pCommonData->level)) { rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("LEVEL CLEAR", Vector2F(0.5f, 0.9f), 1.2f * scale, Color4B(100, 100, 250, 255), Menu::TextMenuItem::FLAG_ALPHA_ANIMATION))); } loaded = true; status = STATUSCODE_RUNNABLE; return true; } bool SuccessScene::Unload(Engine&) { if (loaded) { objList.clear(); loaded = false; } rootMenu.Clear(); status = STATUSCODE_STOPPED; return true; } void SuccessScene::ProcessWindowEvent(Engine&, const Event& e) { switch (e.Type) { case Event::EVENT_MOUSE_BUTTON_PRESSED: if ((timer <= enableInputTime) && (e.MouseButton.Button == MOUSEBUTTON_LEFT)) { hasFinishRequest = true; } break; default: /* DO NOTING */ break; } } int SuccessScene::Update(Engine& engine, float tick) { for (auto e : objList) { e->Update(tick); } rootMenu.Update(tick); const float theta = degreeToRadian<float>(cameraRotation); const float distance = 25; const float x = std::cos(theta) * distance; const float z = std::sin(theta) * distance; const Position3F eyePos(x, 20, z); const Vector3F dir = objList[1]->Position() - eyePos; engine.GetRenderer().Update(tick, eyePos, dir, Vector3F(0, 1, 0)); cameraRotation += tick * 10.0f; while (cameraRotation >= 360.0f) { cameraRotation -= 360.0f; } return (this->*updateFunc)(engine, tick); } /** Wait user input. Transition to DoFadeOut() when receive user input or time out. This is the update function called from Update(). */ int SuccessScene::DoUpdate(Engine& engine, float tick) { timer -= tick; if ((timer <= 0.0f) || hasFinishRequest) { engine.GetRenderer().FadeOut(Color4B(0, 0, 0, 0), 1.0f); updateFunc = &SuccessScene::DoFadeOut; } return SCENEID_CONTINUE; } /** Do fade out. Transition to the scene of the success/failure event when the fadeout finished. This is the update function called from Update(). */ int SuccessScene::DoFadeOut(Engine& engine, float deltaTime) { Renderer& r = engine.GetRenderer(); if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) { r.FadeIn(1.0f); CommonData& commonData = *engine.GetCommonData<CommonData>(); if (++commonData.courseNo > GetMaximumCourseNo(commonData.level)) { commonData.level = std::min(commonData.level + 1, GetMaximumLevel()); commonData.courseNo = 0; return SCENEID_TITLE; } return SCENEID_MAINGAME; } return SCENEID_CONTINUE; } void SuccessScene::Draw(Engine& engine) { Renderer& r = engine.GetRenderer(); rootMenu.Draw(r, Vector2F(0, 0), 1.0f); r.Render(&objList[0], &objList[0] + objList.size()); } ScenePtr CreateSuccessScene(Engine&) { return ScenePtr(new SuccessScene()); } } // namespace SunnySideUp<commit_msg>Close the distance between frypan and egg.<commit_after>/** @file SuccessScene.cpp */ #include "LevelInfo.h" #include "SaveData.h" #include "Scene.h" #include "../Menu.h" #include "../../OpenGLESApp2/OpenGLESApp2.Android.NativeActivity/Renderer.h" #include <vector> #include <random> namespace SunnySideUp { using namespace Mai; /** Show the success event. */ class SuccessScene : public Scene { public: SuccessScene(); virtual ~SuccessScene() {} virtual int Update(Engine&, float); virtual bool Load(Engine&); virtual bool Unload(Engine&); virtual void Draw(Engine&); virtual void ProcessWindowEvent(Engine&, const Event&); private: static const int eventTime = 60; static const int enableInputTime = eventTime - 5; int DoUpdate(Engine&, float); int DoFadeOut(Engine&, float); int(SuccessScene::*updateFunc)(Engine&, float); std::vector<ObjectPtr> objList; bool loaded; bool hasFinishRequest; bool hasNewRecord; float timer; float cameraRotation; Menu::Menu rootMenu; }; SuccessScene::SuccessScene() : updateFunc(&SuccessScene::DoUpdate) , objList() , loaded(false) , hasFinishRequest(false) , hasNewRecord(false) , timer(static_cast<float>(eventTime)) , cameraRotation(0) {} bool SuccessScene::Load(Engine& engine) { if (loaded) { status = STATUSCODE_RUNNABLE; return true; } const CommonData* pCommonData = engine.GetCommonData<CommonData>(); hasNewRecord = SaveData::SetNewRecord(engine.GetWindow(), pCommonData->level, pCommonData->courseNo, pCommonData->currentTime); objList.reserve(8); Renderer& r = engine.GetRenderer(); const Vector3F shadowDir = GetSunRayDirection(r.GetTimeOfScene()); r.SetShadowLight(Position3F(0, 0, 0) - shadowDir * 200.0f, shadowDir, 150, 250, Vector2F(3, 3 * 4)); r.DoesDrawSkybox(false); { auto obj = r.CreateObject("FlyingPan", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); obj->SetScale(Vector3F(10, 10, 10)); obj->SetTranslation(Vector3F(0, 1.25f, 0)); objList.push_back(obj); } { static const char* const cookingNameList[] = { "SunnySideUp", "SunnySideUp01", "OverMedium", }; boost::random::mt19937 random(static_cast<uint32_t>(time(nullptr))); const int n = std::uniform_int_distribution<>(0, sizeof(cookingNameList) / sizeof(cookingNameList[0]) - 1)(random); auto obj = r.CreateObject(cookingNameList[n], Material(Color4B(255, 255, 255, 255), 0, 0), "defaultWithAlpha"); obj->SetScale(Vector3F(7, 7, 7)); obj->SetTranslation(Vector3F(0, 2.0f, 0)); objList.push_back(obj); } { auto obj = r.CreateObject("landscape", Material(Color4B(255, 255, 255, 255), 0, 0), "solidmodel" , ShadowCapability::Disable); obj->SetScale(Vector3F(12, 1, 12)); obj->SetTranslation(Vector3F(0, -4, 0)); objList.push_back(obj); } { // for shadow. auto obj = r.CreateObject("ground", Material(Color4B(255, 255, 255, 255), 0, 0), "default", ShadowCapability::ShadowOnly); obj->SetTranslation(Vector3F(0, -3, 0)); obj->SetScale(Vector3F(0.01f, 0.01f, 0.01f)); obj->SetRotation(degreeToRadian(-90.0f), 0, 0); objList.push_back(obj); } float scale = 1.0f; rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("THAT'S YUMMY!", Vector2F(0.5f, 0.25f), scale, Color4B(250, 250, 250, 255)))); if (hasNewRecord) { rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("NEW RECORD!", Vector2F(0.5f, 0.675f), scale, Color4B(250, 100, 50, 255), Menu::TextMenuItem::FLAG_ALPHA_ANIMATION))); } rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("YOUR TIME IS:", Vector2F(0.5f, 0.75f), scale, Color4B(250, 250, 250, 255)))); { const float time = static_cast<float>(engine.GetCommonData<CommonData>()->currentTime) / 1000.0f; char buf[32]; sprintf(buf, "%03.3fSec", time); rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem(buf, Vector2F(0.5f, 0.825f), scale, Color4B(250, 250, 250, 255)))); } if (pCommonData->courseNo >= GetMaximumCourseNo(pCommonData->level)) { rootMenu.Add(Menu::MenuItem::Pointer(new Menu::TextMenuItem("LEVEL CLEAR", Vector2F(0.5f, 0.9f), 1.2f * scale, Color4B(100, 100, 250, 255), Menu::TextMenuItem::FLAG_ALPHA_ANIMATION))); } loaded = true; status = STATUSCODE_RUNNABLE; return true; } bool SuccessScene::Unload(Engine&) { if (loaded) { objList.clear(); loaded = false; } rootMenu.Clear(); status = STATUSCODE_STOPPED; return true; } void SuccessScene::ProcessWindowEvent(Engine&, const Event& e) { switch (e.Type) { case Event::EVENT_MOUSE_BUTTON_PRESSED: if ((timer <= enableInputTime) && (e.MouseButton.Button == MOUSEBUTTON_LEFT)) { hasFinishRequest = true; } break; default: /* DO NOTING */ break; } } int SuccessScene::Update(Engine& engine, float tick) { for (auto e : objList) { e->Update(tick); } rootMenu.Update(tick); const float theta = degreeToRadian<float>(cameraRotation); const float distance = 25; const float x = std::cos(theta) * distance; const float z = std::sin(theta) * distance; const Position3F eyePos(x, 20, z); const Vector3F dir = objList[1]->Position() - eyePos; engine.GetRenderer().Update(tick, eyePos, dir, Vector3F(0, 1, 0)); cameraRotation += tick * 10.0f; while (cameraRotation >= 360.0f) { cameraRotation -= 360.0f; } return (this->*updateFunc)(engine, tick); } /** Wait user input. Transition to DoFadeOut() when receive user input or time out. This is the update function called from Update(). */ int SuccessScene::DoUpdate(Engine& engine, float tick) { timer -= tick; if ((timer <= 0.0f) || hasFinishRequest) { engine.GetRenderer().FadeOut(Color4B(0, 0, 0, 0), 1.0f); updateFunc = &SuccessScene::DoFadeOut; } return SCENEID_CONTINUE; } /** Do fade out. Transition to the scene of the success/failure event when the fadeout finished. This is the update function called from Update(). */ int SuccessScene::DoFadeOut(Engine& engine, float deltaTime) { Renderer& r = engine.GetRenderer(); if (r.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) { r.FadeIn(1.0f); CommonData& commonData = *engine.GetCommonData<CommonData>(); if (++commonData.courseNo > GetMaximumCourseNo(commonData.level)) { commonData.level = std::min(commonData.level + 1, GetMaximumLevel()); commonData.courseNo = 0; return SCENEID_TITLE; } return SCENEID_MAINGAME; } return SCENEID_CONTINUE; } void SuccessScene::Draw(Engine& engine) { Renderer& r = engine.GetRenderer(); rootMenu.Draw(r, Vector2F(0, 0), 1.0f); r.Render(&objList[0], &objList[0] + objList.size()); } ScenePtr CreateSuccessScene(Engine&) { return ScenePtr(new SuccessScene()); } } // namespace SunnySideUp<|endoftext|>
<commit_before>// // brainCloudClientObjc.hh // brainCloudClientObjc // // Copyright (c) 2016 bitHeads. All rights reserved. // #pragma once //#import <UIKit/UIKit.h> //! Project version number for brainCloudClientObjc. //FOUNDATION_EXPORT double brainCloudClientObjcVersionNumber; //! Project version string for brainCloudClientObjc. //FOUNDATION_EXPORT const unsigned char brainCloudClientObjcVersionString[]; // In this header, you should import all the public headers of your framework // using statements like #import <brainCloudClientObjc/PublicHeader.h> #import "BrainCloudAsyncMatch.hh" #import "BrainCloudAuthentication.hh" #import "BrainCloudClient.hh" #import "BrainCloudEntity.hh" #import "BrainCloudEvent.hh" #import "BrainCloudFile.hh" #import "BrainCloudFriend.hh" #import "BrainCloudGamification.hh" #import "BrainCloudGlobalApp.hh" #import "BrainCloudGlobalEntity.hh" #import "BrainCloudGlobalStatistics.hh" #import "BrainCloudGroup.hh" #import "BrainCloudIdentity.hh" #import "BrainCloudLeaderboard.hh" #import "BrainCloudMail.hh" #import "BrainCloudMatchMaking.hh" #import "BrainCloudOneWayMatch.hh" #import "BrainCloudPlaybackStream.hh" #import "BrainCloudPlayerState.hh" #import "BrainCloudPlayerStatistics.hh" #import "BrainCloudPlayerStatisticsEvent.hh" #import "BrainCloudPresence.hh" #import "BrainCloudTournament.hh" #import "BrainCloudProduct.hh" #import "BrainCloudProfanity.hh" #import "BrainCloudPushNotification.hh" #import "BrainCloudRedemptionCode.hh" #import "BrainCloudS3Handling.hh" #import "BrainCloudScript.hh" #import "BrainCloudTime.hh" #import "BrainCloudVirtualCurrency" #import "BrainCloudAppStore" #import "PlatformObjc.hh" #import "ReasonCodes.hh" #import "ServiceName.hh" #import "ServiceOperation.hh" <commit_msg>adding the two missing .hh in brainCloudClientObjc.hh<commit_after>// // brainCloudClientObjc.hh // brainCloudClientObjc // // Copyright (c) 2016 bitHeads. All rights reserved. // #pragma once //#import <UIKit/UIKit.h> //! Project version number for brainCloudClientObjc. //FOUNDATION_EXPORT double brainCloudClientObjcVersionNumber; //! Project version string for brainCloudClientObjc. //FOUNDATION_EXPORT const unsigned char brainCloudClientObjcVersionString[]; // In this header, you should import all the public headers of your framework // using statements like #import <brainCloudClientObjc/PublicHeader.h> #import "BrainCloudAsyncMatch.hh" #import "BrainCloudAuthentication.hh" #import "BrainCloudClient.hh" #import "BrainCloudEntity.hh" #import "BrainCloudEvent.hh" #import "BrainCloudFile.hh" #import "BrainCloudFriend.hh" #import "BrainCloudGamification.hh" #import "BrainCloudGlobalApp.hh" #import "BrainCloudGlobalEntity.hh" #import "BrainCloudGlobalStatistics.hh" #import "BrainCloudGroup.hh" #import "BrainCloudIdentity.hh" #import "BrainCloudLeaderboard.hh" #import "BrainCloudMail.hh" #import "BrainCloudMatchMaking.hh" #import "BrainCloudOneWayMatch.hh" #import "BrainCloudPlaybackStream.hh" #import "BrainCloudPlayerState.hh" #import "BrainCloudPlayerStatistics.hh" #import "BrainCloudPlayerStatisticsEvent.hh" #import "BrainCloudPresence.hh" #import "BrainCloudTournament.hh" #import "BrainCloudProduct.hh" #import "BrainCloudProfanity.hh" #import "BrainCloudPushNotification.hh" #import "BrainCloudRedemptionCode.hh" #import "BrainCloudS3Handling.hh" #import "BrainCloudScript.hh" #import "BrainCloudTime.hh" #import "BrainCloudVirtualCurrency.hh" #import "BrainCloudAppStore.hh" #import "PlatformObjc.hh" #import "ReasonCodes.hh" #import "ServiceName.hh" #import "ServiceOperation.hh" <|endoftext|>
<commit_before>/* * This file is part of the FreeStreamer project, * (C)Copyright 2011 Matias Muhonen <[email protected]> * See the file ''LICENSE'' for using the code. */ #include "http_stream.h" #include "audio_queue.h" namespace astreamer { const size_t HTTP_Stream::STREAM_BUFSIZ = Audio_Queue::AQ_BUFSIZ; CFStringRef HTTP_Stream::httpRequestMethod = CFSTR("GET"); CFStringRef HTTP_Stream::httpUserAgentHeader = CFSTR("User-Agent"); CFStringRef HTTP_Stream::httpUserAgentValue = CFSTR("aStreamer/1.0"); CFStringRef HTTP_Stream::httpRangeHeader = CFSTR("Range"); CFStringRef HTTP_Stream::icyMetaDataHeader = CFSTR("Icy-MetaData"); CFStringRef HTTP_Stream::icyMetaDataValue = CFSTR("1"); /* always request ICY metadata, if available */ /* HTTP_Stream: public */ HTTP_Stream::HTTP_Stream() : m_readStream(0), m_scheduledInRunLoop(false), m_delegate(0), m_url(0), m_httpHeadersParsed(false), m_contentLength(0), m_icyStream(false), m_icyHeaderCR(false), m_icyHeadersRead(false), m_icyHeadersParsed(false), m_icyMetaDataInterval(0), m_dataByteReadCount(0), m_metaDataBytesRemaining(0), m_httpReadBuffer(0), m_icyReadBuffer(0) { } HTTP_Stream::~HTTP_Stream() { close(); if (m_httpReadBuffer) { delete m_httpReadBuffer, m_httpReadBuffer = 0; } if (m_icyReadBuffer) { delete m_icyReadBuffer, m_icyReadBuffer = 0; } if (m_url) { CFRelease(m_url), m_url = 0; } } HTTP_Stream_Position HTTP_Stream::position() { return m_position; } std::string HTTP_Stream::contentType() { return m_contentType; } size_t HTTP_Stream::contentLength() { return m_contentLength; } bool HTTP_Stream::open() { HTTP_Stream_Position position; position.start = 0; position.end = 0; return open(position); } bool HTTP_Stream::open(const HTTP_Stream_Position& position) { bool success = false; CFStreamClientContext CTX = { 0, this, NULL, NULL, NULL }; /* Already opened a read stream, return */ if (m_readStream) { goto out; } /* Reset state */ m_position = position; m_httpHeadersParsed = false; m_contentType = ""; m_icyStream = false; m_icyHeaderCR = false; m_icyHeadersRead = false; m_icyHeadersParsed = false; m_icyHeaderLines.clear(); m_icyMetaDataInterval = 0; m_dataByteReadCount = 0; m_metaDataBytesRemaining = 0; m_icyMetaData = ""; /* Failed to create a stream */ if (!(m_readStream = createReadStream(m_url))) { goto out; } if (!CFReadStreamSetClient(m_readStream, kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred, readCallBack, &CTX)) { CFRelease(m_readStream), m_readStream = 0; goto out; } setScheduledInRunLoop(true); if (!CFReadStreamOpen(m_readStream)) { /* Open failed: clean */ CFReadStreamSetClient(m_readStream, 0, NULL, NULL); setScheduledInRunLoop(false); CFRelease(m_readStream), m_readStream = 0; goto out; } success = true; out: return success; } void HTTP_Stream::close() { /* The stream has been already closed */ if (!m_readStream) { return; } CFReadStreamSetClient(m_readStream, 0, NULL, NULL); setScheduledInRunLoop(false); CFReadStreamClose(m_readStream); CFRelease(m_readStream), m_readStream = 0; } void HTTP_Stream::setScheduledInRunLoop(bool scheduledInRunLoop) { /* The stream has not been opened, or it has been already closed */ if (!m_readStream) { return; } /* The state doesn't change */ if (m_scheduledInRunLoop == scheduledInRunLoop) { return; } if (m_scheduledInRunLoop) { CFReadStreamUnscheduleFromRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); } else { CFReadStreamScheduleWithRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); } m_scheduledInRunLoop = scheduledInRunLoop; } void HTTP_Stream::setUrl(CFURLRef url) { if (m_url) { CFRelease(m_url); } m_url = (CFURLRef)CFRetain(url); } /* private */ CFReadStreamRef HTTP_Stream::createReadStream(CFURLRef url) { CFReadStreamRef readStream = 0; CFHTTPMessageRef request; CFDictionaryRef proxySettings; if (!(request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, httpRequestMethod, url, kCFHTTPVersion1_1))) { goto out; } CFHTTPMessageSetHeaderFieldValue(request, httpUserAgentHeader, httpUserAgentValue); CFHTTPMessageSetHeaderFieldValue(request, icyMetaDataHeader, icyMetaDataValue); if (m_position.start > 0 && m_position.end > m_position.start) { CFStringRef rangeHeaderValue = CFStringCreateWithFormat(NULL, NULL, CFSTR("bytes=%lu-%lu"), m_position.start, m_position.end); CFHTTPMessageSetHeaderFieldValue(request, httpRangeHeader, rangeHeaderValue); CFRelease(rangeHeaderValue); } if (!(readStream = CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request, 0))) { goto out; } CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue); proxySettings = CFNetworkCopySystemProxySettings(); CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPProxy, proxySettings); CFRelease(proxySettings); out: if (request) { CFRelease(request); } return readStream; } void HTTP_Stream::parseHttpHeadersIfNeeded(UInt8 *buf, CFIndex bufSize) { if (m_httpHeadersParsed) { return; } m_httpHeadersParsed = true; /* If the response has the "ICY 200 OK" string, * we are dealing with the ShoutCast protocol. * The HTTP headers won't be available. */ std::string header; for (CFIndex k=0; k < bufSize; k++) { UInt8 c = buf[k]; // Ignore non-ASCII chars if (c < 32 || c > 126) { continue; } header.push_back(c); } char *p = strstr(header.c_str(), "ICY 200 OK"); // This is an ICY stream, don't try to parse the HTTP headers if (p) { m_icyStream = true; return; } CFHTTPMessageRef response = (CFHTTPMessageRef)CFReadStreamCopyProperty(m_readStream, kCFStreamPropertyHTTPResponseHeader); if (response) { /* * If the server responded with the icy-metaint header, the response * body will be encoded in the ShoutCast protocol. */ CFStringRef icyMetaIntString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("icy-metaint")); if (icyMetaIntString) { m_icyStream = true; m_icyHeadersParsed = true; m_icyHeadersRead = true; m_icyMetaDataInterval = CFStringGetIntValue(icyMetaIntString); CFRelease(icyMetaIntString); } CFStringRef contentTypeString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Type")); if (contentTypeString) { CFIndex len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(contentTypeString), kCFStringEncodingUTF8) + 1; char *buf = new char[len]; if (CFStringGetCString(contentTypeString, buf, len, kCFStringEncodingUTF8)) { m_contentType.append(buf); } delete[] buf; CFRelease(contentTypeString); } CFStringRef contentLengthString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Length")); if (contentLengthString) { m_contentLength = CFStringGetIntValue(contentLengthString); CFRelease(contentLengthString); } CFRelease(response); } if (m_delegate) { m_delegate->streamIsReadyRead(); } } void HTTP_Stream::parseICYStream(UInt8 *buf, CFIndex bufSize) { CFIndex offset = 0; if (!m_icyHeadersRead) { // TODO: fail after n tries? for (; offset < bufSize; offset++) { if (m_icyHeaderCR && buf[offset] == '\n') { m_icyHeaderLines.push_back(std::string("")); size_t n = m_icyHeaderLines.size(); /* If the last two lines were empty, we have reached the end of the headers */ if (n >= 2) { if (m_icyHeaderLines[n-2].empty() && m_icyHeaderLines[n-1].empty()) { m_icyHeadersRead = true; break; } } continue; } if (buf[offset] == '\r') { m_icyHeaderCR = true; continue; } else { m_icyHeaderCR = false; } size_t numberOfLines = m_icyHeaderLines.size(); if (numberOfLines == 0) { continue; } m_icyHeaderLines[numberOfLines - 1].push_back(buf[offset]); } } else if (!m_icyHeadersParsed) { const char *icyContentTypeHeader = "content-type:"; const char *icyMetaDataHeader = "icy-metaint:"; size_t icyContenTypeHeaderLength = strlen(icyContentTypeHeader); size_t icyMetaDataHeaderLength = strlen(icyMetaDataHeader); for (std::vector<std::string>::iterator h = m_icyHeaderLines.begin(); h != m_icyHeaderLines.end(); ++h) { if (h->compare(0, icyContenTypeHeaderLength, icyContentTypeHeader) == 0) { m_contentType = h->substr(icyContenTypeHeaderLength, h->length() - icyContenTypeHeaderLength); } if (h->compare(0, icyMetaDataHeaderLength, icyMetaDataHeader) == 0) { m_icyMetaDataInterval = atoi(h->substr(icyMetaDataHeaderLength, h->length() - icyMetaDataHeaderLength).c_str()); } } m_icyHeadersParsed = true; offset++; if (m_delegate) { m_delegate->streamIsReadyRead(); } } if (!m_icyReadBuffer) { m_icyReadBuffer = new UInt8[STREAM_BUFSIZ]; } size_t i=0; for (; offset < bufSize; offset++) { // is this a metadata byte? if (m_metaDataBytesRemaining > 0) { m_metaDataBytesRemaining--; if (m_metaDataBytesRemaining == 0) { m_dataByteReadCount = 0; if (m_delegate && !m_icyMetaData.empty()) { m_delegate->streamMetaDataAvailable(m_icyMetaData); } m_icyMetaData.clear(); continue; } char c = buf[offset]; if (c < 32 || c > 126) { continue; } m_icyMetaData.push_back(c); continue; } // is this the interval byte? if (m_icyMetaDataInterval > 0 && m_dataByteReadCount == m_icyMetaDataInterval) { m_metaDataBytesRemaining = buf[offset] * 16; if (m_metaDataBytesRemaining == 0) { m_dataByteReadCount = 0; } continue; } // a data byte m_dataByteReadCount++; m_icyReadBuffer[i++] = buf[offset]; } if (m_delegate && i > 0) { m_delegate->streamHasBytesAvailable(m_icyReadBuffer, i); } } void HTTP_Stream::readCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) { HTTP_Stream *THIS = static_cast<HTTP_Stream*>(clientCallBackInfo); if (!THIS->m_delegate) { return; } switch (eventType) { case kCFStreamEventHasBytesAvailable: { if (!THIS->m_httpReadBuffer) { THIS->m_httpReadBuffer = new UInt8[STREAM_BUFSIZ]; } CFIndex bytesRead = CFReadStreamRead(stream, THIS->m_httpReadBuffer, STREAM_BUFSIZ); if (bytesRead < 0) { THIS->m_delegate->streamErrorOccurred(); break; } if (bytesRead > 0) { THIS->parseHttpHeadersIfNeeded(THIS->m_httpReadBuffer, bytesRead); if (THIS->m_icyStream) { THIS->parseICYStream(THIS->m_httpReadBuffer, bytesRead); } else { THIS->m_delegate->streamHasBytesAvailable(THIS->m_httpReadBuffer, bytesRead); } } break; } case kCFStreamEventEndEncountered: { THIS->m_delegate->streamEndEncountered(); break; } case kCFStreamEventErrorOccurred: { THIS->m_delegate->streamErrorOccurred(); break; } } } } // namespace astreamer <commit_msg>When starting the HTTP stream from the beginning, reset content length<commit_after>/* * This file is part of the FreeStreamer project, * (C)Copyright 2011 Matias Muhonen <[email protected]> * See the file ''LICENSE'' for using the code. */ #include "http_stream.h" #include "audio_queue.h" namespace astreamer { const size_t HTTP_Stream::STREAM_BUFSIZ = Audio_Queue::AQ_BUFSIZ; CFStringRef HTTP_Stream::httpRequestMethod = CFSTR("GET"); CFStringRef HTTP_Stream::httpUserAgentHeader = CFSTR("User-Agent"); CFStringRef HTTP_Stream::httpUserAgentValue = CFSTR("aStreamer/1.0"); CFStringRef HTTP_Stream::httpRangeHeader = CFSTR("Range"); CFStringRef HTTP_Stream::icyMetaDataHeader = CFSTR("Icy-MetaData"); CFStringRef HTTP_Stream::icyMetaDataValue = CFSTR("1"); /* always request ICY metadata, if available */ /* HTTP_Stream: public */ HTTP_Stream::HTTP_Stream() : m_readStream(0), m_scheduledInRunLoop(false), m_delegate(0), m_url(0), m_httpHeadersParsed(false), m_contentLength(0), m_icyStream(false), m_icyHeaderCR(false), m_icyHeadersRead(false), m_icyHeadersParsed(false), m_icyMetaDataInterval(0), m_dataByteReadCount(0), m_metaDataBytesRemaining(0), m_httpReadBuffer(0), m_icyReadBuffer(0) { } HTTP_Stream::~HTTP_Stream() { close(); if (m_httpReadBuffer) { delete m_httpReadBuffer, m_httpReadBuffer = 0; } if (m_icyReadBuffer) { delete m_icyReadBuffer, m_icyReadBuffer = 0; } if (m_url) { CFRelease(m_url), m_url = 0; } } HTTP_Stream_Position HTTP_Stream::position() { return m_position; } std::string HTTP_Stream::contentType() { return m_contentType; } size_t HTTP_Stream::contentLength() { return m_contentLength; } bool HTTP_Stream::open() { HTTP_Stream_Position position; position.start = 0; position.end = 0; m_contentLength = 0; return open(position); } bool HTTP_Stream::open(const HTTP_Stream_Position& position) { bool success = false; CFStreamClientContext CTX = { 0, this, NULL, NULL, NULL }; /* Already opened a read stream, return */ if (m_readStream) { goto out; } /* Reset state */ m_position = position; m_httpHeadersParsed = false; m_contentType = ""; m_icyStream = false; m_icyHeaderCR = false; m_icyHeadersRead = false; m_icyHeadersParsed = false; m_icyHeaderLines.clear(); m_icyMetaDataInterval = 0; m_dataByteReadCount = 0; m_metaDataBytesRemaining = 0; m_icyMetaData = ""; /* Failed to create a stream */ if (!(m_readStream = createReadStream(m_url))) { goto out; } if (!CFReadStreamSetClient(m_readStream, kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred, readCallBack, &CTX)) { CFRelease(m_readStream), m_readStream = 0; goto out; } setScheduledInRunLoop(true); if (!CFReadStreamOpen(m_readStream)) { /* Open failed: clean */ CFReadStreamSetClient(m_readStream, 0, NULL, NULL); setScheduledInRunLoop(false); CFRelease(m_readStream), m_readStream = 0; goto out; } success = true; out: return success; } void HTTP_Stream::close() { /* The stream has been already closed */ if (!m_readStream) { return; } CFReadStreamSetClient(m_readStream, 0, NULL, NULL); setScheduledInRunLoop(false); CFReadStreamClose(m_readStream); CFRelease(m_readStream), m_readStream = 0; } void HTTP_Stream::setScheduledInRunLoop(bool scheduledInRunLoop) { /* The stream has not been opened, or it has been already closed */ if (!m_readStream) { return; } /* The state doesn't change */ if (m_scheduledInRunLoop == scheduledInRunLoop) { return; } if (m_scheduledInRunLoop) { CFReadStreamUnscheduleFromRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); } else { CFReadStreamScheduleWithRunLoop(m_readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); } m_scheduledInRunLoop = scheduledInRunLoop; } void HTTP_Stream::setUrl(CFURLRef url) { if (m_url) { CFRelease(m_url); } m_url = (CFURLRef)CFRetain(url); } /* private */ CFReadStreamRef HTTP_Stream::createReadStream(CFURLRef url) { CFReadStreamRef readStream = 0; CFHTTPMessageRef request; CFDictionaryRef proxySettings; if (!(request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, httpRequestMethod, url, kCFHTTPVersion1_1))) { goto out; } CFHTTPMessageSetHeaderFieldValue(request, httpUserAgentHeader, httpUserAgentValue); CFHTTPMessageSetHeaderFieldValue(request, icyMetaDataHeader, icyMetaDataValue); if (m_position.start > 0 && m_position.end > m_position.start) { CFStringRef rangeHeaderValue = CFStringCreateWithFormat(NULL, NULL, CFSTR("bytes=%lu-%lu"), m_position.start, m_position.end); CFHTTPMessageSetHeaderFieldValue(request, httpRangeHeader, rangeHeaderValue); CFRelease(rangeHeaderValue); } if (!(readStream = CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request, 0))) { goto out; } CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue); proxySettings = CFNetworkCopySystemProxySettings(); CFReadStreamSetProperty(readStream, kCFStreamPropertyHTTPProxy, proxySettings); CFRelease(proxySettings); out: if (request) { CFRelease(request); } return readStream; } void HTTP_Stream::parseHttpHeadersIfNeeded(UInt8 *buf, CFIndex bufSize) { if (m_httpHeadersParsed) { return; } m_httpHeadersParsed = true; /* If the response has the "ICY 200 OK" string, * we are dealing with the ShoutCast protocol. * The HTTP headers won't be available. */ std::string header; for (CFIndex k=0; k < bufSize; k++) { UInt8 c = buf[k]; // Ignore non-ASCII chars if (c < 32 || c > 126) { continue; } header.push_back(c); } char *p = strstr(header.c_str(), "ICY 200 OK"); // This is an ICY stream, don't try to parse the HTTP headers if (p) { m_icyStream = true; return; } CFHTTPMessageRef response = (CFHTTPMessageRef)CFReadStreamCopyProperty(m_readStream, kCFStreamPropertyHTTPResponseHeader); if (response) { /* * If the server responded with the icy-metaint header, the response * body will be encoded in the ShoutCast protocol. */ CFStringRef icyMetaIntString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("icy-metaint")); if (icyMetaIntString) { m_icyStream = true; m_icyHeadersParsed = true; m_icyHeadersRead = true; m_icyMetaDataInterval = CFStringGetIntValue(icyMetaIntString); CFRelease(icyMetaIntString); } CFStringRef contentTypeString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Type")); if (contentTypeString) { CFIndex len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(contentTypeString), kCFStringEncodingUTF8) + 1; char *buf = new char[len]; if (CFStringGetCString(contentTypeString, buf, len, kCFStringEncodingUTF8)) { m_contentType.append(buf); } delete[] buf; CFRelease(contentTypeString); } CFStringRef contentLengthString = CFHTTPMessageCopyHeaderFieldValue(response, CFSTR("Content-Length")); if (contentLengthString) { m_contentLength = CFStringGetIntValue(contentLengthString); CFRelease(contentLengthString); } CFRelease(response); } if (m_delegate) { m_delegate->streamIsReadyRead(); } } void HTTP_Stream::parseICYStream(UInt8 *buf, CFIndex bufSize) { CFIndex offset = 0; if (!m_icyHeadersRead) { // TODO: fail after n tries? for (; offset < bufSize; offset++) { if (m_icyHeaderCR && buf[offset] == '\n') { m_icyHeaderLines.push_back(std::string("")); size_t n = m_icyHeaderLines.size(); /* If the last two lines were empty, we have reached the end of the headers */ if (n >= 2) { if (m_icyHeaderLines[n-2].empty() && m_icyHeaderLines[n-1].empty()) { m_icyHeadersRead = true; break; } } continue; } if (buf[offset] == '\r') { m_icyHeaderCR = true; continue; } else { m_icyHeaderCR = false; } size_t numberOfLines = m_icyHeaderLines.size(); if (numberOfLines == 0) { continue; } m_icyHeaderLines[numberOfLines - 1].push_back(buf[offset]); } } else if (!m_icyHeadersParsed) { const char *icyContentTypeHeader = "content-type:"; const char *icyMetaDataHeader = "icy-metaint:"; size_t icyContenTypeHeaderLength = strlen(icyContentTypeHeader); size_t icyMetaDataHeaderLength = strlen(icyMetaDataHeader); for (std::vector<std::string>::iterator h = m_icyHeaderLines.begin(); h != m_icyHeaderLines.end(); ++h) { if (h->compare(0, icyContenTypeHeaderLength, icyContentTypeHeader) == 0) { m_contentType = h->substr(icyContenTypeHeaderLength, h->length() - icyContenTypeHeaderLength); } if (h->compare(0, icyMetaDataHeaderLength, icyMetaDataHeader) == 0) { m_icyMetaDataInterval = atoi(h->substr(icyMetaDataHeaderLength, h->length() - icyMetaDataHeaderLength).c_str()); } } m_icyHeadersParsed = true; offset++; if (m_delegate) { m_delegate->streamIsReadyRead(); } } if (!m_icyReadBuffer) { m_icyReadBuffer = new UInt8[STREAM_BUFSIZ]; } size_t i=0; for (; offset < bufSize; offset++) { // is this a metadata byte? if (m_metaDataBytesRemaining > 0) { m_metaDataBytesRemaining--; if (m_metaDataBytesRemaining == 0) { m_dataByteReadCount = 0; if (m_delegate && !m_icyMetaData.empty()) { m_delegate->streamMetaDataAvailable(m_icyMetaData); } m_icyMetaData.clear(); continue; } char c = buf[offset]; if (c < 32 || c > 126) { continue; } m_icyMetaData.push_back(c); continue; } // is this the interval byte? if (m_icyMetaDataInterval > 0 && m_dataByteReadCount == m_icyMetaDataInterval) { m_metaDataBytesRemaining = buf[offset] * 16; if (m_metaDataBytesRemaining == 0) { m_dataByteReadCount = 0; } continue; } // a data byte m_dataByteReadCount++; m_icyReadBuffer[i++] = buf[offset]; } if (m_delegate && i > 0) { m_delegate->streamHasBytesAvailable(m_icyReadBuffer, i); } } void HTTP_Stream::readCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) { HTTP_Stream *THIS = static_cast<HTTP_Stream*>(clientCallBackInfo); if (!THIS->m_delegate) { return; } switch (eventType) { case kCFStreamEventHasBytesAvailable: { if (!THIS->m_httpReadBuffer) { THIS->m_httpReadBuffer = new UInt8[STREAM_BUFSIZ]; } CFIndex bytesRead = CFReadStreamRead(stream, THIS->m_httpReadBuffer, STREAM_BUFSIZ); if (bytesRead < 0) { THIS->m_delegate->streamErrorOccurred(); break; } if (bytesRead > 0) { THIS->parseHttpHeadersIfNeeded(THIS->m_httpReadBuffer, bytesRead); if (THIS->m_icyStream) { THIS->parseICYStream(THIS->m_httpReadBuffer, bytesRead); } else { THIS->m_delegate->streamHasBytesAvailable(THIS->m_httpReadBuffer, bytesRead); } } break; } case kCFStreamEventEndEncountered: { THIS->m_delegate->streamEndEncountered(); break; } case kCFStreamEventErrorOccurred: { THIS->m_delegate->streamErrorOccurred(); break; } } } } // namespace astreamer <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FuzzyConnectApp.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "FuzzyConnectApp.h" #include "itkByteSwapper.h" #include "itkImageRegionIterator.h" #include "itkImageMapper.h" #include "itkRawImageWriter.h" #include "itkExceptionObject.h" #include "vnl/vnl_math.h" #include <fstream> #include <string> FuzzyConnectApp ::FuzzyConnectApp() { this->Initialize(); } void FuzzyConnectApp ::Initialize() { m_InputImage = InputImageType::New(); m_Filter = FilterType::New(); m_ObjectVariance = 2500.0; m_DiffMean = 1.0; m_DiffVariance = 1.0; m_Weight = 1.0; m_DumpPGMFiles = true; for( int j = 0; j < ImageDimension; j++ ) { m_InputSpacing[j] = 1.0; } } void FuzzyConnectApp ::Execute() { char currentLine[150]; char buffer[150]; unsigned int uNumbers[3]; float fValue; char symbol; std::cout << std::endl; // Get input file name while(1) { std::cout << "Input file name: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: filename expected." << std::endl; } m_InputFileName = buffer; // Get big endian flag while(1) { std::cout << "Input image big endian? [y|n]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%c", &symbol ) >= 1 && ( symbol == 'y' || symbol == 'n' ) ) break; std::cout << "Error: 'y' or 'n' expected." << std::endl; } if( symbol == 'y' ) { m_InputBigEndian = true; } else { m_InputBigEndian = false; } // Get input file size while(1) { std::cout << "Input image size: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_InputSize[j] = uNumbers[j]; } // Read in input image if( !this->ReadImage( m_InputFileName.c_str(), m_InputSize, m_InputSpacing, m_InputBigEndian, m_InputImage ) ) { std::cout << "Error while reading in input volume: "; std::cout << m_InputFileName.c_str() << std::endl; return; } // Get input file name while(1) { std::cout << "PGM output directory: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: directory name expected." << std::endl; } m_PGMDirectory = buffer; if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the input volume." << std::endl; if( !this->WritePGMFiles( m_InputImage, m_PGMDirectory.c_str(), "input" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } std::cout << std::endl << std::endl; // Set the initial seed while(1) { std::cout << "Set initial seed index: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } // Set the initial threshold while(1) { std::cout << "Set initial threshold value: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%f", &fValue ) >= 1 ) break; std::cout << "Error: one floating point value expected." << std::endl; } m_Threshold = fValue; // run the filter std::cout << "Generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); while(1) { std::cout << std::endl << "Command [s|t|d|x]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%s", buffer ) >= 1 ) { // parse the command switch ( buffer[0] ) { case 's' : if( sscanf( currentLine, "%c%d%d%d", &symbol, uNumbers, uNumbers+1, uNumbers+2 ) != 4 ) { std::cout << "Error: three unsigned integers expected" << std::endl; continue; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } std::cout << "Re-generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); break; case 't' : if( sscanf( currentLine, "%c%f", &symbol, &fValue ) != 2 ) { std::cout << "Error: one floating point value expected" << std::endl; continue; } m_Threshold = fValue;; std::cout << "Re-thresholding the map." << std::endl; this->ComputeSegmentationImage(); this->WriteSegmentationImage(); break; break; case 'd': std::cout << "Seed: " << m_Seed << "Threshold: " << m_Threshold << std::endl; break; case 'x' : std::cout << "Goodbye. " << std::endl; return; break; default : std::cout << "Not a valid command." << std::endl; } //end switch } } //end while } void FuzzyConnectApp ::ComputeMap() { m_Filter->SetInput( m_InputImage ); m_Filter->SetSeed( m_Seed ); m_ObjectMean = double( m_InputImage->GetPixel( m_Seed ) ); m_Filter->SetParameters( m_ObjectMean, m_ObjectVariance, m_DiffMean, m_DiffVariance, m_Weight ); m_Filter->SetThreshold( m_Threshold ); m_Filter->ExcuteSegment(); } void FuzzyConnectApp ::ComputeSegmentationImage() { m_Filter->SetThreshold( m_Threshold ); m_Filter->MakeSegmentObject(); } void FuzzyConnectApp ::WriteSegmentationImage() { if( m_DumpPGMFiles ) { //dump out the segmented image if( !this->WritePGMFiles( m_Filter->GetOutput(), m_PGMDirectory.c_str(), "seg" ) ) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } bool FuzzyConnectApp ::ReadImage( const char * filename, const SizeType& size, const double * spacing, bool bigEndian, InputImageType * imgPtr ) { //***** //FIXME - use itkRawImageIO instead once its stable //***** // allocate memory in the image InputImageType::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); double origin[ImageDimension]; for( int j = 0; j < ImageDimension; j++ ) { origin[j] = -0.5 * ( double(size[j]) - 1.0 ) * spacing[j]; } imgPtr->SetSpacing( spacing ); imgPtr->SetOrigin( origin ); unsigned int numPixels = region.GetNumberOfPixels(); // open up the file std::ifstream imgStream( filename, std::ios::binary | std::ios::in ); if( !imgStream.is_open() ) { return false; } // read the file InputPixelType * buffer = imgPtr->GetBufferPointer(); imgStream.read( (char *) buffer, numPixels * sizeof(InputPixelType) ); // clost the file imgStream.close(); // swap bytes if neccessary if( bigEndian ) { itk::ByteSwapper<InputPixelType>::SwapRangeBE( buffer, numPixels ); } else { itk::ByteSwapper<InputPixelType>::SwapRangeLE( buffer, numPixels ); } return true; } bool FuzzyConnectApp ::WritePGMFiles( InputImageType * input, const char * dirname, const char * basename ) { // go through the image and compute the offset and scale // to make it normalized to between 0 and 255 typedef itk::ImageRegionIterator<InputImageType> InputIterator; InputIterator inIter( input, input->GetBufferedRegion() ); InputPixelType minValue = inIter.Get(); InputPixelType maxValue = minValue; while( !inIter.IsAtEnd() ) { InputPixelType value = inIter.Get(); if( value < minValue ) minValue = value; if( value > maxValue ) maxValue = value; ++inIter; } double scale = double( maxValue - minValue ); if( !scale ) scale = 1.0; double offset = double(minValue); // write image out to pgm files char filename[256]; char buffer[50]; unsigned long ncol = input->GetBufferedRegion().GetSize()[0]; unsigned long nrow = input->GetBufferedRegion().GetSize()[1]; unsigned long nslice = input->GetBufferedRegion().GetSize()[2]; sprintf(buffer,"P5 %ld %ld 255\n", ncol, nrow ); unsigned int nchar = strlen(buffer); unsigned long npixels = nrow * ncol; inIter.GoToBegin(); for( unsigned int k = 0; k < nslice; k++ ) { if( k < 10 ) { sprintf(filename,"%s/%s00%d.pgm", dirname, basename, k ); } else if( k < 100 ) { sprintf(filename, "%s/%s0%d.pgm", dirname, basename, k ); } else { sprintf(filename, "%s/%s%d.pgm", dirname, basename, k ); } // open up the stream std::ofstream imgStream( filename, std::ios::out | std::ios::binary ); if( !imgStream.is_open() ) { return false; } // writer the header imgStream.write( buffer, nchar ); // write the bytes for( unsigned long i = 0; i < npixels; i++ ) { double value = (double(inIter.Get()) - offset) / scale * 255; char num = vnl_math_rnd( value ); imgStream.put( num ); ++inIter; } // close this file imgStream.close(); } return true; } <commit_msg><commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FuzzyConnectApp.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "FuzzyConnectApp.h" #include "itkByteSwapper.h" #include "itkImageRegionIterator.h" #include "itkImageMapper.h" #include "itkRawImageWriter.h" #include "itkExceptionObject.h" #include "vnl/vnl_math.h" #include <fstream> #include <string> FuzzyConnectApp ::FuzzyConnectApp() { this->Initialize(); } void FuzzyConnectApp ::Initialize() { m_InputImage = InputImageType::New(); m_Filter = FilterType::New(); m_ObjectVariance = 2500.0; m_DiffMean = 1.0; m_DiffVariance = 1.0; m_Weight = 1.0; m_DumpPGMFiles = true; for( int j = 0; j < ImageDimension; j++ ) { m_InputSpacing[j] = 1.0; } } void FuzzyConnectApp ::Execute() { char currentLine[150]; char buffer[150]; unsigned int uNumbers[3]; float fValue; char symbol; std::cout << std::endl; // Get input file name while(1) { std::cout << "Input file name: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: filename expected." << std::endl; } m_InputFileName = buffer; // Get big endian flag while(1) { std::cout << "Input image big endian? [y|n]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%c", &symbol ) >= 1 && ( symbol == 'y' || symbol == 'n' ) ) break; std::cout << "Error: 'y' or 'n' expected." << std::endl; } if( symbol == 'y' ) { m_InputBigEndian = true; } else { m_InputBigEndian = false; } // Get input file size while(1) { std::cout << "Input image size: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_InputSize[j] = uNumbers[j]; } // Read in input image if( !this->ReadImage( m_InputFileName.c_str(), m_InputSize, m_InputSpacing, m_InputBigEndian, m_InputImage ) ) { std::cout << "Error while reading in input volume: "; std::cout << m_InputFileName.c_str() << std::endl; return; } // Get input file name while(1) { std::cout << "PGM output directory: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: directory name expected." << std::endl; } m_PGMDirectory = buffer; if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the input volume." << std::endl; if( !this->WritePGMFiles( m_InputImage, m_PGMDirectory.c_str(), "input" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } std::cout << std::endl << std::endl; // Set the initial seed while(1) { std::cout << "Set initial seed index: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } // Set the initial threshold while(1) { std::cout << "Set initial threshold value: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%f", &fValue ) >= 1 ) break; std::cout << "Error: one floating point value expected." << std::endl; } m_Threshold = fValue; // run the filter std::cout << "Generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); while(1) { std::cout << std::endl << "Command [s|t|d|x]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%s", buffer ) >= 1 ) { // parse the command switch ( buffer[0] ) { case 's' : if( sscanf( currentLine, "%c%d%d%d", &symbol, uNumbers, uNumbers+1, uNumbers+2 ) != 4 ) { std::cout << "Error: three unsigned integers expected" << std::endl; continue; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } std::cout << "Re-generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); break; case 't' : if( sscanf( currentLine, "%c%f", &symbol, &fValue ) != 2 ) { std::cout << "Error: one floating point value expected" << std::endl; continue; } m_Threshold = fValue;; std::cout << "Re-thresholding the map." << std::endl; this->ComputeSegmentationImage(); this->WriteSegmentationImage(); break; break; case 'd': std::cout << "Seed: " << m_Seed << "Threshold: " << m_Threshold << std::endl; break; case 'x' : std::cout << "Goodbye. " << std::endl; return; break; default : std::cout << "Not a valid command." << std::endl; } //end switch } } //end while } void FuzzyConnectApp ::ComputeMap() { m_Filter->SetInput( m_InputImage ); m_Filter->SetSeed( m_Seed ); m_ObjectMean = double( m_InputImage->GetPixel( m_Seed ) ); m_Filter->SetParameters( m_ObjectMean, m_ObjectVariance, m_DiffMean, m_DiffVariance, m_Weight ); m_Filter->SetThreshold( m_Threshold ); m_Filter->Update(); } void FuzzyConnectApp ::ComputeSegmentationImage() { m_Filter->UpdateThreshold( m_Threshold ); } void FuzzyConnectApp ::WriteSegmentationImage() { if( m_DumpPGMFiles ) { //dump out the segmented image if( !this->WritePGMFiles( m_Filter->GetOutput(), m_PGMDirectory.c_str(), "seg" ) ) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } bool FuzzyConnectApp ::ReadImage( const char * filename, const SizeType& size, const double * spacing, bool bigEndian, InputImageType * imgPtr ) { //***** //FIXME - use itkRawImageIO instead once its stable //***** // allocate memory in the image InputImageType::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); double origin[ImageDimension]; for( int j = 0; j < ImageDimension; j++ ) { origin[j] = -0.5 * ( double(size[j]) - 1.0 ) * spacing[j]; } imgPtr->SetSpacing( spacing ); imgPtr->SetOrigin( origin ); unsigned int numPixels = region.GetNumberOfPixels(); // open up the file std::ifstream imgStream( filename, std::ios::binary | std::ios::in ); if( !imgStream.is_open() ) { return false; } // read the file InputPixelType * buffer = imgPtr->GetBufferPointer(); imgStream.read( (char *) buffer, numPixels * sizeof(InputPixelType) ); // clost the file imgStream.close(); // swap bytes if neccessary if( bigEndian ) { itk::ByteSwapper<InputPixelType>::SwapRangeBE( buffer, numPixels ); } else { itk::ByteSwapper<InputPixelType>::SwapRangeLE( buffer, numPixels ); } return true; } bool FuzzyConnectApp ::WritePGMFiles( InputImageType * input, const char * dirname, const char * basename ) { // go through the image and compute the offset and scale // to make it normalized to between 0 and 255 typedef itk::ImageRegionIterator<InputImageType> InputIterator; InputIterator inIter( input, input->GetBufferedRegion() ); InputPixelType minValue = inIter.Get(); InputPixelType maxValue = minValue; while( !inIter.IsAtEnd() ) { InputPixelType value = inIter.Get(); if( value < minValue ) minValue = value; if( value > maxValue ) maxValue = value; ++inIter; } double scale = double( maxValue - minValue ); if( !scale ) scale = 1.0; double offset = double(minValue); // write image out to pgm files char filename[256]; char buffer[50]; unsigned long ncol = input->GetBufferedRegion().GetSize()[0]; unsigned long nrow = input->GetBufferedRegion().GetSize()[1]; unsigned long nslice = input->GetBufferedRegion().GetSize()[2]; sprintf(buffer,"P5 %ld %ld 255\n", ncol, nrow ); unsigned int nchar = strlen(buffer); unsigned long npixels = nrow * ncol; inIter.GoToBegin(); for( unsigned int k = 0; k < nslice; k++ ) { if( k < 10 ) { sprintf(filename,"%s/%s00%d.pgm", dirname, basename, k ); } else if( k < 100 ) { sprintf(filename, "%s/%s0%d.pgm", dirname, basename, k ); } else { sprintf(filename, "%s/%s%d.pgm", dirname, basename, k ); } // open up the stream std::ofstream imgStream( filename, std::ios::out | std::ios::binary ); if( !imgStream.is_open() ) { return false; } // writer the header imgStream.write( buffer, nchar ); // write the bytes for( unsigned long i = 0; i < npixels; i++ ) { double value = (double(inIter.Get()) - offset) / scale * 255; char num = vnl_math_rnd( value ); imgStream.put( num ); ++inIter; } // close this file imgStream.close(); } return true; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FuzzyConnectApp.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "FuzzyConnectApp.h" #include "itkByteSwapper.h" #include "itkImageRegionIterator.h" #include "itkImageMapper.h" #include "itkRawImageWriter.h" #include "itkExceptionObject.h" #include "vnl/vnl_math.h" #include "vnl/vnl_quaternion.h" #include "vnl/vnl_diag_matrix.h" #include <fstream> #include <string> FuzzyConnectApp ::FuzzyConnectApp() { this->Initialize(); } void FuzzyConnectApp ::Initialize() { m_InputImage = InputImageType::New(); m_Filter = FilterType::New(); m_ObjectVariance = 2500.0; m_DiffMean = 1.0; m_DiffVariance = 1.0; m_Weight = 1.0; m_DumpPGMFiles = true; for( int j = 0; j < ImageDimension; j++ ) { m_InputSpacing[j] = 1.0; } } void FuzzyConnectApp ::Execute() { char currentLine[150]; char buffer[150]; unsigned int uNumbers[3]; float fValue; char symbol; std::cout << std::endl; // Get input file name while(1) { std::cout << "Input file name: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: filename expected." << std::endl; } m_InputFileName = buffer; // Get big endian flag while(1) { std::cout << "Input image big endian? [y|n]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%c", &symbol ) >= 1 && ( symbol == 'y' || symbol == 'n' ) ) break; std::cout << "Error: 'y' or 'n' expected." << std::endl; } if( symbol == 'y' ) { m_InputBigEndian = true; } else { m_InputBigEndian = false; } // Get input file size while(1) { std::cout << "Input image size: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_InputSize[j] = uNumbers[j]; } // Read in input image if( !this->ReadImage( m_InputFileName.c_str(), m_InputSize, m_InputSpacing, m_InputBigEndian, m_InputImage ) ) { std::cout << "Error while reading in input volume: "; std::cout << m_InputFileName.c_str() << std::endl; return; } // Get input file name while(1) { std::cout << "PGM output directory: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: directory name expected." << std::endl; } m_PGMDirectory = buffer; if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the input volume." << std::endl; if( !this->WritePGMFiles( m_InputImage, m_PGMDirectory.c_str(), "input" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } std::cout << std::endl << std::endl; // Set the initial seed while(1) { std::cout << "Set initial seed index: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } // Set the initial threshold while(1) { std::cout << "Set initial threshold value: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%f", &fValue ) >= 1 ) break; std::cout << "Error: one floating point value expected." << std::endl; } m_Threshold = fValue; // run the filter std::cout << "Generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); while(1) { std::cout << std::endl << "Command [s|t|d|x]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%s", buffer ) >= 1 ) { // parse the command switch ( buffer[0] ) { case 's' : if( sscanf( currentLine, "%c%d%d%d", &symbol, uNumbers, uNumbers+1, uNumbers+2 ) != 4 ) { std::cout << "Error: three unsigned integers expected" << std::endl; continue; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } std::cout << "Re-generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); break; case 't' : if( sscanf( currentLine, "%c%f", &symbol, &fValue ) != 2 ) { std::cout << "Error: one floating point value expected" << std::endl; continue; } m_Threshold = fValue;; std::cout << "Re-thresholding the map." << std::endl; this->ComputeSegmentationImage(); this->WriteSegmentationImage(); break; break; case 'd': std::cout << "Seed: " << m_Seed << "Threshold: " << m_Threshold << std::endl; break; case 'x' : std::cout << "Goodbye. " << std::endl; return; break; default : std::cout << "Not a valid command." << std::endl; } //end switch } } //end while } void FuzzyConnectApp ::ComputeMap() { m_Filter->SetInput( m_InputImage ); m_Filter->SetSeed( m_Seed ); m_ObjectMean = double( m_InputImage->GetPixel( m_Seed ) ); m_Filter->SetParameters( m_ObjectMean, m_ObjectVariance, m_DiffMean, m_DiffVariance, m_Weight ); m_Filter->SetThreshold( m_Threshold ); m_Filter->ExcuteSegment(); } void FuzzyConnectApp ::ComputeSegmentationImage() { m_Filter->SetThreshold( m_Threshold ); m_Filter->MakeSegmentObject(); } void FuzzyConnectApp ::WriteSegmentationImage() { if( m_DumpPGMFiles ) { //dump out the segmented image if( !this->WritePGMFiles( m_Filter->GetOutput(), m_PGMDirectory.c_str(), "seg" ) ) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } bool FuzzyConnectApp ::ReadImage( const char * filename, const SizeType& size, const double * spacing, bool bigEndian, InputImageType * imgPtr ) { //***** //FIXME - use itkRawImageIO instead once its stable //***** // allocate memory in the image InputImageType::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); double origin[ImageDimension]; for( int j = 0; j < ImageDimension; j++ ) { origin[j] = -0.5 * ( double(size[j]) - 1.0 ) * spacing[j]; } imgPtr->SetSpacing( spacing ); imgPtr->SetOrigin( origin ); unsigned int numPixels = region.GetNumberOfPixels(); // open up the file std::ifstream imgStream( filename, std::ios::binary | std::ios::in ); if( !imgStream.is_open() ) { return false; } // read the file InputPixelType * buffer = imgPtr->GetBufferPointer(); imgStream.read( (char *) buffer, numPixels * sizeof(InputPixelType) ); // clost the file imgStream.close(); // swap bytes if neccessary if( bigEndian ) { itk::ByteSwapper<InputPixelType>::SwapRangeBE( buffer, numPixels ); } else { itk::ByteSwapper<InputPixelType>::SwapRangeLE( buffer, numPixels ); } return true; } bool FuzzyConnectApp ::WritePGMFiles( InputImageType * input, const char * dirname, const char * basename ) { // go through the image and compute the offset and scale // to make it normalized to between 0 and 255 typedef itk::ImageRegionIterator<InputImageType> InputIterator; InputIterator inIter( input, input->GetBufferedRegion() ); inIter = inIter.Begin(); InputPixelType minValue = inIter.Get(); InputPixelType maxValue = minValue; while( !inIter.IsAtEnd() ) { InputPixelType value = inIter.Get(); if( value < minValue ) minValue = value; if( value > maxValue ) maxValue = value; ++inIter; } double scale = double( maxValue - minValue ); if( !scale ) scale = 1.0; double offset = double(minValue); // write image out to pgm files char filename[256]; char buffer[50]; unsigned long ncol = input->GetBufferedRegion().GetSize()[0]; unsigned long nrow = input->GetBufferedRegion().GetSize()[1]; unsigned long nslice = input->GetBufferedRegion().GetSize()[2]; sprintf(buffer,"P5 %ld %ld 255\n", ncol, nrow ); unsigned int nchar = strlen(buffer); unsigned long npixels = nrow * ncol; inIter = inIter.Begin(); for( unsigned int k = 0; k < nslice; k++ ) { if( k < 10 ) { sprintf(filename,"%s/%s00%d.pgm", dirname, basename, k ); } else if( k < 100 ) { sprintf(filename, "%s/%s0%d.pgm", dirname, basename, k ); } else { sprintf(filename, "%s/%s%d.pgm", dirname, basename, k ); } // open up the stream std::ofstream imgStream( filename, std::ios::out | std::ios::binary ); if( !imgStream.is_open() ) { return false; } // writer the header imgStream.write( buffer, nchar ); // write the bytes for( unsigned long i = 0; i < npixels; i++ ) { double value = (double(inIter.Get()) - offset) / scale * 255; char num = vnl_math_rnd( value ); imgStream.put( num ); ++inIter; } // close this file imgStream.close(); } return true; } <commit_msg><commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FuzzyConnectApp.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2001 Insight Consortium 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. * The name of the Insight Consortium, nor the names of any consortium members, nor of any contributors, may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AUTHORS 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 "FuzzyConnectApp.h" #include "itkByteSwapper.h" #include "itkImageRegionIterator.h" #include "itkImageMapper.h" #include "itkRawImageWriter.h" #include "itkExceptionObject.h" #include "vnl/vnl_math.h" #include <fstream> #include <string> FuzzyConnectApp ::FuzzyConnectApp() { this->Initialize(); } void FuzzyConnectApp ::Initialize() { m_InputImage = InputImageType::New(); m_Filter = FilterType::New(); m_ObjectVariance = 2500.0; m_DiffMean = 1.0; m_DiffVariance = 1.0; m_Weight = 1.0; m_DumpPGMFiles = true; for( int j = 0; j < ImageDimension; j++ ) { m_InputSpacing[j] = 1.0; } } void FuzzyConnectApp ::Execute() { char currentLine[150]; char buffer[150]; unsigned int uNumbers[3]; float fValue; char symbol; std::cout << std::endl; // Get input file name while(1) { std::cout << "Input file name: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: filename expected." << std::endl; } m_InputFileName = buffer; // Get big endian flag while(1) { std::cout << "Input image big endian? [y|n]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%c", &symbol ) >= 1 && ( symbol == 'y' || symbol == 'n' ) ) break; std::cout << "Error: 'y' or 'n' expected." << std::endl; } if( symbol == 'y' ) { m_InputBigEndian = true; } else { m_InputBigEndian = false; } // Get input file size while(1) { std::cout << "Input image size: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_InputSize[j] = uNumbers[j]; } // Read in input image if( !this->ReadImage( m_InputFileName.c_str(), m_InputSize, m_InputSpacing, m_InputBigEndian, m_InputImage ) ) { std::cout << "Error while reading in input volume: "; std::cout << m_InputFileName.c_str() << std::endl; return; } // Get input file name while(1) { std::cout << "PGM output directory: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: directory name expected." << std::endl; } m_PGMDirectory = buffer; if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the input volume." << std::endl; if( !this->WritePGMFiles( m_InputImage, m_PGMDirectory.c_str(), "input" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } std::cout << std::endl << std::endl; // Set the initial seed while(1) { std::cout << "Set initial seed index: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } // Set the initial threshold while(1) { std::cout << "Set initial threshold value: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%f", &fValue ) >= 1 ) break; std::cout << "Error: one floating point value expected." << std::endl; } m_Threshold = fValue; // run the filter std::cout << "Generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); while(1) { std::cout << std::endl << "Command [s|t|d|x]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%s", buffer ) >= 1 ) { // parse the command switch ( buffer[0] ) { case 's' : if( sscanf( currentLine, "%c%d%d%d", &symbol, uNumbers, uNumbers+1, uNumbers+2 ) != 4 ) { std::cout << "Error: three unsigned integers expected" << std::endl; continue; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } std::cout << "Re-generating the fuzzy connectedness map." << std::endl; this->ComputeMap(); this->WriteSegmentationImage(); break; case 't' : if( sscanf( currentLine, "%c%f", &symbol, &fValue ) != 2 ) { std::cout << "Error: one floating point value expected" << std::endl; continue; } m_Threshold = fValue;; std::cout << "Re-thresholding the map." << std::endl; this->ComputeSegmentationImage(); this->WriteSegmentationImage(); break; break; case 'd': std::cout << "Seed: " << m_Seed << "Threshold: " << m_Threshold << std::endl; break; case 'x' : std::cout << "Goodbye. " << std::endl; return; break; default : std::cout << "Not a valid command." << std::endl; } //end switch } } //end while } void FuzzyConnectApp ::ComputeMap() { m_Filter->SetInput( m_InputImage ); m_Filter->SetSeed( m_Seed ); m_ObjectMean = double( m_InputImage->GetPixel( m_Seed ) ); m_Filter->SetParameters( m_ObjectMean, m_ObjectVariance, m_DiffMean, m_DiffVariance, m_Weight ); m_Filter->SetThreshold( m_Threshold ); m_Filter->ExcuteSegment(); } void FuzzyConnectApp ::ComputeSegmentationImage() { m_Filter->SetThreshold( m_Threshold ); m_Filter->MakeSegmentObject(); } void FuzzyConnectApp ::WriteSegmentationImage() { if( m_DumpPGMFiles ) { //dump out the segmented image if( !this->WritePGMFiles( m_Filter->GetOutput(), m_PGMDirectory.c_str(), "seg" ) ) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } bool FuzzyConnectApp ::ReadImage( const char * filename, const SizeType& size, const double * spacing, bool bigEndian, InputImageType * imgPtr ) { //***** //FIXME - use itkRawImageIO instead once its stable //***** // allocate memory in the image InputImageType::RegionType region; region.SetSize( size ); imgPtr->SetLargestPossibleRegion( region ); imgPtr->SetBufferedRegion( region ); imgPtr->Allocate(); double origin[ImageDimension]; for( int j = 0; j < ImageDimension; j++ ) { origin[j] = -0.5 * ( double(size[j]) - 1.0 ) * spacing[j]; } imgPtr->SetSpacing( spacing ); imgPtr->SetOrigin( origin ); unsigned int numPixels = region.GetNumberOfPixels(); // open up the file std::ifstream imgStream( filename, std::ios::binary | std::ios::in ); if( !imgStream.is_open() ) { return false; } // read the file InputPixelType * buffer = imgPtr->GetBufferPointer(); imgStream.read( (char *) buffer, numPixels * sizeof(InputPixelType) ); // clost the file imgStream.close(); // swap bytes if neccessary if( bigEndian ) { itk::ByteSwapper<InputPixelType>::SwapRangeBE( buffer, numPixels ); } else { itk::ByteSwapper<InputPixelType>::SwapRangeLE( buffer, numPixels ); } return true; } bool FuzzyConnectApp ::WritePGMFiles( InputImageType * input, const char * dirname, const char * basename ) { // go through the image and compute the offset and scale // to make it normalized to between 0 and 255 typedef itk::ImageRegionIterator<InputImageType> InputIterator; InputIterator inIter( input, input->GetBufferedRegion() ); inIter = inIter.Begin(); InputPixelType minValue = inIter.Get(); InputPixelType maxValue = minValue; while( !inIter.IsAtEnd() ) { InputPixelType value = inIter.Get(); if( value < minValue ) minValue = value; if( value > maxValue ) maxValue = value; ++inIter; } double scale = double( maxValue - minValue ); if( !scale ) scale = 1.0; double offset = double(minValue); // write image out to pgm files char filename[256]; char buffer[50]; unsigned long ncol = input->GetBufferedRegion().GetSize()[0]; unsigned long nrow = input->GetBufferedRegion().GetSize()[1]; unsigned long nslice = input->GetBufferedRegion().GetSize()[2]; sprintf(buffer,"P5 %ld %ld 255\n", ncol, nrow ); unsigned int nchar = strlen(buffer); unsigned long npixels = nrow * ncol; inIter = inIter.Begin(); for( unsigned int k = 0; k < nslice; k++ ) { if( k < 10 ) { sprintf(filename,"%s/%s00%d.pgm", dirname, basename, k ); } else if( k < 100 ) { sprintf(filename, "%s/%s0%d.pgm", dirname, basename, k ); } else { sprintf(filename, "%s/%s%d.pgm", dirname, basename, k ); } // open up the stream std::ofstream imgStream( filename, std::ios::out | std::ios::binary ); if( !imgStream.is_open() ) { return false; } // writer the header imgStream.write( buffer, nchar ); // write the bytes for( unsigned long i = 0; i < npixels; i++ ) { double value = (double(inIter.Get()) - offset) / scale * 255; char num = vnl_math_rnd( value ); imgStream.put( num ); ++inIter; } // close this file imgStream.close(); } return true; } <|endoftext|>
<commit_before> // FastRandom.cpp // Implements the cFastRandom class representing a fast random number generator #include "Globals.h" #include <time.h> #include "FastRandom.h" #if 0 && defined(_DEBUG) // Self-test // Both ints and floats are quick-tested to see if the random is calculated correctly, checking the range in ASSERTs, // and if it performs well in terms of distribution (checked by avg, expected to be in the range midpoint class cFastRandomTest { public: cFastRandomTest(void) { TestInts(); TestFloats(); } void TestInts(void) { printf("Testing ints...\n"); cFastRandom rnd; int sum = 0; const int BUCKETS = 8; int Counts[BUCKETS]; memset(Counts, 0, sizeof(Counts)); const int ITER = 10000; for (int i = 0; i < ITER; i++) { int v = rnd.NextInt(1000); ASSERT(v >= 0); ASSERT(v < 1000); Counts[v % BUCKETS]++; sum += v; } double avg = (double)sum / ITER; printf("avg: %f\n", avg); for (int i = 0; i < BUCKETS; i++) { printf(" bucket %d: %d\n", i, Counts[i]); } } void TestFloats(void) { printf("Testing floats...\n"); cFastRandom rnd; float sum = 0; const int BUCKETS = 8; int Counts[BUCKETS]; memset(Counts, 0, sizeof(Counts)); const int ITER = 10000; for (int i = 0; i < ITER; i++) { float v = rnd.NextFloat(1000); ASSERT(v >= 0); ASSERT(v <= 1000); Counts[((int)v) % BUCKETS]++; sum += v; } sum = sum / ITER; printf("avg: %f\n", sum); for (int i = 0; i < BUCKETS; i++) { printf(" bucket %d: %d\n", i, Counts[i]); } } } g_Test; #endif int cFastRandom::m_SeedCounter = 0; cFastRandom::cFastRandom(void) : m_Seed(m_SeedCounter++) { } int cFastRandom::NextInt(int a_Range) { ASSERT(a_Range <= 1000000); // The random is not sufficiently linearly distributed with bigger ranges ASSERT(a_Range > 0); // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, m_Counter and m_Seed as inputs to the pseudorandom function: int n = a_Range + m_Counter * 57 + m_Seed * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); return ((n / 11) % a_Range); } int cFastRandom::NextInt(int a_Range, int a_Salt) { ASSERT(a_Range <= 1000000); // The random is not sufficiently linearly distributed with bigger ranges ASSERT(a_Range > 0); // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, a_Salt, m_Counter and m_Seed as inputs to the pseudorandom function: int n = a_Range + m_Counter * 57 + m_Seed * 57 * 57 + a_Salt * 57 * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); return ((n / 11) % a_Range); } float cFastRandom::NextFloat(float a_Range) { // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, a_Salt, m_Counter and m_Seed as inputs to the pseudorandom function: int n = (int)a_Range + m_Counter * 57 + m_Seed * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); // Convert the integer into float with the specified range: return (((float)n / (float)0x7fffffff) * a_Range); } float cFastRandom::NextFloat(float a_Range, int a_Salt) { // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, a_Salt, m_Counter and m_Seed as inputs to the pseudorandom function: int n = (int)a_Range + m_Counter * 57 + m_Seed * 57 * 57 + a_Salt * 57 * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); // Convert the integer into float with the specified range: return (((float)n / (float)0x7fffffff) * a_Range); } <commit_msg>Properly fixed warnings in cFastRandom.<commit_after> // FastRandom.cpp // Implements the cFastRandom class representing a fast random number generator #include "Globals.h" #include <time.h> #include "FastRandom.h" #if 0 && defined(_DEBUG) // Self-test // Both ints and floats are quick-tested to see if the random is calculated correctly, checking the range in ASSERTs, // and if it performs well in terms of distribution (checked by avg, expected to be in the range midpoint class cFastRandomTest { public: cFastRandomTest(void) { TestInts(); TestFloats(); } void TestInts(void) { printf("Testing ints...\n"); cFastRandom rnd; int sum = 0; const int BUCKETS = 8; int Counts[BUCKETS]; memset(Counts, 0, sizeof(Counts)); const int ITER = 10000; for (int i = 0; i < ITER; i++) { int v = rnd.NextInt(1000); ASSERT(v >= 0); ASSERT(v < 1000); Counts[v % BUCKETS]++; sum += v; } double avg = (double)sum / ITER; printf("avg: %f\n", avg); for (int i = 0; i < BUCKETS; i++) { printf(" bucket %d: %d\n", i, Counts[i]); } } void TestFloats(void) { printf("Testing floats...\n"); cFastRandom rnd; float sum = 0; const int BUCKETS = 8; int Counts[BUCKETS]; memset(Counts, 0, sizeof(Counts)); const int ITER = 10000; for (int i = 0; i < ITER; i++) { float v = rnd.NextFloat(1000); ASSERT(v >= 0); ASSERT(v <= 1000); Counts[((int)v) % BUCKETS]++; sum += v; } sum = sum / ITER; printf("avg: %f\n", sum); for (int i = 0; i < BUCKETS; i++) { printf(" bucket %d: %d\n", i, Counts[i]); } } } g_Test; #endif int cFastRandom::m_SeedCounter = 0; cFastRandom::cFastRandom(void) : m_Seed(m_SeedCounter++) { } int cFastRandom::NextInt(int a_Range) { ASSERT(a_Range <= 1000000); // The random is not sufficiently linearly distributed with bigger ranges ASSERT(a_Range > 0); // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, m_Counter and m_Seed as inputs to the pseudorandom function: int n = a_Range + Counter * 57 + m_Seed * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); return ((n / 11) % a_Range); } int cFastRandom::NextInt(int a_Range, int a_Salt) { ASSERT(a_Range <= 1000000); // The random is not sufficiently linearly distributed with bigger ranges ASSERT(a_Range > 0); // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, a_Salt, m_Counter and m_Seed as inputs to the pseudorandom function: int n = a_Range + Counter * 57 + m_Seed * 57 * 57 + a_Salt * 57 * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); return ((n / 11) % a_Range); } float cFastRandom::NextFloat(float a_Range) { // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, a_Salt, m_Counter and m_Seed as inputs to the pseudorandom function: int n = (int)a_Range + Counter * 57 + m_Seed * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); // Convert the integer into float with the specified range: return (((float)n / (float)0x7fffffff) * a_Range); } float cFastRandom::NextFloat(float a_Range, int a_Salt) { // Make the m_Counter operations as minimal as possible, to emulate atomicity int Counter = m_Counter++; // Use a_Range, a_Salt, m_Counter and m_Seed as inputs to the pseudorandom function: int n = (int)a_Range + Counter * 57 + m_Seed * 57 * 57 + a_Salt * 57 * 57 * 57; n = (n << 13) ^ n; n = ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff); // Convert the integer into float with the specified range: return (((float)n / (float)0x7fffffff) * a_Range); } <|endoftext|>
<commit_before>/* * For licensing please refer to the LICENSE.md file */ #include "GmshReader.hpp" #include "GmshReaderException.hpp" #include <algorithm> #include <chrono> #include <fstream> #include <iomanip> #include <iostream> #include <numeric> #include <json/json.h> namespace gmsh { Reader::Reader(std::string const& input_file_name, NodalOrdering const ordering, IndexingBase const base, distributed const distributed_option) : input_file_name(input_file_name), useZeroBasedIndexing(base == IndexingBase::Zero), useLocalNodalConnectivity(ordering == NodalOrdering::Local), is_feti_format(distributed_option == distributed::feti) { fillMesh(); } void Reader::fillMesh() { auto const start = std::chrono::high_resolution_clock::now(); std::fstream gmsh_file(input_file_name); if (!gmsh_file.is_open()) { throw GmshReaderException("Input file " + input_file_name + " was not able to be opened"); } std::string token, null; // Loop around file and read in keyword tokens while (!gmsh_file.eof()) { gmsh_file >> token; if (token == "$MeshFormat") { float gmshVersion; // File format version std::int32_t dataType; // Precision gmsh_file >> gmshVersion >> dataType >> null; checkSupportedGmsh(gmshVersion); } else if (token == "$PhysicalNames") { std::string physical_name; std::int32_t physicalIds; gmsh_file >> physicalIds; for (auto i = 0; i < physicalIds; ++i) { std::int32_t dimension, physicalId; gmsh_file >> dimension >> physicalId >> physical_name; // Extract the name from the quotes physical_name.erase(std::remove(physical_name.begin(), physical_name.end(), '\"'), physical_name.end()); physicalGroupMap.emplace(physicalId, physical_name); } token.clear(); gmsh_file >> token; } else if (token == "$Nodes") { std::int64_t number_of_nodes; gmsh_file >> number_of_nodes; nodal_data.resize(number_of_nodes); for (auto& node : nodal_data) { gmsh_file >> node.id >> node.coordinates[0] >> node.coordinates[1] >> node.coordinates[2]; } } else if (token == "$Elements") { int elementIds; gmsh_file >> elementIds; for (int elementId = 0; elementId < elementIds; elementId++) { int id = 0, numberOfTags = 0, elementTypeId = 0; gmsh_file >> id >> elementTypeId >> numberOfTags; auto const numberOfNodes = mapElementData(elementTypeId); list tags(numberOfTags, 0); list nodalConnectivity(numberOfNodes, 0); for (auto& tag : tags) { gmsh_file >> tag; } for (auto& nodeId : nodalConnectivity) { gmsh_file >> nodeId; } auto const physicalId = tags[0]; ElementData elementData(nodalConnectivity, tags, elementTypeId, id); // Update the total number of partitions on the fly number_of_partitions = std::max(elementData.maxProcessId(), number_of_partitions); // Copy the element data into the mesh structure meshes[{physicalGroupMap[physicalId], elementTypeId}].push_back(elementData); if (elementData.isSharedByMultipleProcesses()) { for (int i = 4; i < tags[2] + 3; ++i) { auto const owner_sharer = std::make_pair(tags[3], std::abs(tags[i])); auto const& connectivity = elementData.nodalConnectivity(); interfaceElementMap[owner_sharer].insert(std::begin(connectivity), std::end(connectivity)); } } } } } std::cout << std::string(2, ' ') << "A total number of " << number_of_partitions << " partitions was found\n"; auto const end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "Mesh data structure filled in " << elapsed_seconds.count() << "s\n"; } int Reader::mapElementData(int const elementTypeId) { // Return the number of local nodes per element switch (elementTypeId) { case LINE2: return 2; break; case TRIANGLE3: return 3; break; case QUADRILATERAL4: return 4; break; case TETRAHEDRON4: return 4; break; case HEXAHEDRON8: return 8; break; case PRISM6: return 6; break; case PYRAMID5: return 5; break; case LINE3: return 3; break; case TRIANGLE6: return 6; break; case QUADRILATERAL9: return 9; break; case TETRAHEDRON10: return 10; break; case HEXAHEDRON27: return 27; break; case PRISM18: return 18; break; case PYRAMID14: return 14; break; case POINT: return 1; break; case QUADRILATERAL8: return 8; break; case HEXAHEDRON20: return 20; break; case PRISM15: return 15; break; case PYRAMID13: return 13; break; case TRIANGLE9: return 19; break; case TRIANGLE10: return 10; break; case TRIANGLE12: return 12; break; case TRIANGLE15: return 15; break; case TRIANGLE15_IC: return 15; break; case TRIANGLE21: return 21; break; case EDGE4: return 4; break; case EDGE5: return 5; break; case EDGE6: return 6; break; case TETRAHEDRON20: return 20; break; case TETRAHEDRON35: return 35; break; case TETRAHEDRON56: return 56; break; case HEXAHEDRON64: return 64; break; case HEXAHEDRON125: return 125; break; default: throw GmshReaderException("The elementTypeId " + std::to_string(elementTypeId) + " is not implemented"); } return -1; } void Reader::checkSupportedGmsh(float const gmshVersion) { if (gmshVersion < 2.2) { throw std::runtime_error("GmshVersion " + std::to_string(gmshVersion) + " is not supported"); } } void Reader::writeMeshToJson(bool const print_indices) const { for (auto partition = 0; partition < number_of_partitions; ++partition) { Mesh process_mesh; // Find all of the elements which belong to this process for (auto const& mesh : meshes) { // Copy the elements into the process mesh for (auto const& element : mesh.second) { if (element.isOwnedByProcess(partition + 1)) { process_mesh[mesh.first].push_back(element); } } } auto local_global_mapping = fillLocalToGlobalMap(process_mesh); auto local_nodes = fillLocalNodeList(local_global_mapping); if (useLocalNodalConnectivity) { reorderLocalMesh(process_mesh, local_global_mapping); } // Check if this local mesh needs to be converted to zero based indexing // then correct the nodal connectivities, the mappings and the nodal and // element ids of the data structures if (useZeroBasedIndexing) { for (auto& l2g : local_global_mapping) --l2g; for (auto& localNode : local_nodes) --localNode.id; for (auto& mesh : process_mesh) { for (auto& element : mesh.second) { element.convertToZeroBasedIndexing(); } } } writeInJsonFormat(process_mesh, local_global_mapping, local_nodes, partition, number_of_partitions > 1, print_indices); std::cout << std::string(2, ' ') << "Finished writing out JSON file for mesh partition " << partition << "\n"; } } list Reader::fillLocalToGlobalMap(Mesh const& process_mesh) const { list local_global_mapping; for (auto const& mesh : process_mesh) { for (auto const& element : mesh.second) { auto const& nodes = element.nodalConnectivity(); std::copy(std::begin(nodes), std::end(nodes), std::back_inserter(local_global_mapping)); } } // Sort and remove duplicates std::sort(std::begin(local_global_mapping), std::end(local_global_mapping)); local_global_mapping.erase(std::unique(std::begin(local_global_mapping), std::end(local_global_mapping)), std::end(local_global_mapping)); return local_global_mapping; } void Reader::reorderLocalMesh(Mesh& process_mesh, list const& local_global_mapping) const { for (auto& mesh : process_mesh) { for (auto& element : mesh.second) { for (auto& node : element.nodalConnectivity()) { auto const found = std::lower_bound(std::begin(local_global_mapping), std::end(local_global_mapping), node); // Reset the node value to that inside the local ordering with // the default of one based ordering node = std::distance(local_global_mapping.begin(), found) + 1; } } } } std::vector<NodeData> Reader::fillLocalNodeList(list const& local_global_mapping) const { std::vector<NodeData> local_nodal_data; local_nodal_data.reserve(local_global_mapping.size()); for (auto const& node_index : local_global_mapping) { local_nodal_data.emplace_back(nodal_data[node_index - 1]); } return local_nodal_data; } void Reader::writeInJsonFormat(Mesh const& process_mesh, list const& localToGlobalMapping, std::vector<NodeData> const& nodalCoordinates, int const partition_number, bool const is_decomposed, bool const print_indices) const { // Write out each file to Json format Json::Value event; std::string output_file_name = input_file_name.substr(0, input_file_name.find_last_of(".")) + ".mesh"; if (is_decomposed) output_file_name += std::to_string(partition_number); std::fstream writer; writer.open(output_file_name, std::ios::out); // Write out the nodal coordinates Json::Value nodeGroup; auto& nodeGroupCoordinates = nodeGroup["Coordinates"]; for (auto const& node : nodalCoordinates) { Json::Value coordinates(Json::arrayValue); for (auto const& xyz : node.coordinates) { coordinates.append(Json::Value(xyz)); } nodeGroupCoordinates.append(coordinates); if (print_indices) nodeGroup["Indices"].append(node.id); } event["Nodes"].append(nodeGroup); for (auto const& mesh : process_mesh) { Json::Value elementGroup; auto& elementGroupNodalConnectivity = elementGroup["NodalConnectivity"]; for (auto const& element_data : mesh.second) { Json::Value connectivity(Json::arrayValue); for (auto const& node : element_data.nodalConnectivity()) { connectivity.append(node); } elementGroupNodalConnectivity.append(connectivity); if (print_indices) elementGroup["Indices"].append(element_data.id()); } elementGroup["Name"] = mesh.first.first; elementGroup["Type"] = mesh.first.second; event["Elements"].append(elementGroup); } if (is_decomposed) { auto& eventLocalToGlobalMap = event["LocalToGlobalMap"]; for (auto const& l2g : localToGlobalMapping) { eventLocalToGlobalMap.append(l2g); } if (is_feti_format) { long globalStartId{0l}; for (auto const& interface : interfaceElementMap) { auto const master_partition = interface.first.first; auto const slave_partition = interface.first.second; if (master_partition < slave_partition) { std::set<std::int64_t> intersection; auto const& v1 = interface.second; auto const& v2 = interfaceElementMap.at({slave_partition, master_partition}); std::set_intersection(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2), std::inserter(intersection, std::begin(intersection))); if (partition_number == master_partition - 1 or partition_number == slave_partition - 1) { Json::Value interface_group, nodal_numbers; for (auto const& node_number : intersection) nodal_numbers.append(node_number); interface_group["NodeIds"].append(nodal_numbers); interface_group["Master"] = useZeroBasedIndexing ? master_partition - 1 : master_partition; interface_group["Slave"] = useZeroBasedIndexing ? slave_partition - 1 : slave_partition; interface_group["Value"] = partition_number == master_partition - 1 ? 1 : -1; interface_group["GlobalStartId"] = globalStartId; event["Interface"].append(interface_group); } globalStartId += intersection.size(); } } event["NumInterfaceNodes"] = globalStartId; } else { for (auto const& interface : interfaceElementMap) { auto const master_partition = interface.first.first; auto const slave_partition = interface.first.second; if (partition_number == slave_partition - 1) { std::set<std::int64_t> intersection; // Find the common indices between the master and the slave // partition and print these out for each process interface auto const& v1 = interface.second; auto const& v2 = interfaceElementMap.at({slave_partition, master_partition}); std::set_intersection(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2), std::inserter(intersection, std::begin(intersection))); Json::Value interface_group, nodal_numbers; for (auto const& node_number : intersection) { nodal_numbers.append(useZeroBasedIndexing ? node_number - 1 : node_number); } interface_group["Indices"] = nodal_numbers; interface_group["Process"] = useZeroBasedIndexing ? master_partition - 1 : master_partition; event["Interface"].append(interface_group); } } } } Json::StyledWriter jsonwriter; writer << jsonwriter.write(event); writer.close(); } } <commit_msg>Use move to avoid copy<commit_after>/* * For licensing please refer to the LICENSE.md file */ #include "GmshReader.hpp" #include "GmshReaderException.hpp" #include <algorithm> #include <chrono> #include <fstream> #include <iomanip> #include <iostream> #include <numeric> #include <json/json.h> namespace gmsh { Reader::Reader(std::string const& input_file_name, NodalOrdering const ordering, IndexingBase const base, distributed const distributed_option) : input_file_name(input_file_name), useZeroBasedIndexing(base == IndexingBase::Zero), useLocalNodalConnectivity(ordering == NodalOrdering::Local), is_feti_format(distributed_option == distributed::feti) { fillMesh(); } void Reader::fillMesh() { auto const start = std::chrono::high_resolution_clock::now(); std::fstream gmsh_file(input_file_name); if (!gmsh_file.is_open()) { throw GmshReaderException("Input file " + input_file_name + " was not able to be opened"); } std::string token, null; // Loop around file and read in keyword tokens while (!gmsh_file.eof()) { gmsh_file >> token; if (token == "$MeshFormat") { float gmshVersion; // File format version std::int32_t dataType; // Precision gmsh_file >> gmshVersion >> dataType >> null; checkSupportedGmsh(gmshVersion); } else if (token == "$PhysicalNames") { std::string physical_name; std::int32_t physicalIds; gmsh_file >> physicalIds; for (auto i = 0; i < physicalIds; ++i) { std::int32_t dimension, physicalId; gmsh_file >> dimension >> physicalId >> physical_name; // Extract the name from the quotes physical_name.erase(std::remove(physical_name.begin(), physical_name.end(), '\"'), physical_name.end()); physicalGroupMap.emplace(physicalId, physical_name); } token.clear(); gmsh_file >> token; } else if (token == "$Nodes") { std::int64_t number_of_nodes; gmsh_file >> number_of_nodes; nodal_data.resize(number_of_nodes); for (auto& node : nodal_data) { gmsh_file >> node.id >> node.coordinates[0] >> node.coordinates[1] >> node.coordinates[2]; } } else if (token == "$Elements") { int elementIds; gmsh_file >> elementIds; for (int elementId = 0; elementId < elementIds; elementId++) { int id = 0, numberOfTags = 0, elementTypeId = 0; gmsh_file >> id >> elementTypeId >> numberOfTags; auto const numberOfNodes = mapElementData(elementTypeId); list tags(numberOfTags, 0); list nodalConnectivity(numberOfNodes, 0); for (auto& tag : tags) { gmsh_file >> tag; } for (auto& nodeId : nodalConnectivity) { gmsh_file >> nodeId; } auto const physicalId = tags[0]; ElementData elementData(std::move(nodalConnectivity), tags, elementTypeId, id); // Update the total number of partitions on the fly number_of_partitions = std::max(elementData.maxProcessId(), number_of_partitions); // Copy the element data into the mesh structure meshes[{physicalGroupMap[physicalId], elementTypeId}].push_back(elementData); if (elementData.isSharedByMultipleProcesses()) { for (int i = 4; i < tags[2] + 3; ++i) { auto const owner_sharer = std::make_pair(tags[3], std::abs(tags[i])); auto const& connectivity = elementData.nodalConnectivity(); interfaceElementMap[owner_sharer].insert(std::begin(connectivity), std::end(connectivity)); } } } } } std::cout << std::string(2, ' ') << "A total number of " << number_of_partitions << " partitions was found\n"; auto const end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "Mesh data structure filled in " << elapsed_seconds.count() << "s\n"; } int Reader::mapElementData(int const elementTypeId) { // Return the number of local nodes per element switch (elementTypeId) { case LINE2: return 2; break; case TRIANGLE3: return 3; break; case QUADRILATERAL4: return 4; break; case TETRAHEDRON4: return 4; break; case HEXAHEDRON8: return 8; break; case PRISM6: return 6; break; case PYRAMID5: return 5; break; case LINE3: return 3; break; case TRIANGLE6: return 6; break; case QUADRILATERAL9: return 9; break; case TETRAHEDRON10: return 10; break; case HEXAHEDRON27: return 27; break; case PRISM18: return 18; break; case PYRAMID14: return 14; break; case POINT: return 1; break; case QUADRILATERAL8: return 8; break; case HEXAHEDRON20: return 20; break; case PRISM15: return 15; break; case PYRAMID13: return 13; break; case TRIANGLE9: return 19; break; case TRIANGLE10: return 10; break; case TRIANGLE12: return 12; break; case TRIANGLE15: return 15; break; case TRIANGLE15_IC: return 15; break; case TRIANGLE21: return 21; break; case EDGE4: return 4; break; case EDGE5: return 5; break; case EDGE6: return 6; break; case TETRAHEDRON20: return 20; break; case TETRAHEDRON35: return 35; break; case TETRAHEDRON56: return 56; break; case HEXAHEDRON64: return 64; break; case HEXAHEDRON125: return 125; break; default: throw GmshReaderException("The elementTypeId " + std::to_string(elementTypeId) + " is not implemented"); } return -1; } void Reader::checkSupportedGmsh(float const gmshVersion) { if (gmshVersion < 2.2) { throw std::runtime_error("GmshVersion " + std::to_string(gmshVersion) + " is not supported"); } } void Reader::writeMeshToJson(bool const print_indices) const { for (auto partition = 0; partition < number_of_partitions; ++partition) { Mesh process_mesh; // Find all of the elements which belong to this process for (auto const& mesh : meshes) { // Copy the elements into the process mesh for (auto const& element : mesh.second) { if (element.isOwnedByProcess(partition + 1)) { process_mesh[mesh.first].push_back(element); } } } auto local_global_mapping = fillLocalToGlobalMap(process_mesh); auto local_nodes = fillLocalNodeList(local_global_mapping); if (useLocalNodalConnectivity) { reorderLocalMesh(process_mesh, local_global_mapping); } // Check if this local mesh needs to be converted to zero based indexing // then correct the nodal connectivities, the mappings and the nodal and // element ids of the data structures if (useZeroBasedIndexing) { for (auto& l2g : local_global_mapping) --l2g; for (auto& localNode : local_nodes) --localNode.id; for (auto& mesh : process_mesh) { for (auto& element : mesh.second) { element.convertToZeroBasedIndexing(); } } } writeInJsonFormat(process_mesh, local_global_mapping, local_nodes, partition, number_of_partitions > 1, print_indices); std::cout << std::string(2, ' ') << "Finished writing out JSON file for mesh partition " << partition << "\n"; } } list Reader::fillLocalToGlobalMap(Mesh const& process_mesh) const { list local_global_mapping; for (auto const& mesh : process_mesh) { for (auto const& element : mesh.second) { auto const& nodes = element.nodalConnectivity(); std::copy(std::begin(nodes), std::end(nodes), std::back_inserter(local_global_mapping)); } } // Sort and remove duplicates std::sort(std::begin(local_global_mapping), std::end(local_global_mapping)); local_global_mapping.erase(std::unique(std::begin(local_global_mapping), std::end(local_global_mapping)), std::end(local_global_mapping)); return local_global_mapping; } void Reader::reorderLocalMesh(Mesh& process_mesh, list const& local_global_mapping) const { for (auto& mesh : process_mesh) { for (auto& element : mesh.second) { for (auto& node : element.nodalConnectivity()) { auto const found = std::lower_bound(std::begin(local_global_mapping), std::end(local_global_mapping), node); // Reset the node value to that inside the local ordering with // the default of one based ordering node = std::distance(local_global_mapping.begin(), found) + 1; } } } } std::vector<NodeData> Reader::fillLocalNodeList(list const& local_global_mapping) const { std::vector<NodeData> local_nodal_data; local_nodal_data.reserve(local_global_mapping.size()); for (auto const& node_index : local_global_mapping) { local_nodal_data.emplace_back(nodal_data[node_index - 1]); } return local_nodal_data; } void Reader::writeInJsonFormat(Mesh const& process_mesh, list const& localToGlobalMapping, std::vector<NodeData> const& nodalCoordinates, int const partition_number, bool const is_decomposed, bool const print_indices) const { // Write out each file to Json format Json::Value event; std::string output_file_name = input_file_name.substr(0, input_file_name.find_last_of('.')) + ".mesh"; if (is_decomposed) output_file_name += std::to_string(partition_number); std::fstream writer; writer.open(output_file_name, std::ios::out); // Write out the nodal coordinates Json::Value nodeGroup; auto& nodeGroupCoordinates = nodeGroup["Coordinates"]; for (auto const& node : nodalCoordinates) { Json::Value coordinates(Json::arrayValue); for (auto const& xyz : node.coordinates) { coordinates.append(Json::Value(xyz)); } nodeGroupCoordinates.append(coordinates); if (print_indices) nodeGroup["Indices"].append(node.id); } event["Nodes"].append(nodeGroup); for (auto const& mesh : process_mesh) { Json::Value elementGroup; auto& elementGroupNodalConnectivity = elementGroup["NodalConnectivity"]; for (auto const& element_data : mesh.second) { Json::Value connectivity(Json::arrayValue); for (auto const& node : element_data.nodalConnectivity()) { connectivity.append(node); } elementGroupNodalConnectivity.append(connectivity); if (print_indices) elementGroup["Indices"].append(element_data.id()); } elementGroup["Name"] = mesh.first.first; elementGroup["Type"] = mesh.first.second; event["Elements"].append(elementGroup); } if (is_decomposed) { auto& eventLocalToGlobalMap = event["LocalToGlobalMap"]; for (auto const& l2g : localToGlobalMapping) { eventLocalToGlobalMap.append(l2g); } if (is_feti_format) { long globalStartId{0l}; for (auto const& interface : interfaceElementMap) { auto const master_partition = interface.first.first; auto const slave_partition = interface.first.second; if (master_partition < slave_partition) { std::set<std::int64_t> intersection; auto const& v1 = interface.second; auto const& v2 = interfaceElementMap.at({slave_partition, master_partition}); std::set_intersection(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2), std::inserter(intersection, std::begin(intersection))); if (partition_number == master_partition - 1 or partition_number == slave_partition - 1) { Json::Value interface_group, nodal_numbers; for (auto const& node_number : intersection) nodal_numbers.append(node_number); interface_group["NodeIds"].append(nodal_numbers); interface_group["Master"] = useZeroBasedIndexing ? master_partition - 1 : master_partition; interface_group["Slave"] = useZeroBasedIndexing ? slave_partition - 1 : slave_partition; interface_group["Value"] = partition_number == master_partition - 1 ? 1 : -1; interface_group["GlobalStartId"] = globalStartId; event["Interface"].append(interface_group); } globalStartId += intersection.size(); } } event["NumInterfaceNodes"] = globalStartId; } else { for (auto const& interface : interfaceElementMap) { auto const master_partition = interface.first.first; auto const slave_partition = interface.first.second; if (partition_number == slave_partition - 1) { std::set<std::int64_t> intersection; // Find the common indices between the master and the slave // partition and print these out for each process interface auto const& v1 = interface.second; auto const& v2 = interfaceElementMap.at({slave_partition, master_partition}); std::set_intersection(std::begin(v1), std::end(v1), std::begin(v2), std::end(v2), std::inserter(intersection, std::begin(intersection))); Json::Value interface_group, nodal_numbers; for (auto const& node_number : intersection) { nodal_numbers.append(useZeroBasedIndexing ? node_number - 1 : node_number); } interface_group["Indices"] = nodal_numbers; interface_group["Process"] = useZeroBasedIndexing ? master_partition - 1 : master_partition; event["Interface"].append(interface_group); } } } } Json::StyledWriter jsonwriter; writer << jsonwriter.write(event); writer.close(); } } <|endoftext|>
<commit_before>/************************************************************************* > File Name: CardLoader.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Card loader that loads data from cards.json. > Created Time: 2017/08/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Loaders/CardLoader.h> #include <Models/Entities/Enchantment.h> #include <Models/Entities/Hero.h> #include <Models/Entities/HeroPower.h> #include <Models/Entities/Minion.h> #include <Models/Entities/Spell.h> #include <Models/Entities/Weapon.h> #include <fstream> namespace Hearthstonepp { std::vector<Card*> CardLoader::Load() const { // Read card data from JSON file std::ifstream cardFile(RESOURCES_DIR "cards.json"); json j; if (!cardFile.is_open()) { throw std::runtime_error("Can't open cards.json"); } cardFile >> j; std::vector<Card*> cards; cards.reserve(j.size()); for (auto& card : j) { const std::string id = card["id"].get<std::string>(); const Rarity rarity = card["rarity"].is_null() ? +Rarity::FREE : std::move(Rarity::_from_string(card["rarity"].get<std::string>().c_str())); const Faction faction = card["faction"].is_null() ? +Faction::NEUTRAL : std::move(Faction::_from_string(card["faction"].get<std::string>().c_str())); const CardSet cardSet = card["set"].is_null() ? +CardSet::NONE : std::move(CardSet::_from_string(card["set"].get<std::string>().c_str())); const CardClass cardClass = card["cardClass"].is_null() ? +CardClass::NEUTRAL : std::move(CardClass::_from_string(card["cardClass"].get<std::string>().c_str())); const CardType cardType = card["type"].is_null() ? +CardType::INVALID : std::move(CardType::_from_string(card["type"].get<std::string>().c_str())); const Race race = card["race"].is_null() ? +Race::INVALID : std::move(Race::_from_string(card["race"].get<std::string>().c_str())); const std::string name = card["name"].is_null() ? "" : card["name"]["enUS"].get<std::string>(); const std::string text = card["text"].is_null() ? "" : card["text"]["enUS"].get<std::string>(); const bool collectible = card["collectible"].is_null() ? false : card["collectible"].get<bool>(); const int cost = card["cost"].is_null() ? -1 : card["cost"].get<int>(); const int attack = card["attack"].is_null() ? -1 : card["attack"].get<int>(); const int health = card["health"].is_null() ? -1 : card["health"].get<int>(); const int durability = card["durability"].is_null() ? -1 : card["durability"].get<int>(); std::vector<GameTag> mechanics; for (auto& mechanic : card["mechanics"]) { mechanics.emplace_back(std::move(GameTag::_from_string(mechanic.get<std::string>().c_str()))); } std::map<PlayReq, int> playRequirements; for (auto iter = card["playRequirements"].begin(); iter != card["playRequirements"].end(); ++iter) { playRequirements.try_emplace(std::move(PlayReq::_from_string(iter.key().c_str())), iter.value().get<int>()); } std::vector<std::string> entourages; for (auto& entourage : card["entourage"]) { entourages.emplace_back(entourage.get<std::string>()); } Card* c; switch (cardType) { case CardType::HERO: c = new Hero( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::MINION: c = new Minion( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::SPELL: c = new Spell( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::ENCHANTMENT: c = new Enchantment( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::WEAPON: c = new Weapon( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::HERO_POWER: c = new HeroPower( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; default: // TODO: Log invalid card type break; } cards.emplace_back(c); } cardFile.close(); return cards; } }<commit_msg>Fix 'pessimizing move' warning message<commit_after>/************************************************************************* > File Name: CardLoader.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Card loader that loads data from cards.json. > Created Time: 2017/08/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Loaders/CardLoader.h> #include <Models/Entities/Enchantment.h> #include <Models/Entities/Hero.h> #include <Models/Entities/HeroPower.h> #include <Models/Entities/Minion.h> #include <Models/Entities/Spell.h> #include <Models/Entities/Weapon.h> #include <fstream> namespace Hearthstonepp { std::vector<Card*> CardLoader::Load() const { // Read card data from JSON file std::ifstream cardFile(RESOURCES_DIR "cards.json"); json j; if (!cardFile.is_open()) { throw std::runtime_error("Can't open cards.json"); } cardFile >> j; std::vector<Card*> cards; cards.reserve(j.size()); for (auto& card : j) { const std::string id = card["id"].get<std::string>(); const Rarity rarity = card["rarity"].is_null() ? +Rarity::FREE : Rarity::_from_string(card["rarity"].get<std::string>().c_str()); const Faction faction = card["faction"].is_null() ? +Faction::NEUTRAL : Faction::_from_string(card["faction"].get<std::string>().c_str()); const CardSet cardSet = card["set"].is_null() ? +CardSet::NONE : CardSet::_from_string(card["set"].get<std::string>().c_str()); const CardClass cardClass = card["cardClass"].is_null() ? +CardClass::NEUTRAL : CardClass::_from_string(card["cardClass"].get<std::string>().c_str()); const CardType cardType = card["type"].is_null() ? +CardType::INVALID : CardType::_from_string(card["type"].get<std::string>().c_str()); const Race race = card["race"].is_null() ? +Race::INVALID : Race::_from_string(card["race"].get<std::string>().c_str()); const std::string name = card["name"].is_null() ? "" : card["name"]["enUS"].get<std::string>(); const std::string text = card["text"].is_null() ? "" : card["text"]["enUS"].get<std::string>(); const bool collectible = card["collectible"].is_null() ? false : card["collectible"].get<bool>(); const int cost = card["cost"].is_null() ? -1 : card["cost"].get<int>(); const int attack = card["attack"].is_null() ? -1 : card["attack"].get<int>(); const int health = card["health"].is_null() ? -1 : card["health"].get<int>(); const int durability = card["durability"].is_null() ? -1 : card["durability"].get<int>(); std::vector<GameTag> mechanics; for (auto& mechanic : card["mechanics"]) { mechanics.emplace_back(GameTag::_from_string(mechanic.get<std::string>().c_str())); } std::map<PlayReq, int> playRequirements; for (auto iter = card["playRequirements"].begin(); iter != card["playRequirements"].end(); ++iter) { playRequirements.try_emplace(PlayReq::_from_string(iter.key().c_str())), iter.value().get<int>(); } std::vector<std::string> entourages; for (auto& entourage : card["entourage"]) { entourages.emplace_back(entourage.get<std::string>()); } Card* c; switch (cardType) { case CardType::HERO: c = new Hero( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::MINION: c = new Minion( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::SPELL: c = new Spell( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::ENCHANTMENT: c = new Enchantment( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::WEAPON: c = new Weapon( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::HERO_POWER: c = new HeroPower( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; default: // TODO: Log invalid card type break; } cards.emplace_back(c); } cardFile.close(); return cards; } }<|endoftext|>
<commit_before>/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2004 Ingo Ralf Blum. All rights reserved. ** ** 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 Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id: IOCallback.cpp 639 2004-07-09 20:59:14Z mosu $ \author Steve Lhomme <robux4 @ users.sf.net> \author Moritz Bunkus <moritz @ bunkus.org> */ #include <sstream> #include <stdexcept> #include "ebml/IOCallback.h" using namespace std; namespace libebml { void IOCallback::writeFully(const void*Buffer,size_t Size) { if (Size == 0) return; if (Buffer == nullptr) throw; if(write(Buffer,Size) != Size) { stringstream Msg; Msg<<"EOF in writeFully("<<Buffer<<","<<Size<<")"; throw runtime_error(Msg.str()); } } void IOCallback::readFully(void*Buffer,size_t Size) { if(Buffer == nullptr) throw; if(read(Buffer,Size) != Size) { stringstream Msg; Msg<<"EOF in readFully("<<Buffer<<","<<Size<<")"; throw runtime_error(Msg.str()); } } } // namespace libebml <commit_msg>IOCallback: avoid reading more than 2^32 at once<commit_after>/**************************************************************************** ** libebml : parse EBML files, see http://embl.sourceforge.net/ ** ** <file/class description> ** ** Copyright (C) 2002-2004 Ingo Ralf Blum. All rights reserved. ** ** 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 Street, Fifth Floor, Boston, MA 02110-1301 USA ** ** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information. ** ** Contact [email protected] if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ /*! \file \version \$Id: IOCallback.cpp 639 2004-07-09 20:59:14Z mosu $ \author Steve Lhomme <robux4 @ users.sf.net> \author Moritz Bunkus <moritz @ bunkus.org> */ #include <limits> #include <sstream> #include <stdexcept> #include "ebml/IOCallback.h" using namespace std; namespace libebml { void IOCallback::writeFully(const void*Buffer,size_t Size) { if (Size == 0) return; if (Buffer == nullptr) throw; if(write(Buffer,Size) != Size) { stringstream Msg; Msg<<"EOF in writeFully("<<Buffer<<","<<Size<<")"; throw runtime_error(Msg.str()); } } void IOCallback::readFully(void*Buffer,size_t Size) { if(Buffer == nullptr) throw; char *readBuf = static_cast<char *>(Buffer); uint32_t readSize = static_cast<uint32_t>(std::min<size_t>(std::numeric_limits<uint32>::max(), Size)); while (readSize != 0) { if(read(readBuf,readSize) != readSize) { stringstream Msg; Msg<<"EOF in readFully("<<Buffer<<","<<Size<<")"; throw runtime_error(Msg.str()); } Size -= readSize; readBuf += readSize; readSize = static_cast<uint32_t>(std::min<size_t>(std::numeric_limits<uint32>::max(), Size)); } } } // namespace libebml <|endoftext|>